-
Notifications
You must be signed in to change notification settings - Fork 0
/
passportSetup.js
50 lines (48 loc) · 1.33 KB
/
passportSetup.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
42
43
44
45
46
47
48
49
50
let localStrategy = require('passport-local').Strategy;
let bcrypt = require('bcrypt');
let models = require('./models');
function validPassword (user, password) {
return bcrypt.compareSync(password, user.password);
}
module.exports = function(passport) {
passport.serializeUser((user, done) => {
done(null, user.id);
})
passport.deserializeUser((id, done) => {
models.User.findOne({
where: {
'id': id
}
}).then(user => {
if (user === null) {
done(new Error('Wrong user id'));
}
done(null, user);
})
});
passport.use(new localStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) => {
return models.User.findOne({
where: {
'email': email
}
}).then(user => {
if (user === null) {
req.flash('message', 'Incorrect credentials')
return done(null, false);
} else if (user.password === null || user.password === undefined) {
req.flash('message', 'Please reset your password')
return done(null, false);
} else if (!validPassword(user, password)) {
req.flash('message', 'Password is incorrect')
return done(null, false);
}
return done(null, user);
}).catch(error => {
done(error, false);
})
}))
}