In typeorm, I am trying to use a subscriber decorator to hash users password before persisting to the database. Unfortunately, I can't find a reference in the docs.
In sequelizejs, I use the following code,
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));
};
Right now, I am trying to migrate the code to typeorm
and my translation is roughly
@BeforeInsert()
@BeforeUpdate()
hashPassword() {
// conditional to detect if password has changed goes here
this.password = bcrypt.hashSync(this.password, SALT_ROUNDS);
}
The issue is, I stuck at !user.changed('password')
. Is there an equivalent function in typeorm
to do this without rolling out my own solution?
The solution to this question was found in @adetoola's own issue.
You can use @AfterLoad
to load the user password and check if the current password is different:
@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) {
//
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With