Objection.js: Hash user password on $beforeUpdate

Created on 14 Nov 2018  路  7Comments  路  Source: Vincit/objection.js

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:

https://github.com/scoutforpets/objection-password/blob/d2fdfa13a0cef604460eb8d8b29867f858ee5133/index.js#L34-L36

What can I do about that?

Most helpful comment

Np :)

All 7 comments

@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 :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bsdo64 picture bsdo64  路  3Comments

chen7david picture chen7david  路  3Comments

mycahjay-nms picture mycahjay-nms  路  4Comments

louis-etne picture louis-etne  路  4Comments

officer-rosmarino picture officer-rosmarino  路  4Comments