猫鼬密码哈希 [英] Mongoose password hashing
问题描述
我正在寻找一种使用mongoose将帐户保存到MongoDB的好方法.
I am looking for a good way to save an Account to MongoDB using mongoose.
我的问题是:密码是异步哈希的.设置器将无法在这里工作,因为它只能同步工作.
My problem is: The password is hashed asynchronously. A setter wont work here because it only works synchronous.
我考虑了两种方法:
-
创建模型的实例并将其保存在 哈希函数.
Create an instance of the model and save it in the callback of the hash function.
在保存"上创建一个预钩子
Creating a pre hook on 'save'
在这个问题上有什么好的解决方法吗?
Is there any good solution on this problem?
推荐答案
mongodb博客上有一篇很棒的文章,详细介绍了如何实现用户身份验证.
The mongodb blog has an excellent post detailing how to implement user authentication.
http://blog.mongodb.org/post/32866457221/password-authentication-with-mongoose-part-1
直接从上面的链接复制以下内容:
The following is copied directly from the link above:
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 user to database
testUser.save(function(err) {
if (err) throw err;
});
// fetch 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
});
});
这篇关于猫鼬密码哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!