user.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. /********** Gravatar **************/
  45. userSchema.methods.gravatar = function(size) {
  46. if (!size) {
  47. size = 200;
  48. }
  49. if (!this.email) {
  50. return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';
  51. }
  52. var md5 = crypto.createHash('md5').update(this.email).digest('hex');
  53. return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';
  54. };
  55. module.exports = mongoose.model('User', userSchema);