Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在注册时散列我的mongoose passport js密码?_Node.js_Mongodb_Hash_Mongoose_Passport.js - Fatal编程技术网

Node.js 如何在注册时散列我的mongoose passport js密码?

Node.js 如何在注册时散列我的mongoose passport js密码?,node.js,mongodb,hash,mongoose,passport.js,Node.js,Mongodb,Hash,Mongoose,Passport.js,我正在试图弄清楚如何在用户注册时散列密码。我正在使用猫鼬和passport js。是否有任何节点模块可以用来散列密码,这些密码可以用我当前的代码轻松实现?以下是我的策略: // Passport login LocalStrategy passport.use('login', new LocalStrategy({ passReqToCallback : true }, function(req, username, password, done) { // check in

我正在试图弄清楚如何在用户注册时散列密码。我正在使用猫鼬和passport js。是否有任何节点模块可以用来散列密码,这些密码可以用我当前的代码轻松实现?以下是我的策略:

// 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 dbs时,密码不会被散列。我怎么把它们炸开?非常感谢

您可以使用
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);
在您的本地策略中

您可以使用下面的代码块删除
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') );
}
...

您可以使用
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);
在您的本地策略中

您可以使用下面的代码块删除
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') );
}
...
可能的重复可能的重复