User.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var crypto = require('crypto');
  2. var bcrypt = require('bcrypt-nodejs');
  3. var mongoose = require('mongoose');
  4. var schemaOptions = {
  5. timestamps: true,
  6. toJSON: {
  7. virtuals: true
  8. }
  9. };
  10. var userSchema = new mongoose.Schema({
  11. username: {type: String, unique: true},
  12. email: {type: String, unique: true},
  13. name: String,
  14. password: String,
  15. passwordResetToken: String,
  16. passwordResetExpires: Date,
  17. gender: String,
  18. location: String,
  19. website: String,
  20. picture: String,
  21. facebook: String,
  22. twitter: String,
  23. mod: Boolean
  24. }, schemaOptions);
  25. userSchema.pre('save', function(next) {
  26. var user = this;
  27. if (!user.isModified('password')) { return next(); }
  28. bcrypt.genSalt(10, function(err, salt) {
  29. bcrypt.hash(user.password, salt, null, function(err, hash) {
  30. user.password = hash;
  31. next();
  32. });
  33. });
  34. });
  35. userSchema.methods.comparePassword = function(password, cb) {
  36. bcrypt.compare(password, this.password, function(err, isMatch) {
  37. cb(err, isMatch);
  38. });
  39. };
  40. userSchema.virtual('gravatar').get(function() {
  41. if (!this.get('email')) {
  42. return 'https://gravatar.com/avatar/?s=200&d=retro';
  43. }
  44. var md5 = crypto.createHash('md5').update(this.get('email')).digest('hex');
  45. return 'https://gravatar.com/avatar/' + md5 + '?s=200&d=retro';
  46. });
  47. userSchema.options.toJSON = {
  48. transform: function(doc, ret, options) {
  49. delete ret.password;
  50. delete ret.passwordResetToken;
  51. delete ret.passwordResetExpires;
  52. }
  53. };
  54. var User = mongoose.model('User', userSchema);
  55. module.exports = User;