Hi can someone take a look at my code? I am implementing authentication on a back end I am building as a side project to improve my understanding of JavaScript.
I'm not sure why the promise from a mongoose find is returning undefined.
I have two functions I need help with. One is a help function which will be passed to a controller.
import db from '../models';
import bcrypt from 'bcrypt';
import validateLogin from '../validations/login';
import isEmpty from 'lodash/isEmpty';
const loginController = {};
loginController.login = function(req,res){
validateLogin(req.body).then(({isValid, errors }) => {
// isValid is undefined here
// This is the problem
if(isValid){
// give token
res.status(200).json({
success: true,
token: 'here is your token'
});
} else {
res.status(401).json({
errors
});
}
}).catch(err =>{
console.log(err)
});
};
export default loginController;
The other is the controller function itself that will issuse a token depending on whether the helper function returns a valid or not response.
import validator from 'validator';
import db from '../models';
import isEmpty from 'lodash/isEmpty';
import bcrypt from 'bcrypt';
function validateLogin(data){
const { userInput, password } = data;
const errors = {};
if(validator.isEmpty(userInput)){
errors.userInput = 'username is required';
}
if(validator.isEmpty(password)){
errors.password = 'password is required';
}
return db.User.find({$or:[{ username: userInput }, { email: userInput }]}).then(existingUser =>{
if(existingUser.length > 0){
// User exists, check if password matches hash
const user = existingUser[0];
bcrypt.compare(password, user.password_digest).then(valid => {
if(!valid){
errors.password = 'Invalid Password';
}
console.log('from prmomise');
return {
isValid: isEmpty(errors),
errors
};
}).catch(err => console.log(err));
} else {
errors.userInput = 'username or email does not exist';
return {
isValid: isEmpty(errors),
errors
};
}
});
}
export default validateLogin
It looks like a return
is missing for the bcrypt
call:
return bcrypt.compare(password, user.password_digest).then(valid => {
// password check and returning result object
}).catch(err => console.log(err));
Without it your validateLogin
function eventually returns a promise that resolves to undefined
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.