【问题标题】:How to Hash a Password with the Event Subscriber Typeorm如何使用事件订阅者 Typeorm 散列密码
【发布时间】:2022-04-05 23:47:04
【问题描述】:

快速提问:

我已经通过 StackOverflow 搜索并没有看到这样的直接问题,而且谷歌似乎没有给出很好的答案。

我正在使用 Nestjs 和 Typeorm,并且正在尝试使用 EventSubscriber() 对密码进行哈希处理。

代码如下: 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('$');
    }
}

我正在尝试在插入之前对密码进行哈希处理,然后将其设置为用户的密码。很简单的东西。我只是想确保我在这里做的方式是最好的方式。它有效,但我担心像我正在做的那样重置event.entity.password

任何反馈都将不胜感激,如果这不是这个问题的地方,请告诉我,我会移动它。 :) 谢谢!

【问题讨论】:

    标签: passwords nestjs typeorm pbkdf2


    【解决方案1】:

    你可以在你的实体定义中使用@BeforeInsert() 钩子来实现 喜欢:

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

    我把它写在这里,也许它有错误。试着自己写。 它非常适合散列密码或任何东西。

    【讨论】:

    • 是的,我最终选择了这条路!事件订阅者很酷 - 我想尝试一下。但为什么要重新发明轮子呢?
    • 这两个抽象的工作方式相同,但我遇到了事件订阅者的问题。例如,after insert 钩子在 SQL 调用之前运行,我无法设置关系或任何东西! (在 PostgresSQL 中)。为了更好地实现,请创建一个单独的类并将您的实现保存在类中,然后在您想要保持代码干净时调用它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多