user.js 1.7 KB

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