Mongoose password hashing

前端 未结 10 984
盖世英雄少女心
盖世英雄少女心 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 07:43

    For those who are willing to use ES6+ syntax can use this -

    const bcrypt = require('bcryptjs');
    const mongoose = require('mongoose');
    const { isEmail } = require('validator');
    
    const { Schema } = mongoose;
    const SALT_WORK_FACTOR = 10;
    
    const schema = new Schema({
      email: {
        type: String,
        required: true,
        validate: [isEmail, 'invalid email'],
        createIndexes: { unique: true },
      },
      password: { type: String, required: true },
    });
    
    schema.pre('save', async function save(next) {
      if (!this.isModified('password')) return next();
      try {
        const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
        this.password = await bcrypt.hash(this.password, salt);
        return next();
      } catch (err) {
        return next(err);
      }
    });
    
    schema.methods.validatePassword = async function validatePassword(data) {
      return bcrypt.compare(data, this.password);
    };
    
    const Model = mongoose.model('User', schema);
    
    module.exports = Model;
    

提交回复
热议问题