user.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. username: { type: String, default: '' },
  11. location: { type: String, default: '' },
  12. website: { type: String, default: '' },
  13. bio: { type: String, default: '' },
  14. picture: { type: String, default: '' }
  15. },
  16. resetPasswordToken: String,
  17. resetPasswordExpires: Date
  18. });
  19. /********** PASS HASH **************/
  20. userSchema.pre('save', function(next) {
  21. var user = this;
  22. if (!user.isModified('password')) {
  23. return next();
  24. }
  25. bcrypt.genSalt(10, function(err, salt) {
  26. if (err) {
  27. return next(err);
  28. }
  29. bcrypt.hash(user.password, salt, null, function(err, hash) {
  30. if (err) {
  31. return next(err);
  32. }
  33. user.password = hash;
  34. next();
  35. });
  36. });
  37. });
  38. /********** PASS Valid **************/
  39. userSchema.methods.comparePassword = function(candidatePassword, cb) {
  40. bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  41. if (err) {
  42. return cb(err);
  43. }
  44. cb(null, isMatch);
  45. });
  46. };
  47. /********** Gravatar **************/
  48. userSchema.methods.gravatar = function(size) {
  49. if (!size) {
  50. size = 200;
  51. }
  52. if (!this.email) {
  53. return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';
  54. }
  55. var md5 = crypto.createHash('md5').update(this.email).digest('hex');
  56. return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';
  57. };
  58. module.exports = mongoose.model('User', userSchema);