所以我在使用bcrypt正确比较密码时遇到问题。我在所有函数之外生成了salt,在register函数内部对其进行哈希处理,并尝试在login函数中进行比较。但是,我遇到了问题,它总是会产生我输入错误密码的情况。我将遗漏很多代码,以保持可读性。
const express = require('express');
const db = require('mongodb');
const bcrypt = require('bcryptjs');
const router = express.Router();
let error = {};
const salt = bcrypt.genSaltSync(10);
// register user
router.post('/', async (req, res) => {
const newUser = await userDb();
// Checks for already existing users
let userNameCheck = await newUser.findOne( { 'username': req.body.username });
let userEmailCheck = await newUser.findOne( { 'email': req.body.email });
if (userNameCheck) {
Object.assign(error, {
'usernameExists': 'Username already Exists',
});
}
if (userEmailCheck) {
Object.assign(error, {
'emailExists': 'Email already Exists',
});
}
// Check for illegal characters in username
if (checkSymb(req.body.username) || checkLatin(req.body.username)) {
illegalCharacters = true;
Object.assign(error, {
'illegalCharacters': 'Illegal Characters, please only alpha numeric!',
});
}
if (userNameCheck || userEmailCheck || illegalCharacters) {
res.status(201).send(error);
return;
} else {
const hash = bcrypt.hashSync(req.body.password, salt);
await newUser.insertOne({
email: req.body.email,
username: req.body.username,
password: hash,
},
}).catch(err => {
if (err) {
return err;
}
});
res.status(201).send();
}
});
router.post('/login', async (req, res)=> {
const currentUser = await userDb();
// Check blank
let emailBody = req.body.email.length;
let passBody = req.body.password.length;
if (!emailBody) {
Object.assign(error, {
'blankEmail': 'Email can not be blank!',
});
}
if (!passBody) {
Object.assign(error, {
'blankPassword': 'Password can not be blank!',
});
}
if (!emailBody || !passBody) {
res.status(201).send(error);
}
// See if member exists
const doesExist = await currentUser.findOne({ 'email': `${req.body.email}` });
if (doesExist) {
// if user exists check password
let passGood = bcrypt.compareSync(doesExist.password, salt);
if (passGood) {
console.log('Login Successful');
res.status(201).send();
} else {
console.log('Username or Password incorrect');
Object.assign(error, {
'wrongCredits': 'Username or Password incorrect',
});
res.status(201).send(error);
}
} else {
error = 'This user does not exist';
console.log(error);
res.status(201).send(error);
}
});
async function userDb() {
const client = await db.MongoClient.connect('mongodb://127.0.0.1:27017', {
useNewUrlParser: true
});
return client.db('kog').collection('users');
};
如您所见,我正在尝试比较现有密码以查看是否正确。我知道它是正确的,因为出于测试原因我将其保持简单。我不确定为什么比较不起作用,我知道我需要比较散列,但是如果我尝试比较新的散列,仍然会成为问题。
谢谢!
答案 0 :(得分:0)
弄清楚了...这是一个愚蠢的错误:
从此:let passGood = bcrypt.compareSync(doesExist.password, salt);
对此:let passGood = bcrypt.compareSync(req.body.password, doesExist.password);