问题描述
我正在遵循freeCodeCamp的Youtube教程,但是我的代码无法比较我的哈希密码和用户输入的密码。
Authencation.js代码
const { User } = require('../models')
const jwt = require('jsonwebtoken')
const config = require('../config/config')
function jwtSignUser (user) {
const ONE_WEEK = 60 * 60 * 24 * 7
return jwt.sign(user,config.authentication.jwtSecret,{
expiresIn: ONE_WEEK
})
}
module.exports = {
async register (req,res) {
try {
const user = await User.create(req.body)
const userjson = user.toJSON()
res.send({
user: userjson,token: jwtSignUser(userjson)
})
} catch (err) {
console.log(err)
res.status(400).send({
error: 'This email account is already in use.'
})
}
},async login (req,res) {
try {
const { email,password } = req.body
const user = await User.findOne({
where: {
email: email
}
})
console.log(user)
if (!user) {
return res.status(403).send({
error: 'The email information was incorrect'
})
}
const isPasswordValid = await user.comparePassword(password)
console.log(isPasswordValid)
if (!isPasswordValid) {
return res.status(403).send({
error: 'The password information was incorrect'
})
}
const userjson = user.toJSON()
res.send({
user: userjson,token: jwtSignUser(userjson)
})
} catch (err) {
console.log(err)
res.status(500).send({
error: 'An error has occured trying to log in'
})
}
}
}
在这里user.comparePassword(password)是需要将密码与存储的密码和用户输入的密码进行比较的功能
哈希和存储是通过User.js完成的
const Promise = require('bluebird')
const bcrypt = Promise.promisifyAll(require('bcrypt'))
function hashPassword (user,options) {
const SALT_FACTOR = 8
if (!user.changed('password')) {
return
}
return bcrypt
.genSalt(SALT_FACTOR)
.then(salt => bcrypt.hash(user.password,salt,null))
.then(hash => {
user.setDataValue('password',hash)
})
}
module.exports = (sequelize,DataTypes) => {
const User = sequelize.define('User',{
email: {
type: DataTypes.STRING,unique: true
},password: DataTypes.STRING
},{
hooks: {
beforeCreate: hashPassword,beforeUpdate: hashPassword,beforeSave: hashPassword
}
})
User.prototype.comparePassword = function (password) {
return bcrypt.compare(password,this.password)
}
return User
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)