Guest User

Untitled

a guest
Mar 10th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. var mongoose = require("mongoose");
  2. var bcrypt = require("bcrypt");
  3. var Schema = mongoose.Schema;
  4. const SALT_WORK_FACTOR = 10;
  5.  
  6. var UserSchema = new Schema({
  7. email: { type: String, required: true, index: { unique: true } },
  8. password: { type: String, required: true }
  9. });
  10.  
  11. UserSchema.pre("save", function(next) {
  12. var user = this;
  13. // only hash the password if it has been modified (or is new)
  14. if (!user.isModified("password")) return next();
  15. // generate a salt
  16. bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
  17. if (err) return next(err);
  18.  
  19. // hash the password using our new salt
  20. bcrypt.hash(user.password, salt, function(err, hash) {
  21. if (err) return next(err);
  22.  
  23. // override the cleartext password with the hashed one
  24. user.password = hash;
  25. next();
  26. });
  27. });
  28. });
  29.  
  30. UserSchema.methods.comparePassword = function(candidatePassword, cb) {
  31. bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  32. if (err) return cb(err);
  33. cb(null, isMatch);
  34. });
  35. }
  36.  
  37. module.exports = mongoose.modle('User',UserSchema);
Add Comment
Please, Sign In to add comment