I'm writing a few methods to hash the user password using argon2 but I'm having a hard time to understand something:
That is how my code looks like in my User model
async $beforeInsert(context) {
await super.$beforeInsert(context)
return this.generateHash()
}
async $beforeUpdate(options, context) {
await super.$beforeUpdate(options, context)
if (options.patch) {
return false
}
return this.generateHash()
}
async generateHash() {
const hash = await argon2.hash(this.password)
this.password = hash
}
It works nice, the only problem tho is on the $beforeUpdate.
If I don't use the
if (options.patch) {
return false
}
When I call patchAndFetchById it hashes the password again changing it (not the behavior I want).
The behavior I wanted is: if the user changed the password it would hash again, otherwise it would keep the hashed password.
The reason: the only way now to change the user password is by calling updateAndFetchById but it requires all the fields again from the user.
And beforehand the https://github.com/scoutforpets/objection-password has the same behavior:
What can I do about that?
@zefexdeveloper You are mixing your persistence and business logic. Are you sure you want to do that?
@kibertoad what you mean? I'm only asking this cause I was used to do that when using mongoose and also sequelize, I could hash the password before inserting or updating, what do you recommend?
... by the way, thank you for answering, nice to have you active here helping us.
@zefexdeveloper In general I would advise against having "smart" persistence layer that performs such transformations as automatic password encryption. Usually this causes more headache than it's worth. I definitely recommend hashing password before inserting or updating it, especially because this is a very special case that is going to be different from how you handle pretty much everything.
@kibertoad I get what you mean, so instead of hashing the password in the models I hash in the API itself, when the user sends a post request for creating a new user, I get his password, hash it and then insert in the database, is that it?
@zefexdeveloper Yup, I would definitely recommend this approach.
@kibertoad Thank you for that, I was actually thinking about it and you just opened my mind.
Np :)
Most helpful comment
Np :)