user.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. var mongoose = require('mongoose'),
  2. Schema = mongoose.Schema,
  3. bcrypt = require('bcrypt'),
  4. SALT_WORK_FACTOR = 10;
  5. var UserSchema = new Schema({
  6. username: { type: String, required: true, index: { unique: true } },
  7. password: { type: String, required: true },
  8. language: {type: String, required: true, default: 'en'},
  9. created_at: {type: Date, 'default': Date.now}
  10. });
  11. UserSchema.statics.getAuthenticated = function(username, password, callback) {
  12. this.findOne({ username: username }, function(error, user) {
  13. if (error) {
  14. console.error(error);
  15. return callback(error);
  16. }
  17. // make sure the user exists
  18. if (!user) {
  19. return callback(null, null, 404);
  20. }
  21. user.comparePassword(password, function(error, isMatch) {
  22. if (isMatch) {
  23. return callback(null, user);
  24. }
  25. return callback(null, null, 401);
  26. });
  27. });
  28. };
  29. UserSchema.pre('save', function(next) {
  30. var user = this;
  31. // only hash the password if it has been modified (or is new)
  32. if (!user.isModified('password')) {
  33. return next();
  34. }
  35. // generate a salt
  36. bcrypt.genSalt(SALT_WORK_FACTOR, function(error, salt) {
  37. if (error) {
  38. console.log(error);
  39. return next(error);
  40. }
  41. // hash the password using our new salt
  42. bcrypt.hash(user.password, salt, function(error, hash) {
  43. if (error) {
  44. return next(error);
  45. }
  46. // override the cleartext password with the hashed one
  47. user.password = hash;
  48. next();
  49. });
  50. });
  51. });
  52. UserSchema.methods.comparePassword = function(candidatePassword, callback) {
  53. bcrypt.compare(candidatePassword, this.password, function(error, isMatch) {
  54. if (error) {
  55. return callback(error);
  56. }
  57. callback(null, isMatch);
  58. });
  59. };
  60. var User = mongoose.model('User', UserSchema);
  61. User.schema.path('username').validate(function (username) {
  62. return username.length;
  63. }, 'Username cannot be blank');
  64. User.schema.path('password').validate(function(password) {
  65. return password.length;
  66. }, 'Password cannot be blank');
  67. User.schema.path('language').validate(function(language) {
  68. return /en|fr/i.test(language);
  69. }, 'Unknown language ("en" or "fr" only)')
  70. module.exports = User;