user.js 1.6 KB

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