在 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) {
//
}
}
关于javascript - 你如何检测 typeorm 中的密码等属性是否已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697680/