Mongoose password hashing

前端 未结 10 978
盖世英雄少女心
盖世英雄少女心 2020-12-04 07:28

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 on

10条回答
  •  青春惊慌失措
    2020-12-04 08:00

    I think this is a good way by user Mongoose and bcrypt!

    User Model

    /**
     * Module dependences
    */
    
    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const bcrypt = require('bcrypt');
    const SALT_WORK_FACTOR = 10;
    
    // define User Schema
    const UserSchema = new Schema({
        username: {
            type: String,
            unique: true,
            index: {
                unique: true
            }
        },
        hashed_password: {
            type: String,
            default: ''
        }
    });
    
    // Virtuals
    UserSchema
        .virtual('password')
        // set methods
        .set(function (password) {
            this._password = password;
        });
    
    UserSchema.pre("save", function (next) {
        // store reference
        const user = this;
        if (user._password === undefined) {
            return next();
        }
        bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
            if (err) console.log(err);
            // hash the password using our new salt
            bcrypt.hash(user._password, salt, function (err, hash) {
                if (err) console.log(err);
                user.hashed_password = hash;
                next();
            });
        });
    });
    
    /**
     * Methods
    */
    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);
    

    Usage

    signup: (req, res) => {
        let newUser = new User({
            username: req.body.username,
            password: req.body.password
        });
        // save user
        newUser.save((err, user) => {
            if (err) throw err;
            res.json(user);
        });
    }
    

    Result

    Result

提交回复
热议问题