Guest User

Untitled

a guest
Mar 10th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. 'use strict';
  2.  
  3. const mongoose = require('mongoose');
  4. const Schema = mongoose.Schema;
  5. const isEmail = require('validator').isEmail;
  6. const Promise = require('bluebird');
  7. const bcrypt = require('bcrypt');
  8.  
  9. // define the User model
  10. const userSchema = new Schema({
  11. fullName: {
  12. type: String,
  13. required: 'Full Name is required',
  14. trim: true
  15. },
  16. emailAddress: {
  17. type: String,
  18. unique: 'Email Address is already on file and not available',
  19. lowercase: true,
  20. trim: true,
  21. validate: {validator: isEmail, message: '{VALUE} Is an invalid Email Address', isAsync: false},
  22. required: 'Email Address is required'
  23. },
  24. password: {
  25. type: String,
  26. required: 'Password is required',
  27. }
  28. });
  29.  
  30. // authenticate User
  31. userSchema.statics.authenticate = function(email, password, callback) {
  32. // search for user by email
  33. User.findOne({ emailAddress: email })
  34. .exec((err, user) => {
  35. if (err) {
  36. return callback(err);
  37. } else if (!user) {
  38. err = new Error('User Not Found');
  39. err.status = 401;
  40. return callback(err);
  41. }
  42. // validate password hashing with bcrypt
  43. bcrypt.compare(password, user.password, function (err, result) {
  44. if (result === true){
  45. return callback(null, user)
  46. } else{
  47. return callback();
  48. }
  49. });
  50. });
  51. };
  52.  
  53. // hash password prior to saving to database
  54. userSchema.pre('save', function(next) {
  55. const user = this;
  56. const saltRounds = 10;
  57. bcrypt.hash(user.password, saltRounds)
  58. .then(function(hash){ return user.password = hash; })
  59. .catch(function(err){
  60. return next(err);
  61. });
  62. });
  63.  
  64. module.exports = mongoose.model('User', userSchema);
Add Comment
Please, Sign In to add comment