Skip to content

Commit

Permalink
feature #11: User model password hashing.
Browse files Browse the repository at this point in the history
  • Loading branch information
Boosmith committed Aug 27, 2019
1 parent 41a1f83 commit 9fbddcc
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/api/user/userModel.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
Expand All @@ -23,6 +24,30 @@ userSchema.virtual("name").get(() => {
return this.lastName + ", " + this.firstName;
});

userSchema.pre("save", function(next) {
const user = this;
if (!this.isModified("password")) {
next();
} else {
bcrypt.hash(user.password, 10, function(err, hash) {
if (err) {
next(err);
} else {
user.password = hash;
next();
}
});
}
});
userSchema.methods = {
comparePassword(receivedPassword, next) {
bcrypt.compare(receivedPassword, this.password, function(err, isMatch) {
if (err) return next(err);
next(null, isMatch);
});
}
};

const userModel = mongoose.model("User", userSchema);

module.exports = userModel;

0 comments on commit 9fbddcc

Please sign in to comment.