user.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var bcrypt = require('bcrypt-nodejs');
  2. var crypto = require('crypto');
  3. var mongoose = require('mongoose');
  4. var userSchema = new mongoose.Schema({
  5. email: { type: String, unique: true, lowercase: true },
  6. password: String,
  7. tokens: Array,
  8. profile: {
  9. name: { type: String, default: '' },
  10. website: { type: String, default: '' },
  11. picture: { type: String, default: '' }
  12. },
  13. resetPasswordToken: String,
  14. resetPasswordExpires: Date
  15. });
  16. /********** PASS HASH **************/
  17. userSchema.pre('save', function(next) {
  18. var user = this;
  19. if (!user.isModified('password')) {
  20. return next();
  21. }
  22. bcrypt.genSalt(10, function(err, salt) {
  23. if (err) {
  24. return next(err);
  25. }
  26. bcrypt.hash(user.password, salt, null, function(err, hash) {
  27. if (err) {
  28. return next(err);
  29. }
  30. user.password = hash;
  31. next();
  32. });
  33. });
  34. });
  35. /********** PASS Valid **************/
  36. userSchema.methods.comparePassword = function(candidatePassword, cb) {
  37. bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  38. if (err) {
  39. return cb(err);
  40. }
  41. cb(null, isMatch);
  42. });
  43. };
  44. module.exports = mongoose.model('User', userSchema);