在typeorm中,我试图在持久化到数据库之前使用订阅者装饰器来哈希用户密码。不幸的是,我在文档中找不到引用。
在sequelizejs中,我使用以下代码,
User.hashPassword = (user, options) => {
if (!user.changed('password')) {
return null;
}
// hash password
return Bcrypt.hash(user.get('password'), SALT_ROUNDS)
.then(hash => user.set('password', hash));
};
现在,我正在尝试将代码迁移到typeorm
,我的翻译大致是
@BeforeInsert()
@BeforeUpdate()
hashPassword() {
// conditional to detect if password has changed goes here
this.password = bcrypt.hashSync(this.password, SALT_ROUNDS);
}
问题是,我坚持在!user.changed('password')
。在没有推出我自己的解决方案的情况下,在typeorm
中有相同的功能吗?
这个问题的解决方案是在@ adetoola自己的issue中找到的。您可以使用@AfterLoad
加载用户密码并检查当前密码是否不同:
@Entity()
export class User extends BaseEntity {
@PrimaryColumn()
public username: string;
@Column()
public password: string;
@Column({ nullable: true })
public jwtToken: string;
private tempPassword: string;
@AfterLoad()
private loadTempPassword(): void {
this.tempPassword = this.password;
}
@BeforeUpdate()
private encryptPassword(): void {
if (this.tempPassword !== this.password) {
//
}
}
你可以试试这个:
@BeforeInsert()
@BeforeUpdate()
hashPassword() {
if (this.password) {
this.password = createHmac('sha256', this.password).digest('hex');
}
}
我只是检查DTO中是否存在密码(在更新和插入之前)。如果它存在,我应该哈希它。