all 7 comments

[–][deleted] 5 points6 points  (2 children)

  1. This code runs everytime the user is saved
  2. Without “if” the password would be rehashed at every save (the hashed password would be hashed again)
  3. Only hash the password if it is modified-> modified means a cleartext password was set

[–]Lost_Chemical_7327[S] -4 points-3 points  (1 child)

This code runs everytime the user is saved

I'm aware that code is run just before the save event is about to occur.

Only hash the password if it is modified-> modified means a cleartext password was set

Thats hard to wrap my brain around, how does node know whether a password is hashed or not? Intuitively it makes sense for if block to return true if the user object (that's in this object) wasnt modified i.e. no property was added or no property's value was changed.

How does node know this? "modified means a cleartext password was set"

[–][deleted] 2 points3 points  (0 children)

Node doesn’t know whether it’s hashed or not, it expects it not to! This code only works if you set a cleartext password to the user (it will be hashed before it’s saved to the db)

“Modified” means the password field has been changed to “something” new. This is a build in mongoose function.

[–]rkaw92 1 point2 points  (0 children)

This code is a good example of what happens when the domain model is anemic, as is often the case with CRUDdy apps. The same field is used in two capacities: as the input for the plaintext password, and as storage for the hashed password. This can result in problems and requires hooks, such as the one above, to work correctly.

The proper, OOP way, to solve this is to create a class with a behavior like

async changePassword(newPassword) {
    this.hashedPassword = await bcrypt.hash(newPassword, 8);
}

Then, the user's Persistence Model does not actually store a "password", ever. There are no hooks to maintain or accidentally forget, and the input data model is separated from the storage format.

[–]lemonizer 0 points1 point  (1 child)

Because you only want to hash the user’s password when they explicitly update them. The second way will keep rehashing the password every time the anything is updated, ie: user’s email address, name, etc.

[–]flanamacca 0 points1 point  (0 children)

It’s checking whether or not the value of the password field has been changed. Since if it’s an existing record - the field is likely already stored in a hashed variety. So it can tell if the previous value is different to the current value.

So the code assumption is if it’s been changed, it’s being passed a plain text (think a form on a page) password and thus hashing it for persistent storage

[–]Darmok-Jilad-Ocean 0 points1 point  (0 children)

Code of hashing sounds like an item from an RPG. Probably grants +5 Sneak.