I am working with stream signup is working with status 200 but did not create user in stream - axios

const handleSubmit = async (e) => {
e.preventDefault();
const { username, password, phoneNumber, avatarURL } = form;
const URL = 'http://localhost:5000/auth';
const { data: { token, userId, hashedPassword, fullName } } = await axios.post(`${URL}/${isSignup ? 'signup' : 'login'}`, {
username, password, fullName: form.fu
llName, phoneNumber, avatarURL,
});

Related

how can we store the response to local storage which comes from post api in NEXT.JS

Here is my post function which is posting data
const submitHandler = async (e) => {
e.preventDefault();
setLoading(true);
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
toast.warning("Please Fill all the Fields", {
position: "bottom-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
progress: undefined,
theme: "light",
bodyClassName: 'font-bold'
});
setTimeout(() => {
setLoading(false)
}, 2000);
return;
}
if (password !== confirmpassword) {
toast.warning("Passwords not Matched", {
position: "bottom-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
progress: undefined,
theme: "light",
});
setTimeout(() => {
setLoading(false)
}, 2000);
return;
}
try {
const config = {
headers: {
"Content-type":"application/json"
}
}
const { dev } = await axios.post("/api/registerteacher", {
name,
phone,
email,
gender,
password,
confirmpassword,
pic,
},config);
toast.success("Registration Succesfull", {
position: "bottom-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
progress: undefined,
theme: "dark",
});
console.log(dev)
localStorage.setItem("teacherinfo", JSON.stringify(dev));
setLoading(false);
router.replace("/teacher/selectcategory");
} catch (error) {
toast.error("Error Occured, Try Again Later", {
position: "bottom-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
progress: undefined,
theme: "dark",
className:"rounded-full"
});
setLoading(true);
}
};
In the above function I am taking the data from the register page. data is name, email, phone, password and confirm password and there are some validations at the front end and if data is not validate the showing the toast by react toastify and after vaidation i am posting the data to the backend by axios and storing the response in dev variable and store the dev variable in localstorage but i am getting the dev as undefined from the backend.
Here my backend code looks like:
import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;
In backend the frontend data is storing in mongo db and send the respone too. but still the dev is undefined.
Here is my respone looks like
{
"_id": "63c8085ed8a4774dc48c68c6",
"name": "joe don",
"email": "john#gmail.com",
"phone": "6350330324",
"pic": "https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzYzgwODVlZDhhNDc3NGRjNDhjNjhjNiIsImlhdCI6MTY3NDA1MzczMiwiZXhwIjoxNjc2NjQ1NzMyfQ.ejS4PlsmQhS4Avu8Vo6B7RmuEhlhhGI2hPRRwQRCsyE"
}
Please Help me I am Stucked in this problem
How can i store the response (dev) in localstorge to use for put request

Next-Auth CredentialsProvider really slow

