Advertisement
Guest User

Untitled

a guest
Aug 6th, 2016
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. var mongoose = require('mongoose'),
  2. Schema = mongoose.Schema,
  3. bcrypt = require('bcrypt'),
  4. SALT_WORK_FACTOR = 10;
  5.  
  6. var UserSchema = new Schema({
  7. username: { 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.  
  14. // only hash the password if it has been modified (or is new)
  15. if (!user.isModified('password')) return next();
  16.  
  17. // generate a salt
  18. bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
  19. if (err) return next(err);
  20.  
  21. // hash the password using our new salt
  22. bcrypt.hash(user.password, salt, function(err, hash) {
  23. if (err) return next(err);
  24.  
  25. // override the cleartext password with the hashed one
  26. user.password = hash;
  27. next();
  28. });
  29. });
  30.  
  31.  
  32. });
  33.  
  34. UserSchema.methods.comparePassword = function(candidatePassword, cb) {
  35. bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  36. if (err) return cb(err);
  37. cb(null, isMatch);
  38. });
  39. };
  40.  
  41. module.exports = mongoose.model(User, UserSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement