Advertisement
Guest User

Untitled

a guest
Jul 11th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. var mongoose = require('mongoose'),
  2. Schema = mongoose.Schema,
  3. bcrypt = require('bcryptjs'),
  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. admin: {type: Boolean, default: false}
  10. })
  11.  
  12.  
  13. UserSchema.pre('save', function(next) {
  14. var user = this
  15. if (!user.isModified('password')) return next()
  16. bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
  17. if (err) return next(err)
  18. bcrypt.hash(user.password, salt, function(err, hash) {
  19. if (err) return next(err)
  20. user.password = hash
  21. next()
  22. })
  23. })
  24. })
  25.  
  26. UserSchema.methods.comparePassword = function(candidatePassword, cb) {
  27. bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  28. if (err) return cb(err)
  29. cb(null, isMatch)
  30. })
  31. }
  32.  
  33. module.exports = mongoose.model('User', UserSchema)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement