您如何在用于登录用户的快速应用程序中使用 mongoose for mongoDB 验证密码?
How do you validate password using mongoose for mongoDB in an express app for logging in a user?
我正在尝试让用户通过他们的电子邮件和密码登录。 MongoDb 文档显示在用户模型中使用 bcrypt 散列密码。它还提供了一种很好的方法来验证模型中的密码。我的问题是如何使用来自 "controller" 的验证?我很清楚 "if (req.body.password === user.password)" 不会工作,因为一个被散列而另一个没有。
我已经搜索了几个小时的答案,但似乎无法找到与我如何在 post 请求中使用 "UserSchema.methods.comparePassword" 方法登录的联系。这还不完全真正的登录,只是尝试获取密码以验证并在登录后发回密钥。这是文档:https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
// 这是我的用户模型
let mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10
var hat = require('hat');
let UserSchema = new Schema({
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
require: true
},
api_key: {
type: String
}
});
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
user.api_key = hat();
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('user', UserSchema);
//这是sessions.js
let UserModel = require('../../../models/user.model');
var express = require('express');
var router = express.Router();
router.post('/', (req, res, next) => {
UserModel.findOne(
{
$or: [
{ email : req.body.email }
]
}
)
.then(user => {
if (req.body.password === user.password) {
res.setHeader("Content-Type", "application/json");
res.status(200).send(JSON.stringify({
"api_key": `${user.api_key}`
}));
} else {
res.status(404).send("Incorrect email or password")
}
})
.catch(error => {
res.setHeader("Content-Type", "application/json");
res.status(500).send({error})
})
})
module.exports = router
如果我只是通过电子邮件找到用户,一切正常。只需要弄清楚如何在用户模型中使用比较密码方法。谢谢!
也许你的模型中有这样的东西:
User = require('./user-model');
.......
User.findOne({ username: 'jmar777' }, function(err, user) {
if (err) throw err;
user.comparePassword('Password123', function(err, isMatch) {
if (err) throw err;
console.log('Password123:', isMatch); // -> Password123: true
});
........
其他资源:
http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt
https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt
希望对您有所帮助!
我正在尝试让用户通过他们的电子邮件和密码登录。 MongoDb 文档显示在用户模型中使用 bcrypt 散列密码。它还提供了一种很好的方法来验证模型中的密码。我的问题是如何使用来自 "controller" 的验证?我很清楚 "if (req.body.password === user.password)" 不会工作,因为一个被散列而另一个没有。
我已经搜索了几个小时的答案,但似乎无法找到与我如何在 post 请求中使用 "UserSchema.methods.comparePassword" 方法登录的联系。这还不完全真正的登录,只是尝试获取密码以验证并在登录后发回密钥。这是文档:https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
// 这是我的用户模型
let mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10
var hat = require('hat');
let UserSchema = new Schema({
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
require: true
},
api_key: {
type: String
}
});
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
user.api_key = hat();
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('user', UserSchema);
//这是sessions.js
let UserModel = require('../../../models/user.model');
var express = require('express');
var router = express.Router();
router.post('/', (req, res, next) => {
UserModel.findOne(
{
$or: [
{ email : req.body.email }
]
}
)
.then(user => {
if (req.body.password === user.password) {
res.setHeader("Content-Type", "application/json");
res.status(200).send(JSON.stringify({
"api_key": `${user.api_key}`
}));
} else {
res.status(404).send("Incorrect email or password")
}
})
.catch(error => {
res.setHeader("Content-Type", "application/json");
res.status(500).send({error})
})
})
module.exports = router
如果我只是通过电子邮件找到用户,一切正常。只需要弄清楚如何在用户模型中使用比较密码方法。谢谢!
也许你的模型中有这样的东西:
User = require('./user-model');
.......
User.findOne({ username: 'jmar777' }, function(err, user) {
if (err) throw err;
user.comparePassword('Password123', function(err, isMatch) {
if (err) throw err;
console.log('Password123:', isMatch); // -> Password123: true
});
........
其他资源:
http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt
https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt
希望对您有所帮助!