Advertisement
Guest User

Untitled

a guest
Jul 28th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. var mongoose = require ('mongoose');
  2. var bcrypt = require('bcryptjs');
  3. var Schema = mongoose.Schema;
  4. var SALT_WORK_FACTOR = 10;
  5. var touristSchema = new Schema ({
  6. local: {
  7. email: String,
  8. password: String
  9. },
  10. facebook: {
  11. id: String,
  12. token: String,
  13. email: String,
  14. name: String,
  15. }
  16. });
  17.  
  18.  
  19. touristSchema.pre('save', function(next) {
  20. var user = this;
  21. console.log('bcrypt called by strategy', user);
  22.  
  23. // if user is facebook user skip the pasword thing.
  24. if (user.facebook.token) {
  25. next();
  26. }
  27. // only hash the password if it has been modified (or is new)
  28. if (!user.isModified('password') && !user.isNew){
  29. console.log('I am in here', user.isNew);
  30. return next();
  31. }
  32. // generate a salt
  33. bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
  34. console.log('I am in genSalt');
  35.  
  36. if (err) return next(err);
  37.  
  38. // hash the password using our new salt
  39. bcrypt.hash(user.local.password, salt, function(err, hash) {
  40. if (err) return next(err);
  41.  
  42. // override the cleartext password with the hashed one
  43. user.local.password = hash;
  44. next();
  45. });
  46. });
  47. });
  48.  
  49. touristSchema.methods.comparePassword = function(candidatePassword, cb) {
  50. bcrypt.compare(candidatePassword,this.local.password, function(err, isMatch) {
  51. // console.log(this.local.password);
  52.  
  53. if (err) return cb(err);
  54. cb(null, isMatch);
  55. });
  56. };
  57.  
  58. module.exports = mongoose.model('users', touristSchema);
  59.  
  60. passport.use('local-login', new LocalStrategy({
  61. usernameField: 'email',
  62. passwordField: 'password',
  63. passReqToCallback: true
  64. },
  65. function(req, email, password, done) {
  66. process.nextTick(function() {
  67. User.findOne({ 'local.email': email }, function(err, user) {
  68. if(err)
  69. return done(err);
  70. if(!user)
  71. return done(null, false, req.flash('loginMessage', 'No User Found'));
  72. user.comparePassword(password, function(err, isMatch) {
  73. if (err) throw err;
  74. if (isMatch) {
  75. done(null, user);
  76. }
  77. else
  78. done(null, false, req.flash('loginMessage', 'Incorrect password'));
  79. });
  80. });
  81. });
  82. }
  83. ));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement