Guest User

Untitled

a guest
Nov 21st, 2018
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. // grab the things we need
  2. var mongoose = require("mongoose");
  3. var bcrypt = require("bcryptjs");
  4. let SALT_WORK_FACTOR = 10;
  5. var userSchema = new mongoose.Schema({
  6. username: { type: String, required: true, unique: true },
  7. password: { type: String, required: true }
  8. });
  9.  
  10. userSchema.pre("save", function(next) {
  11. var user = this;
  12.  
  13. if (!user.isModified("password")) return next();
  14.  
  15.  
  16. bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
  17. if (err) return next(err);
  18.  
  19. bcrypt.hash(user.password, salt, function(err, hash) {
  20. if (err) return next(err);
  21.  
  22.  
  23. user.password = hash;
  24. next();
  25. });
  26. });
  27. });
  28.  
  29. userSchema.methods.comparePassword = function(candidatePassword, cb) {
  30. bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  31. if (err) return cb(err);
  32. cb(null, isMatch);
  33. });
  34. };
  35.  
  36. var User = mongoose.model("User", userSchema);
  37.  
  38.  
  39. module.exports = User;
Add Comment
Please, Sign In to add comment