Search code examples
passwordsnestjstypeormpbkdf2

How to Hash a Password with the Event Subscriber Typeorm


quick question:

I have searched through StackOverflow and havent seen a direct question like this, also google seems to not give a good answer.

I am using Nestjs and Typeorm and am attemtping to hash a password using the EventSubscriber().

Here is the Code: user.subscriber.ts

@EventSubscriber()
export class UserSubscriber implements EntitySubscriberInterface<User> {
    private iterations = Number(process.env.PASSWORD_ITERATIONS);
    // eslint-disable-next-line @typescript-eslint/ban-types
    public listenTo(): Function | string {
        return User;
    }

    public afterLoad(
        entity: User,
        event?: LoadEvent<User>,
    ): Promise<any> | void {}

    public beforeInsert(event: InsertEvent<User>): Promise<any> | void {
        const { password } = event.entity;
        const salt = crypto.randomBytes(20).toString('hex');
        const hash = crypto
            .pbkdf2Sync(password, salt, this.iterations, 32, 'sha512')
            .toString('hex');
        event.entity.password = [salt, hash].join('$');
    }
}

I am attempting to hash the password beforeInsert, and then set it as the user's password. Pretty easy stuff. I just wanted to ensure that the way I did it here would be the best way. It works, but I am worried about resetting the event.entity.password like I am doing.

any feedback would be appreciated, and if this is not the place for this question please let me know and I will move it. :) thanks!


Solution

  • you can do it inside your Entity definition by using @BeforeInsert() hooks like:

    @Entity()
    export class JohnEntity {
    
        @BeforeInsert()
        hashPassword() {
            const hashedPassword = hashMyPass(this.password);
            this.password = hashedPassword;
        } 
    
        @Column('text') password: string;
    }
    

    I write it down here and maybe it has errors. try to write it yourself. it will work very well for hashing passwords or anything.