Browse Source
Local strategy handles login/register in one go. No need for 2 routes as we only require username and password.main
Haris Razis
4 years ago
1 changed files with 57 additions and 0 deletions
@ -0,0 +1,57 @@ |
|||
const bcrypt = require('bcrypt') |
|||
const passport = require('passport'); |
|||
const LocalStrategy = require('passport-local').Strategy; |
|||
const mongoose = require('mongoose'); |
|||
|
|||
const User = mongoose.model('User'); |
|||
|
|||
passport.serializeUser(function (user, done) { |
|||
done(null, user.id); |
|||
}); |
|||
|
|||
passport.deserializeUser(function (id, done) { |
|||
User.findById(id, function (err, user) { |
|||
done(err, user); |
|||
}); |
|||
}); |
|||
|
|||
passport.use('local', new LocalStrategy( |
|||
{usernameField: 'email'}, |
|||
(email, password, done) => { |
|||
User.findOne({email: email}) |
|||
.then(user => { |
|||
if (!user) { |
|||
const newUser = new User({email, password}); |
|||
bcrypt.genSalt(10, (err, salt) => { |
|||
bcrypt.hash(newUser.password, salt, (err, hash) => { |
|||
if (err) throw err; |
|||
newUser.password = hash; |
|||
newUser |
|||
.save() |
|||
.then(user => { |
|||
return done(null, user); |
|||
}) |
|||
.catch(err => { |
|||
return done(null, false, {message: err}); |
|||
}); |
|||
}); |
|||
}); |
|||
} else { |
|||
bcrypt.compare(password, user.password, (err, isMatch) => { |
|||
if (err) throw err; |
|||
|
|||
if (isMatch) { |
|||
return done(null, user); |
|||
} else { |
|||
return done(null, false, {message: 'Wrong password'}); |
|||
} |
|||
}); |
|||
} |
|||
}) |
|||
.catch(err => { |
|||
return done(null, false, {message: err}); |
|||
}); |
|||
}) |
|||
); |
|||
|
|||
module.exports = passport; |
Loading…
Reference in new issue