I've started learning NodeJS since a few weeks. I'm building my first application where users can register a account and login with their credentials. When a user registers a account the password will be hashed. I'm using password-hash from NPM. The hashing of the password works fine. The problem is verifying the password when a user logs in. This is my code:
Registration:
router.post('/register', function(req, res, next) {
req.getConnection(function (err, connection) {
var data = {
username: req.body.username,
password: passwordHash.generate(req.body.password),
mail: req.body.mail,
hometown: req.body.hometown
};
connection.query("INSERT INTO users set ? ", [data], function(err, results) {
res.redirect('/secret/login');
});
});
});
Logging in and verifying hashed password:
router.post('/login', function(req, res, next) {
var user_login = req.body.username;
var password_login = req.body.password;
req.getConnection(function(err, connection) {
if (err) throw err;
connection.query('SELECT * FROM users WHERE username = ?', [user_login], function(err, results) {
if(results[0] && passwordHash.verify(password_login, results[0].password)) {
req.session.regenerate(function(){
req.session.login = true;
req.session.username = user_login;
req.session.data = results[0];
res.redirect(req.baseUrl);
});
} else {
console.log(results[0]); // true
res.redirect(req.baseUrl);
}
});
});
});
I've also tried
console.log(passwordHash.verify(password_login, results[0].password));
When I sign in with the username & password from one of the registred accounts, the boolean response in the console.log is 'false' every time. I couldn't find a answer on the internet so thats why I'm asking it here. I hope someone can help me solve this!
I'm using these modules:
"ejs": "^2.3.4",
"express": "^4.13.3",
"express-myconnection": "^1.0.4",
"multer": "^1.1.0",
"mysql": "^2.9.0",
"password-hash": "^1.2.2"
What am I doing wrong when verifying the hashed password?
I've found the problem .. The password was saved in my database as a varchar(50) .. Had to be varchar(88). Thanks for reading and answering!
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.