内容纲要

[code]
$ npm install bcrypt –save
[/code]

[code language=”js”]
// require the bcrypt module
var bcrypt = require(‘bcrypt’);
[/code]

[code language=”js”]
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(req.body.password, salt);
— OR —
var hash = bcrypt.hashSync(req.body.password, 10);
[/code]

验证 password

[code language=”js”]
bcrypt.compareSync(req.body.password, hash);
[/code]

异步方式

[code language=”js”]
bcrypt.hash(req.body.password, 10, function(err, hash) {
// Store hash password in your Database.
});
[/code]

[code language=”js”]
bcrypt.compare(req.body.password, hash, function(err, res) {
// res == true
});
[/code]

完整代码

[code language=”js”]
module.exports.authenticate=function(req,res){
var email=req.body.email;
var password=req.body.password;
connection.query(‘SELECT * FROM users WHERE email = ?’,[email], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:’there are some error with query’
})
}else{
if(results.length >0){
bcrypt.compare(password, results[0].password, function(err, ress) {
if(!ress){
res.json({
status:false,
message:"Email and password does not match"
});
}else{
res.json({
status:true,
message:"Successfully Login"
})
}
});
}
else{
res.json({
status:false,
message:"Email does not exits"
});
}
}
});
}
[/code]

发表评论

电子邮件地址不会被公开。 必填项已用*标注