Skip to content

Commit

Permalink
feature #11: Add password compare to User Model
Browse files Browse the repository at this point in the history
  • Loading branch information
Boosmith committed Aug 26, 2019
1 parent e7fa0b0 commit 5073849
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/api/user/userModel.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const userSchema = mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
address: { type: String, required: true },
city: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
password: { type: String, required: true },
postcode: { type: String, required: true }
});

Expand All @@ -20,6 +22,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 5073849

Please sign in to comment.