我正在寻找一种使用 mongoose 将帐户保存到 MongoDB 的好方法。
我的问题是:密码是异步散列的。 setter 不能在这里工作,因为它只能同步工作。
我想到了两种方法:
创建模型实例并保存在 哈希函数。
在“保存”上创建一个预 Hook
这个问题有什么好的解决办法吗?
最佳答案
mongodb 博客有一篇很棒的文章详细介绍了如何实现用户身份验证。
http://blog.mongodb.org/post/32866457221/password-authentication-with-mongoose-part-1
以下内容是直接从上面的链接复制过来的:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true }
});
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;
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);
var mongoose = require(mongoose),
User = require('./user-model');
var connStr = 'mongodb://localhost:27017/mongoose-bcrypt-test';
mongoose.connect(connStr, function(err) {
if (err) throw err;
console.log('Successfully connected to MongoDB');
});
// create a user a new user
var testUser = new User({
username: 'jmar777',
password: 'Password123'
});
// save the user to database
testUser.save(function(err) {
if (err) throw err;
});
// fetch the user and test password verification
User.findOne({ username: 'jmar777' }, function(err, user) {
if (err) throw err;
// test a matching password
user.comparePassword('Password123', function(err, isMatch) {
if (err) throw err;
console.log('Password123:', isMatch); // -> Password123: true
});
// test a failing password
user.comparePassword('123Password', function(err, isMatch) {
if (err) throw err;
console.log('123Password:', isMatch); // -> 123Password: false
});
});
关于node.js - Mongoose 密码哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14588032/
相关文章:
mongodb - 插入后如何在 PyMongo 中获取对象 ID?
mongodb - 如何从 MongoDB 中删除 system.profile 集合?
c# - 如何使用 MongoDB 的 C# 驱动程序指定 Order 或 Sort?
mongodb - 执行 mongoexport 时 "too many positional op
mongodb - 如何停止在 mongodb 集合中插入重复文档
arrays - 查询 MongoDB 以匹配数组中的第一项
session - node.js + express.js : session handling