-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassport-config.js
41 lines (34 loc) · 1.56 KB
/
passport-config.js
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
34
35
36
37
38
39
40
41
const LocalStrategy = require('passport-local').Strategy;
const auth = require('./controllers/auth');
const bcrypt = require('bcrypt');
const User = require('./models/user');
function initialize(passport) {
const authenticateUser = async (req, email, password, done) => {
const hashed = await bcrypt.hash(password, 10);
User.findOne({ 'email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (hashed != user.password)
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}
passport.use(new LocalStrategy({ usernameField: 'username', passReqToCallback: 'password', passReqToCallback: true },
authenticateUser));
passport.serializeUser((user, done) => done(null, user._id))
passport.deserializeUser((id, done) => {
User.findById(id, (err, docs) => {
if (err) done(err)
if (docs) {
done(null, docs)
}
})
})
}
module.exports = initialize