User.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. }, schemaOptions);
  24. userSchema.pre('save', function(next) {
  25. var user = this;
  26. if (!user.isModified('password')) { return next(); }
  27. bcrypt.genSalt(10, function(err, salt) {
  28. bcrypt.hash(user.password, salt, null, function(err, hash) {
  29. user.password = hash;
  30. next();
  31. });
  32. });
  33. });
  34. userSchema.methods.comparePassword = function(password, cb) {
  35. bcrypt.compare(password, this.password, function(err, isMatch) {
  36. cb(err, isMatch);
  37. });
  38. };
  39. userSchema.virtual('gravatar').get(function() {
  40. if (!this.get('email')) {
  41. return 'https://gravatar.com/avatar/?s=200&d=retro';
  42. }
  43. var md5 = crypto.createHash('md5').update(this.get('email')).digest('hex');
  44. return 'https://gravatar.com/avatar/' + md5 + '?s=200&d=retro';
  45. });
  46. userSchema.options.toJSON = {
  47. transform: function(doc, ret, options) {
  48. delete ret.password;
  49. delete ret.passwordResetToken;
  50. delete ret.passwordResetExpires;
  51. }
  52. };
  53. var User = mongoose.model('User', userSchema);
  54. module.exports = User;