user.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var mongoose = require('mongoose');
  2. var bcrypt = require('bcryptjs');
  3. var UserSchema = new mongoose.Schema({
  4. email: {
  5. type: String,
  6. required: true
  7. },
  8. password: {
  9. type: String,
  10. required: true
  11. },
  12. computes: {
  13. type: Number,
  14. default: 0
  15. },
  16. date: {
  17. type: Date,
  18. default: Date.now
  19. }
  20. });
  21. var User = module.exports = mongoose.model('User', UserSchema);
  22. module.exports.createUser = function (newUser, callback) {
  23. bcrypt.genSalt(10, function(err, salt) {
  24. bcrypt.hash(newUser.password, salt, function(err, hash) {
  25. newUser.password = hash;
  26. newUser.save(callback);
  27. });
  28. });
  29. }
  30. module.exports.getUserByEmail = function (email, callback) {
  31. var query = { email: email };
  32. User.findOne(query, callback);
  33. }
  34. module.exports.getUserById = function (id, callback) {
  35. User.findById(id, callback);
  36. }
  37. module.exports.comparePassword = function(candidatePassword, hash, callback) {
  38. bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
  39. if(err) throw err;
  40. callback(null, isMatch);
  41. });
  42. }
  43. module.exports = User;