The following works fine, but I have noticed that it is really slow login in a client. How can I make it faster?
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import { ObjectId } from 'mongodb'
import { MongoDBAdapter } from "#next-auth/mongodb-adapter"
import clientPromise from "../../../lib/mongodb";
import { v4 as uuidv4 } from 'uuid';
var CryptoJS = require("crypto-js");
const sFinder = async (task, token) => {
try{
const client = await clientPromise;
const database = client.db('DRN1');
const ses = await database.collection('sessions');
switch (task) {
case 1:
const result = await ses.find({
"userId": ObjectId(token.uuid)
}).sort({"_id":-1}).limit(1).toArray();
if (!result) {
return 202;
}
else{
return result[0].sessionToken
}
break;
case 2:
const insertResult = await ses.insertOne({"userId":token.uuid, "sessionToken":token.accessToken});
if (!insertResult) {
return 203;
}
else{
return insertResult
}
break;
case 3:
var expdate = new Date(token.exp * 1000);
const UpdateResult = await ses.updateOne({"userId":ObjectId(token.uuid), "sessionToken":token.accessToken},
{ $set: {"expires": expdate}}, { upsert: true });
if (!UpdateResult) {
return 203;
}
else{
return UpdateResult
}
break;
default:
break;
}
} catch(e){
console.error(e);
}
}
export default NextAuth({
adapter: MongoDBAdapter(clientPromise),
session: {
strategy: 'jwt',
jwt: true,
},
providers: [
CredentialsProvider({
name: 'DRN1',
credentials: {
username: { label: "Username", type: "text"},
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
try{
const client = await clientPromise;
const database = client.db('DRN1');
const users = await database.collection('users');
const result = await users.findOne({
username: credentials.username,
});
if (!result) {
throw new Error('No user found with the username');
}
var bytes = CryptoJS.AES.decrypt(result.password, process.env.PASS_ENC);
var decryptedData = bytes.toString(CryptoJS.enc.Utf8);
//Check hased password with DB password
if(decryptedData != credentials.password){
throw new Error('Password doesnt match');
}
return {uuid:result._id, username: result.username, email: result.email, type:result.type, "sessionID":uuidv4()};
} catch(e){
console.error(e)
}
}
})
],
callbacks: {
signIn: async ({ user, account, profile, email, credentials }) => {
account.accessToken = user.sessionID
account.uuid = user.uuid
const test = await sFinder(2,account)
return true
},
jwt: async ({ token, account }) => {
if (account) {
token.uuid = account.uuid
token.accessToken = account.accessToken
}
const lastUsedToken = await sFinder(1,token)
const updateTokenExpire = await sFinder(3,token)
if(lastUsedToken != token.accessToken){
// console.log("I have made it an error")
token.error = 555;
}
return token
},
session: async ({ session, token, user }) => {
session.uuid = token.uuid
if(!token.accessToken){
//OAUTH Accounts
session.accessToken = uuidv4()
}else{
session.accessToken = token.accessToken
}
if(token.error == 555){
session.error = 555
}
return session
}
},
pages:{
error: 'signin'
},
theme: {
colorScheme: "dark", // "auto" | "dark" | "light"
brandColor: "", // Hex color code
logo: "https://storage.googleapis.com/radiomedia-images/station_logos/v2/DRN1_small.png" // Absolute URL to image
}
});
I believe what is slowing it down is the following
callbacks: {
signIn: async ({ user, account, profile, email, credentials }) => {
account.accessToken = user.sessionID
account.uuid = user.uuid
const test = await sFinder(2,account)
return true
},
jwt: async ({ token, account }) => {
if (account) {
token.uuid = account.uuid
token.accessToken = account.accessToken
}
const lastUsedToken = await sFinder(1,token)
const updateTokenExpire = await sFinder(3,token)
if(lastUsedToken != token.accessToken){
// console.log("I have made it an error")
token.error = 555;
}
return token
},
session: async ({ session, token, user }) => {
session.uuid = token.uuid
if(!token.accessToken){
//OAUTH Accounts
session.accessToken = uuidv4()
}else{
session.accessToken = token.accessToken
}
if(token.error == 555){
session.error = 555
}
return session
}
},
Mainly all the awaits, but the await functions are to make sure the user is not login on another device. As we log the old devices out automatically.

The client_secret Provided does not match any associated PaymentIntent on this account

