Encryption and authentication

The encryption logic and salt generation logic, which are used to generate the hashed_password and salt values representing the password value, are defined as UserSchema methods.

mern-skeleton/server/models/user.model.js:

UserSchema.methods = {
authenticate: function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password
},
encryptPassword: function(password) {
if (!password) return ''
try {
return crypto
.createHmac('sha1', this.salt)
.update(password)
.digest('hex')
} catch (err) {
return ''
}
},
makeSalt: function() {
return Math.round((new Date().valueOf() * Math.random())) + ''
}
}

Additionally, the authenticate method is also defined as a UserSchema method, which is used when a user supplied password must be authenticated for sign-in.

The crypto module in Node is used to encrypt the user-provided password string into a hashed_password with a randomly generated salt value. The hashed_password and the salt is stored in the user document when the user details are saved to the database on a create or update. Both the hashed_password and salt values are required in order to match and authenticate a password string provided during user sign-in, using the authenticate method defined previously.