Browse Source

Add passport local strategy

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
parent
commit
ddf47757e4
No known key found for this signature in database GPG Key ID: 86A4D290ED03FAB4
  1. 57
      server/services/passport.js

57
server/services/passport.js

@ -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…
Cancel
Save