I'm trying to use flutter_stripe for a stripe connect account, But I always get the
same error: The client_secret provided doesn't match the client_secret associated with the PaymentIntend.
I've completed all steps according to flutter_stripe but I still face this error.
Below is my code Please check this and help me.
inde.js
const functions = require("firebase-functions");
const stripe = require("stripe")("secret_key");
exports.stripePaymentIntentRequest = functions.https.onRequest(async (req, res) => {
try {
let customerId;
//Gets the customer who's email id matches the one sent by the client
const customerList = await stripe.customers.list({
email: req.body.email,
limit: 1
});
//Checks the if the customer exists, if not creates a new customer
if (customerList.data.length !== 0) {
customerId = customerList.data[0].id;
}
else {
const customer = await stripe.customers.create({
email: req.body.email
});
customerId = customer.data.id;
}
//Creates a temporary secret key linked with the customer
const ephemeralKey = await stripe.ephemeralKeys.create(
{ customer: customerId },
{ apiVersion: '2020-08-27' }
);
//Creates a new payment intent with amount passed in from the client
const paymentIntent = await stripe.paymentIntents.create({
amount: parseInt(req.body.amount),
currency: 'usd',
customer: customerId,
})
res.status(200).send({
clientSecret: paymentIntent.client_secret,
paymentIntent: paymentIntent,
ephemeralKey: ephemeralKey.secret,
customer: customerId,
success: true,
})
} catch (error) {
res.status(404).send({ success: false, error: error.message })
}
});
PaymentService.dart
Future<void> initPaymentSheet(
{required BuildContext context, required String email, required int amount}) async {
try {
// 1. create payment intent on the server
final response = await http.post(
Uri.parse(
'Firebase api link of Functions'),
body: {
'email': email,
'amount': amount.toString(),
});
Map<String, dynamic> paymentIntentBody = jsonDecode(response.body);
log(paymentIntentBody.toString());
//2. initialize the payment sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentBody["clientSecret"],
merchantDisplayName: 'Flutter Stripe Store Demo',
customerId: paymentIntentBody['customer'],
customerEphemeralKeySecret: paymentIntentBody['ephemeralKey'],
style: ThemeMode.light,
testEnv: true,
merchantCountryCode: 'US',
),
);
await Stripe.instance.presentPaymentSheet();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Payment completed!')),
);
} catch (e) {
if (e is StripeException) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error from Stripe: ${e.error.localizedMessage}'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error the Stripe of : $e')),
);
}
}
}
The log error print on my console is :
> [log] {paymentIntent:
> pi_3LI2acCTAUDjRNFV1Ra3dahz_secret_Fcqw73pWrE4avKRyuDVzRBitG,
> ephemeralKey:
> ek_test_YWNjdF8xSlQ3amtDVEFVRGpSTkZWLDl1OE5Vdm1jTGY4T1RpaVhHOTB3NTRVSkQ5UGl4azA_00j32OYG9n,
> customer: cus_LHG2YpQP9Cgwuy, success: true}
The following code is from a previous Stripe evaluation stage. But it worked. Slim it down to your needs.
Remember to publish your secret key to the server, so the server can talk to Stripe.
code.dart
Future<bool> payWithPaymentSheet(
ProductModel productModel, PriceModel priceModel,
{String merchantCountryCode = 'DE'}) async {
if (kIsWeb) {
throw 'Implementation not availabe on Flutter-WEB!';
}
String uid = AuthService.instance.currentUser().uid;
String email = AuthService.instance.currentUser().email ?? '';
HttpsCallableResult response;
try {
response = await FirebaseFunctions
.httpsCallable('createPaymentIntent')
.call(<String, dynamic>{
'amount': priceModel.unitAmount,
'currency': priceModel.currency,
'receipt_email': email,
'metadata': {
'product_id': productModel.id,
'user_id': uid,
"valid_until": productModel.getUntilDateTime().toIso8601String(),
'product_name': productModel.name.tr,
},
'testEnv': kDebugMode,
});
} on FirebaseFunctionsException catch (error) {
log(error.code);
log(error.details);
log(error.message ?? '(no message)');
Get.snackbar(
error.code,
error.message ?? '(no message)',
icon: const Icon(Icons.error_outline),
);
return false;
}
Map<String, dynamic> paymentIntentBody = response.data;
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentBody["clientSecret"],
currencyCode: priceModel.currency,
applePay: false,
googlePay: false,
merchantCountryCode: merchantCountryCode,
merchantDisplayName: Strings.appName,
testEnv: kDebugMode,
customerId: paymentIntentBody['customer'],
customerEphemeralKeySecret: paymentIntentBody['ephemeralKey'],
));
try {
await Stripe.instance.presentPaymentSheet();
return true;
} on StripeException catch (e) {
log(e.error.code.name);
log(e.error.message ?? '(no message)');
log(e.error.localizedMessage ?? '(no message)');
Get.snackbar(e.error.code.name, e.error.message ?? '',
icon: const Icon(Icons.error_outline));
} catch (e) {
Get.snackbar('An unforseen error occured', e.toString(),
icon: const Icon(Icons.error_outline));
}
return false;
}
index.ts
// SETTING SECRET KEY ON SERVER:
// cd functions
// firebase functions:config:set stripe.secret_key="sk_live_51L...Noe"
// firebase deploy --only functions
let stripe = require("stripe")(functions.config().stripe.secret_key);
exports.createPaymentIntent = functions
.https.onCall((data, context) => {
// if (!context.auth) {
// return { "access": false };
// }
return new Promise(function (resolve, reject) {
stripe.paymentIntents.create({
amount: data.amount,
currency: data.currency,
receipt_email: decodeURIComponent(data.receipt_email),
metadata: data.metadata,
}, function (err, paymentIntent) {
if (err != null) {
functions.logger.error("Error paymentIntent: ", err);
reject(err);
}
else {
resolve({
clientSecret: paymentIntent.client_secret,
paymentIntentData: paymentIntent,
});
}
});
});
});

