Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mongoose = require ('mongoose');
- var bcrypt = require('bcryptjs');
- var Schema = mongoose.Schema;
- var SALT_WORK_FACTOR = 10;
- var touristSchema = new Schema ({
- local: {
- email: String,
- password: String
- },
- facebook: {
- id: String,
- token: String,
- email: String,
- name: String,
- }
- });
- touristSchema.pre('save', function(next) {
- var user = this;
- console.log('bcrypt called by strategy', user);
- // if user is facebook user skip the pasword thing.
- if (user.facebook.token) {
- next();
- }
- // only hash the password if it has been modified (or is new)
- if (!user.isModified('password') && !user.isNew){
- console.log('I am in here', user.isNew);
- return next();
- }
- // generate a salt
- bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
- console.log('I am in genSalt');
- if (err) return next(err);
- // hash the password using our new salt
- bcrypt.hash(user.local.password, salt, function(err, hash) {
- if (err) return next(err);
- // override the cleartext password with the hashed one
- user.local.password = hash;
- next();
- });
- });
- });
- touristSchema.methods.comparePassword = function(candidatePassword, cb) {
- bcrypt.compare(candidatePassword,this.local.password, function(err, isMatch) {
- // console.log(this.local.password);
- if (err) return cb(err);
- cb(null, isMatch);
- });
- };
- module.exports = mongoose.model('users', touristSchema);
- passport.use('local-login', new LocalStrategy({
- usernameField: 'email',
- passwordField: 'password',
- passReqToCallback: true
- },
- function(req, email, password, done) {
- process.nextTick(function() {
- User.findOne({ 'local.email': email }, function(err, user) {
- if(err)
- return done(err);
- if(!user)
- return done(null, false, req.flash('loginMessage', 'No User Found'));
- user.comparePassword(password, function(err, isMatch) {
- if (err) throw err;
- if (isMatch) {
- done(null, user);
- }
- else
- done(null, false, req.flash('loginMessage', 'Incorrect password'));
- });
- });
- });
- }
- ));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement