I want to create a login with jwt but bcrypt compare does not work. I connected node to my db and put the db object in the req. The type of req.body.password and user.passwordHash is in bouth cases string.
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jwt-simple');
const joi = require('joi');
const authHelper = require('./authHelper');
const router = express.Router();
router.post('/', (req, res, next) => {
const schema = {
email: joi.string().email().min(7).max(50).required(),
password: joi.string().regex(/^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{7,15}$/).required()
};
joi.validate(req.body, schema, (err) => {
if(err)
return next(new Error('Invalid field: password 7 to 15 (one number, one specail character)'));
req.db.collection.findOne({ type: 'USER_TYPE', email: req.body.email }, (err, user) => {
if(err)
return next(err);
if(!user)
return next(new Error('User was not found'));
bcrypt.compare(user.passwordHash, req.body.password, (err, match) => {
if(match) {
try {
const token = jwt.encode({
authorized: true,
sessionIP: req.ip,
sessionUA: req.headers['user-agent'],
userId: user._id.toHexString(),
displayName: user.displayName
}, process.env.JWT_SECRET);
res.status(201).json({
displayName: user.displayName,
userId: user._id,
token: token,
msg: 'Authorized'
});
}
catch(err) {
return next(err);
}
}
else {
return next(new Error('Wrong password'));
}
});
});
});
});
I hope you can solve my problem :)
bcrypt.compare
的第一个参数是用户未修饰的密码,第二个参数是哈希。
bcrypt.compare(req.body.password, user.passwordHash, (err, match) => {
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.