User.js 1.5 KB

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