Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. const bcrypt = require('bcrypt-nodejs');
  2. const mongoose = require('mongoose');
  3.  
  4. const userSchema = new mongoose.Schema({
  5. email: {
  6. type: String,
  7. required: true,
  8. unique: true,
  9. },
  10. password: String,
  11. });
  12.  
  13. /**
  14. * Password hash middleware.
  15. */
  16. userSchema.pre('save', function save(next) {
  17. const user = this;
  18. if (!user.isModified('password')) { return next(); }
  19. bcrypt.genSalt(10, (err, salt) => {
  20. if (err) { return next(err); }
  21. bcrypt.hash(user.password, salt, null, (err, hash) => {
  22. if (err) { return next(err); }
  23. user.password = hash;
  24. next();
  25. });
  26. });
  27. });
  28.  
  29. /**
  30. * Helper method for validating user's password.
  31. */
  32. userSchema.methods.comparePassword = function comparePassword(candidatePassword) {
  33. return new Promise((resolve, reject) => {
  34. bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
  35. if (err) { reject(err); }
  36. resolve(isMatch);
  37. });
  38. });
  39. };
  40.  
  41. const User = mongoose.model('User', userSchema);
  42.  
  43. module.exports = User;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement