在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
中是否有等效的功能来执行此操作而无需推出自己的解决方案?
答案 0 :(得分:1)
此问题的解决方案在@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) {
//
}
}
答案 1 :(得分:0)
您可以尝试以下方法:
@BeforeInsert()
@BeforeUpdate()
hashPassword() {
if (this.password) {
this.password = createHmac('sha256', this.password).digest('hex');
}
}
我只是检查DTO中是否存在密码(在更新和插入之前)。如果存在,我应该对其进行哈希处理。
答案 2 :(得分:0)
----------
private tempPassword: string
/// commit to handle the password if i not change it it will be not encription
@AfterLoad()
private loadTempPassword(): void {
this.tempPassword = this.password;
}
@BeforeInsert()
@BeforeUpdate()
async hashPassword(): Promise<void> {
// cheack if that password changing or not
if (this.tempPassword !== this.password) {
try {
this.password = await bcrypt.hash(this.password, 10)
} catch (e) {
throw new InternalServerErrorException('there are some issiue in the hash')
}
}
}
答案 3 :(得分:0)
我们可以从列中选择密码
@Column('string', { select: false })
password:string
然后我们尝试散列
we check if the password is found or not
if (this.password) {
//make hash
}
或其他方式 它应该使私有 tempPassword: string
@AfterLoad()
private loadTempPassword(): void {
this.tempPassword = this.password;
}
或
@BeforeInsert()
@BeforeUpdate()
async hashPassword(): Promise<void> {
// cheack if that password changing or not
if (this.password) {
if (this.tempPassword !== this.password) {
try {
this.password = await bcrypt.hash(this.password, 10)
} catch (e) {
throw new InternalServerErrorException('there are some issiue in the hash')
}
}
}