I am trying mobile verification with msg91 ..the code run succesfully but msg notsending messagee...it gives the success message ...
my code:
router.post('/mobile', async (req, res) =\> {
try {
const sendOtp = new SendOtp(process.env.AUTHKEY);
const mobile = await usermodel.findOne({ mobile: req.body.mobile })
if (!mobile) return res.status(403).send('user not found..')
const otp =`${ Math.floor(1000 + Math.random() * 9000)} `
console.log(otp);
const phonenumber = req.body.mobile
const newPhoneNumber = '+91' + phonenumber
// console.log(newPhoneNumber);
sendOtp.send(newPhoneNumber, otp, function (error, data) {
console.log(data);
console.log(error);
});
res.status(201).send({ status: 'TRUE', message: 'OTP SEND' })
} catch (error) {
res.status(200).send({ status: 'failed', message: 'Unable to Send OTP', error })
console.log(error)
}
})
responce:
{ message: '326b6774704a343230323437', type: 'success' }
null
Related
I am having a flow of registering a new user.
I am getting the error UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
auth.js
const express = require("express");
const authrequests = express.Router();
const cors = require("cors");
var createUser = require("./export/authConstants");
// Register User
authrequests.post("/register", async (req, res) => {
const userData = {
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
phone: req.body.phone,
password: req.body.password,
created: new Date(),
};
await createUser(userData)
.then((res) => {
console.log(res)
if (res.status == 200) {
return res.status(200).json({ msg: 'Registered!' });
} else if (res.status == 405) {
return res.status(405).json({ error: 'User already exists' });
} else {
return res.status(400).json({ error: err });
}
})
.catch(err => {
return res.status(400).json({ error: err });
})
});
module.exports = authrequests;
authConstants.js
const customers = require("./../../models/customers");
var hashPassword = require("./util/bcrypt");
var jwtCreate = require("./util/jwt");
var sendMail = require("./util/mail");
var BASE_URL = require("./../constants/constants");
//register
createUser = (userData) => {
return new Promise(async (resolve, reject) => {
customers.findOne({ where: { email: userData.email } })
.then(async (user) => {
if (!user) {
var hashResponse = await hashPassword(userData.password)
if (hashResponse.msg) {
userData.password = hashResponse.msg
customers.create(userData)
.then(async (user) => {
if (user) {
var jwtResponse = await jwtCreate({ data: user.id, expiry: 172800 })
if (jwtResponse.msg) {
const url = `${BASE_URL}/auth/emailVerified/${jwtResponse.msg}`;
var mailResponse = await sendMail({
to: user.email,
subject: 'Email Verification',
html: `Click on the following link to verify your account: click here`
})
if (mailResponse.msg) {
resolve({ status: 200 })
} else {
reject({ error: mailResponse.err })
}
} else {
reject({ error: jwtResponse.err })
}
} else {
reject({ error: "oops..! user creation failed" })
}
})
.catch(err => {
reject({ error: err })
});
} else {
reject({ error: hashResponse.err })
}
} else {
resolve({ status: 405 })
}
})
.catch(err => {
reject({ error: err })
})
})
};
bcrypt.js
const bcrypt = require("bcrypt");
//hashing password
hashPassword = async (password) => {
await bcrypt.hash(password, 10, (err, hash) => {
if (hash) {
return { msg: hash };
} else {
return { error: err };
}
})
};
jwt.js
const jwt = require("jsonwebtoken");
var EMAIL_SECRET = require("./../../constants/constants");
//jwt creation
jwtCreate = async (data) => {
await jwt.sign(data.data, EMAIL_SECRET, { expiresIn: data.expiry }, (err, token) => {
if (token) {
return { msg: token };
} else {
return { error: err };
}
})
};
mail.js
const nodemailer = require("nodemailer");
var MAIL_HOST = require("./../../constants/constants");
var EMAIL_USER = require("./../../constants/constants");
var EMAIL_PASS = require("./../../constants/constants");
//mail send
sendMail = async (data) => {
let transporter = nodemailer.createTransport({
host: MAIL_HOST,
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: EMAIL_USER,
pass: EMAIL_PASS,
},
tls: {
rejectUnauthorized: false,
},
});
await transporter.sendMail({
from: EMAIL_USER,
to: data.to,
subject: data.subject,
html: data.html
}, (err, response) => {
if (token) {
return { msg: response };
} else {
return { error: err };
}
});
};
constants.js
const EMAIL_SECRET = "asdf1093KMnHGcvnkljvasdu09123nlasdasdf";
const MAIL_HOST = "mail.test.com";
const EMAIL_USER = "no_reply_auth#test.com";
const EMAIL_PASS = "JMkC+)*Lv";
const BASE_URL = "http://localhost:3001";
UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
is there something I am missing out..? or the entire flow is wrong..?
I have a fairly bare bones mern stack and im trying to call getUsers and then retrieve a single user from the returned list of users.
however using [] doesnt seem to work. It looks like getUsers correctly returns the list of users but idk how to pull a single one out
user-ctrl.js
const User = require('../models/user-model')
createUser = (req, res) => {
const body = req.body
if (!body) {
return res.status(400).json({
success: false,
error: 'You must provide a user',
})
}
const user = new User(body)
if (!user) {
return res.status(400).json({ success: false, error: err })
}
user
.save()
.then(() => {
return res.status(201).json({
success: true,
id: user._id,
message: 'User created!',
})
})
.catch(error => {
return res.status(400).json({
error,
message: 'User not created!',
})
})
}
updateUser = async (req, res) => {
const body = req.body
if (!body) {
return res.status(400).json({
success: false,
error: 'You must provide a body to update',
})
}
User.findOne({ _id: req.params.id }, (err, user) => {
if (err) {
return res.status(404).json({
err,
message: 'User not found!',
})
}
user.name = body.name
user.email = body.email
user
.save()
.then(() => {
return res.status(200).json({
success: true,
id: user._id,
message: 'User updated!',
})
})
.catch(error => {
return res.status(404).json({
error,
message: 'User not updated!',
})
})
})
}
deleteUser = async (req, res) => {
await User.findOneAndDelete({ _id: req.params.id }, (err, user) => {
if (err) {
return res.status(400).json({ success: false, error: err })
}
if (!user) {
return res
.status(404)
.json({ success: false, error: `User not found` })
}
return res.status(200).json({ success: true, data: user })
}).catch(err => console.log(err))
}
getUserById = async (req, res) => {
await User.findOne({ _id: req.params.id }, (err, user) => {
if (err) {
return res.status(400).json({ success: false, error: err })
}
if (!user) {
return res
.status(404)
.json({ success: false, error: `User not found` })
}
return res.status(200).json({ success: true, data: user })
}).catch(err => console.log(err))
}
getUsers = async (req, res) => {
await User.find({}, (err, users) => {
if (err) {
return res.status(400).json({ success: false, error: err })
}
if (!users.length) {
return res
.status(404)
.json({ success: false, error: `User not found` })
}
return res.status(200).json({ success: true, data: users })
}).catch(err => console.log(err))
}
module.exports = {
createUser,
updateUser,
deleteUser,
getUsers,
getUserById,
}
You need to actually call the getUsers function (with parenthesis), and then wait for the promise to resolve, with await
var allUsers = await UserCtrl.getUsers();
var defaultUser = allUsers[0];
or
UserCtl.getUsers()
.then(u=>u[0])
.then(user=>{
// insert code that uses the user here
})
It's a promise, so try with async/await
var allUsers = await UserCtrl.getUsers();
var defaultUser = allUsers[0];
To make await work, put async infront of your method:
async createUser = (req, res) => {
I have a repository where I connect directly to my model to insert some data, it creates the data successfully but when I connect my controller to this repository, I get a nulled response, if I log it in the repository itself I get Promise . Please checkout my code below:-
Repository.js
exports.register = (request) => {
const data = UserModel.findOne({email: request.email})
.then(user => {
if(user)
{
return {status: 400, message: 'Email Already exist'}
} else {
return bcrypt.genSalt(10, (err, salt) => {
const newUser = new UserModel({
username: request.username,
email: request.email,
password: request.password
});
return bcrypt.hash(newUser.password, salt, async (err, hash) => {
if(err) throw err;
newUser.password = hash;
return newUser.save()
.then(user => {
const token = jwt.sign({id: user._id}, process.env.JWT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
return {status: 200, message: 'Successfully Registered', auth: true, token: token, user: user}
})
.catch(err => {
return {status: 400, message: err}
})
})
})
}
})
console.log(data) // This part is return Promise <pending>
return data;
};
Controller.js
exports.SeedRegisteration = async (req, res, next) => {
try {
let element = await userRepo.register({username: "Testin", email: "Testin#test.com", "password":
"joe" });
return await res.status(200).json({ status: 200, data: element })
} catch (e) {
return res.status(400).json({ status: 400, message: e.message });
}
};
Works fine but does not return data
Here's the register function using the Promise version of bcrypt (if you don't supply a callback, the bcrypt functions return a Promise
exports.register = (request) =>
UserModel.findOne({
email: request.email
})
.then(user => {
if (user) {
throw 'Email Already exist'
}
})
.then(() => bcrypt.genSalt(10))
.then(salt => {
const newUser = new UserModel({
username: request.username,
email: request.email,
password: request.password
});
return bcrypt.hash(newUser.password, salt)
.then((hash) => {
newUser.password = hash;
return newUser.save();
})
}).then(user => {
const token = jwt.sign({
id: user._id
}, process.env.JWT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
return {
status: 200,
message: 'Successfully Registered',
auth: true,
token: token,
user: user
}
}).catch(err => {
return {
status: 400,
message: err
}
});
Note: there is ONE nested .then - this code could be perfectly flat if you used async/await in register - however I was not prepared to perform such a big rewrite for the answer. Now that the code is in a nice almost flat promise chain, it's relatively simple to convert the whole thing into async/await style
There are too many return statements which return promise. Please update your code in to the following:
exports.register = (request) => {
return new Promise((resolve, reject) => {
try {
UserModel.findOne({ email: request.email })
.then(user => {
if (user) {
return reject({ status: 400, message: 'Email Already exist' })
} else {
bcrypt.genSalt(10, (err, salt) => {
const newUser = new UserModel({
username: request.username,
email: request.email,
password: request.password
});
bcrypt.hash(newUser.password, salt, async (err, hash) => {
if (err) return reject(err);
newUser.password = hash;
newUser.save()
.then(user => {
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
return resolve({ status: 200, message: 'Successfully Registered', auth: true, token: token, user: user })
})
.catch(err => {
return reject({ status: 400, message: err })
})
})
})
}
}).catch(err => {
return reject(err)
})
} catch (error) {
return reject(error)
}
});
};
The upcoming code snippet is removing the password attribute from the user JSON object and return it in response. what is happening is that the password attribute is still returning!
const signin = (req, res, next) => {
let requestBody = req.body;
userModel.findUserByEmail(requestBody.email).then(user => {
bcrypt.compare(requestBody.password, user.password, (error, result) => {
if (!result) {
return res.status(500).json({
status: false,
message: 'Auth Failed!',
error
});
}
if (error) {
return res.status(500).json({
error
});
}
let token = jwt.sign({
email: user.email,
userId: user._id
},
process.env.JWT_KEY,
{
expiresIn: "2h"
});
// remonve password key
delete user.password
res.status(200).json({
status: true,
message: 'Authenticated!',
data: {
token,
user
}
});
});
}).catch(error => {
return res.status(500).json({
status: false,
message: 'Auth Failed!',
error
});
});
}
not sure the problem is related to async compilation or not
You could create a new object without the password and use that in your response:
const { password, ...restOfUser } = user
res.status(200).json({
status: true,
message: 'Authenticated!',
data: {
token
user: restOfUser
}
})
I'm trying to validate a user email by decoding a JWT token given as parameter in a GET request.
In case the token is valid and the User is not verified yet, I want to update isVerified column to true.
Why is my Promise always rejected ?
const jwt = require('jsonwebtoken');
const request = require('request');
const models = require('../models');
/**
* GET /verify-email/:token
*/
exports.verifyEmail = function(req, res) {
jwt.verify(req.params.token, process.env.TOKEN_SECRET, function(err, decoded) {
if (err) {
res.send({
msg: 'Token is invalid or has expired'
})
}
models.User.findOne({
where: {
email: decoded.email,
id: decoded.id
}
}).then(record => {
if (!record) {
res.send({
msg: 'User not found'
})
} else if (record.isVerified) {
res.send({
msg: 'User already verified'
})
} else {
console.log('user mail ' + record.email + ' will be verified in db')
record.update({
isVerified: true,
})
.then(() => res.status(200).send({
msg: 'User has been verified'
}))
.catch((error) => res.status(400).send(error));
}
})
});
}
Problem solved, I had a beforeValidation hook in my model :
if (!user.changed('password')) {
return sequelize.Promise.reject("not modified");
}