ade*_*ola 6 javascript node.js typeorm nestjs
在 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));
};
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试将代码迁移到typeorm,我的翻译大致是
@BeforeInsert()
@BeforeUpdate()
hashPassword() {
// conditional to detect if password has changed goes here
this.password = bcrypt.hashSync(this.password, SALT_ROUNDS);
}
Run Code Online (Sandbox Code Playgroud)
问题是,我停留在!user.changed('password'). 是否有等效的功能可以在typeorm不推出我自己的解决方案的情况下执行此操作?
在@adetoola's own 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) {
//
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5647 次 |
| 最近记录: |