node.js - 注册时如何对我的 mongoose Passport js 密码进行哈希处理?

标签 node.js mongodb hash mongoose passport.js

我正在尝试弄清楚如何在用户注册时对密码进行哈希处理。我正在使用 Mongoose 和 Passport js。是否有任何 Node 模块可以用来散列密码,并且可以使用我当前的代码轻松实现?这是我的本地策略:

// Passport login LocalStrategy
passport.use('login', new LocalStrategy({
    passReqToCallback : true
}, function(req, username, password, done) {
    // check in mongo if a user with username exists or not
    User.findOne({ 'username' :  username },
        function(err, user) {
            // In case of any error, return using the done method
            if (err)
                return done(err);
            // Username does not exist, log error & redirect back
            if (!user){
                console.log('User Not Found with username '+username);
                return done(null, false,
                    req.flash('message', 'User Not found.'));
            }
            // User exists but wrong password, log the error
            if (!user.validPassword(password)){
                console.log('Invalid Password');
                return done(null, false,
                    req.flash('message', 'Invalid Password'));
            }
            // User and password both match, return user from
            // done method which will be treated like success
            return done(null, user);
        }
    );
}));

passport.use('signup', new LocalStrategy({
        passReqToCallback : true
    },
    function(req, username, password, done) {
        findOrCreateUser = function(){
            // find a user in Mongo with provided username
            User.findOne({'username':username},function(err, user) {
                // In case of any error return
                if (err){
                    console.log('Error in SignUp: '+err);
                    return done(err);
                }
                // already exists
                if (user) {
                    console.log('User already exists');
                    return done(null, false,
                        req.flash('message','User Already Exists'));
                } else {
                    // if there is no user with that email
                    // create the user
                    var newUser = new User();
                    // set the user's local credentials
                    newUser.username = username;
                    newUser.password = password;
                    newUser.email = req.param('email');
                    // save the user
                    newUser.save(function(err) {
                        if (err){
                            console.log('Error in Saving user: '+err);
                            throw err;
                        }
                        console.log('User Registration succesful');
                        return done(null, newUser);
                    });
                }
            });
        };
    process.nextTick(findOrCreateUser);
}));

这是我的用户模型:

var mongoose = require("mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    email:  String,
    password: String,
    friends: [this]
});
UserSchema.methods.validPassword = function (pwd) {
    return (this.password === pwd);
}

module.exports = mongoose.model("User", UserSchema);

当我检查我的 mongo 数据库时,密码未经过哈希处理。我如何散列它们?非常感谢!

最佳答案

您可以使用bcrypt-nodejs模块对密码进行哈希处理。

在您的用户模型

var mongoose = require("mongoose");
var bcrypt = require('bcrypt-nodejs'); // use const or import if you're using ES6


// store this funciton in some helper file, instead of storing it in this User Model.
var hash_password = function( password ) {
    let salt = bcrypt.genSaltSync(); // enter number of rounds, default: 10
    let hash = bcrypt.hashSync( password, salt );
    return hash;
},


var UserSchema = new mongoose.Schema({
    username: String,
    email:  String,
    password: String,
    friends: [this]
});

UserSchema.methods.comparePassword = function(password) {
    if ( ! this.password ) { return false; }
    return bcrypt.compareSync( password, this.password );
};

UserSchema.pre('save', function(next) {
    // check if password is present and is modified.
    if ( this.password && this.isModified('password') ) {
        this.password = hash_password(this.password);
    }
    next();
});

module.exports = mongoose.model("User", UserSchema);

在您的LocalStrategies

您可以使用下面的代码块删除 user.validPassword 的代码。

...
// User exists but wrong password, log the error
// if (!user.validPassword(password)){
//  console.log('Invalid Password');
//      return done( null, false, req.flash('message', 'Invalid Password') );
// }
// // User and password both match, return user from
// // done method which will be treated like success
// return done(null, user);

if ( user && user.comparePassword( password ) ) {
    // user found, password is correct. do what you want to do
    return done(null, user);
} else {
    // user not found or wrong password.
    console.log('Invalid Password');
    return done( null, false, req.flash('message', 'Invalid Password') );
}
...

关于node.js - 注册时如何对我的 mongoose Passport js 密码进行哈希处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172045/

相关文章:

javascript - 如何根据用户输入使用 Node.js 发出 HTTP 请求?

javascript - 如何将新的 Nan::ObjectWrap 从 C++ 传递到 Javascript?

mongodb - Mongodb 排序异常 - 没有索引的 sort() 数据太多

node.js - 使用 Node.js 和 Mongoose 将查询结果保存到模型/模式的属性

perl - 在 Perl 中,如何从库中导入哈希?

algorithm - 如何为 HashSet/HashMap 实现哈希函数

C++ Inventory & Item Crafting System - 将 "stuff"转换为 hash_tag "garblygook"并反转 hash_tags 以获得真实的 "stuff"

javascript - 渲染组件后 API 调用返回图像

javascript - nodejs 不读取 JSON

algorithm - mongo $in 反对成对的嵌套文档