Mongoose password hashing

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

    TL;DR - Typescript solution

    I have arrived here when I was looking for the same solution but using typescript. So for anyone interested in TS solution to the above problem, here is an example of what I ended up using.

    imports && contants:

    import mongoose, { Document, Schema, HookNextFunction } from 'mongoose';
    import bcrypt from 'bcryptjs';
    
    const HASH_ROUNDS = 10;
    

    simple user interface and schema definition:

    export interface IUser extends Document {
        name: string;
        email: string;
        password: string;
        validatePassword(password: string): boolean;
    }
    
    const userSchema = new Schema({
        name: { type: String, required: true },
        email: { type: String, required: true, unique: true },
        password: { type: String, required: true },
    });
    

    user schema pre-save hook implementation

    userSchema.pre('save', async function (next: HookNextFunction) {
        // here we need to retype 'this' because by default it is 
        // of type Document from which the 'IUser' interface is inheriting 
        // but the Document does not know about our password property
        const thisObj = this as IUser;
    
        if (!this.isModified('password')) {
            return next();
        }
    
        try {
            const salt = await bcrypt.genSalt(HASH_ROUNDS);
            thisObj.password = await bcrypt.hash(thisObj.password, salt);
            return next();
        } catch (e) {
            return next(e);
        }
    });
    

    password validation method

    userSchema.methods.validatePassword = async function (pass: string) {
        return bcrypt.compare(pass, this.password);
    };
    

    and the default export

    export default mongoose.model('User', userSchema);
    

    note: don't forget to install type packages (@types/mongoose, @types/bcryptjs)

提交回复
热议问题