Empty data in response with axios and vuex

When I send this patch request with axios, the backend receives the data, but response.data comes back empty. Please and thanks!
// ACTION IN VUEX STORE
async updateMe({ commit }, payload) {
let id = localStorage.getItem('userId');
let user = { name: payload.name, email: payload.email, id: id };
try {
const response = await axios.patch(
`http://localhost:3000/api/v1/users/updateMe`,
user
);
commit('setUpdatedUser', response.data);
} catch (err) {
console.log(err);
}
}
// CONTROLLER
exports.updateMe = catchAsync(async (req, res, next) => {
const updatedUser = await User.findByIdAndUpdate(
req.body.id,
{
name: req.body.name,
email: req.body.email
},
{ new: true, runValidators: true }
);
res.status(204).json({ data: updatedUser });
});
204 is a No Content response code.

MongoDB + Express How to Optimize the code?

Hello everybody i have this bad code for me how i can optimize it ?
If i used SQL i can do used inner Queries in one query...
"User" it's only object from mongoose
getProfile: async (req, res) => {
const { id } = req.params;
try {
const {
image,
name,
gender,
about,
email,
phone,
address
} = await User.findById({ _id: id }).select('image name gender about email phone address');
const subscriptions = await Subscriber.countDocuments({ userId: id });
const subscribers = await Subscriber.countDocuments({ subscriberId: id });
const user = {
image,
name,
gender,
subscriptions,
subscribers,
about,
email,
phone,
address
};
res.json(user);
} catch (err) {
console.log(err);
}
}
PS.
I only study with this technologies
If i used spread operator of result of my query from User i have like this:
And that what i have in result
module.exports = {
getProfile: async (req, res) => {
const { id } = req.params;
try {
const [data, subscriptions, subscribers] = await Promise.all([
User.findById( { _id: id },
{
__v: false,
password: false,
date: false,
_id: false
},
),
Subscriber.countDocuments({ userId: id }),
Subscriber.countDocuments({ subscriberId: id })
])
const user = {
...data._doc,
subscriptions,
subscribers
}
res.json(user);
} catch (err) {
console.log(err);
}
}
Since all of your queries are independent, the best we can do is execute all of them parallelly with Promise.all(). Try something like this:
getProfile: async (req, res) => {
const { id = _id } = req.params;
try {
const getUser = User.findById({ _id }).select('image name gender about email phone address');
const getSubscriptions = Subscriber.countDocuments({ userId: id });
const getSubscriber = Subscriber.countDocuments({ subscriberId: id });
const [userData, subscriptions, subscribers] = await Promise.all([getUser, getSubscriptions, getSubscriber]);
const user = {
...userData,
subscriptions,
subscribers,
};
res.json(user);
} catch (err) {
console.log(err);
}
}
Hope this helps :)
You can embed subscriptions [array of documents] in the User model. But bear in mind that could put limitations on your api, if subscriptions might be accessed regardless of its user.