aboutsummaryrefslogtreecommitdiff
path: root/config/passport.js
blob: c4368cb590268cd88e5df89a95473e488789d154 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');

const User = require('../models/user');

const strategyCallback = (email, password, done) => {
  // Try to find user
  User.findOne({email}, (err, user) => {
    // Database error
    if (err)
      return done(err);

    // No user found
    if (!user)
      return done(null, false);

    // Wrong password
    if (!bcrypt.compareSync(password, user.password))
      return done(null, false);

    // Successful login
    return done(null, user);
  })
};

passport.use(new LocalStrategy({usernameField: 'email'}, strategyCallback));

passport.serializeUser((user, done) => done(null, user._id));

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => done(err, user));
});