User.js 1.5 KB

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