So, I'm using TypeORM with the ActiveRecord pattern and have this entity
@Entity()
export class User {
@PrimaryGeneratedColumn()
public id: number;
@Column()
public username: string;
@Column()
public password: string;
@BeforeInsert()
public async hashPassword() {
this.password = await hashPassword(this.password);
}
}
now what I want to accomplish is rehashing my password when any given User changes BUT only if the password field changed. I have seen some answers where I should store the tempPassword as a field in the User class but if for some reason the server goes down I would lose that data. I have also seen some people suggest the Subscriber thing typeorm has and im interested in that but not exactly sure how I would implement this with that. for reference this is how I would do what I want to do with mongoose
UserSchema.pre("save", function(next) {
if (this.isModified("password") || this.isNew) {
// hash the password
}
})
any help is appreciated
You can use AfterLoad decorator to store old password as a private temporary variable and compare it with the new password.
private tempPassword: string;
@AfterLoad()
storeOriginalPassword() {
this.tempPassword = this.password;
}
@BeforeInsert()
public async hashPassword() {
if (this.password && this.password !== this.tempPassword) {
this.password = await hashPassword(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