Guest User

Untitled

a guest
Jun 11th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. //written by Carlos Alba
  2.  
  3. var mongoose = require('mongoose');
  4. var bcrypt = require('bcrypt');
  5.  
  6. var UserSchema = new mongoose.Schema({
  7. email: {
  8. type: String,
  9. unique: true,
  10. required: true,
  11. trim: true
  12. },
  13. username: {
  14. type: String,
  15. unique: true,
  16. required: true,
  17. trim: true
  18. },
  19. password: {
  20. type: String,
  21. required: true,
  22. },
  23. passwordConf: {
  24. type: String,
  25. required: true,
  26. }
  27. });
  28.  
  29. //authenticate input against database
  30. UserSchema.statics.authenticate = function (email, password, callback) {
  31. User.findOne({
  32. email: email
  33. })
  34. .exec(function (err, user) {
  35. if (err) {
  36. return callback(err)
  37. } else if (!user) {
  38. var err = new Error('User not found.');
  39. err.status = 401;
  40. return callback(err);
  41. }
  42. bcrypt.compare(password, user.password, function (err, result) {
  43. if (result === true) {
  44. return callback(null, user);
  45. } else {
  46. return callback();
  47. }
  48. })
  49. });
  50. }
  51.  
  52. //hashing a password before saving it to the database
  53. UserSchema.pre('save', function (next) {
  54. var user = this;
  55.  
  56. bcrypt.hash(user.password, 10, function (err, hash) {
  57. if (err) {
  58. return next(err);
  59. }
  60. user.password = hash;
  61. next();
  62. })
  63.  
  64. });
  65.  
  66. //user password conf hashing
  67. UserSchema.pre('save', function (next) {
  68. var user = this;
  69.  
  70. bcrypt.hash(user.passwordConf, 10, function (err, hash) {
  71. if (err) {
  72. return next(err);
  73. }
  74. user.passwordConf = hash;
  75. next();
  76. })
  77.  
  78. });
  79.  
  80.  
  81. var User = mongoose.model('User', UserSchema);
  82. module.exports = User;
Add Comment
Please, Sign In to add comment