-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathauth.js
33 lines (29 loc) · 915 Bytes
/
auth.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
const passport = require('passport');
const LocalStrategy = require('passport-local');
const bcrypt = require('bcryptjs');
const User = require("./models/User");
module.exports = {
init: () => {
passport.use(
new LocalStrategy({ usernameField: 'email' }, async (email, password, done) => {
const user = await User.findOne({where: { email }});
if(!user) return done(null, false);
if(!bcrypt.compareSync(password, user.password)) return done(null, false);
return done(null, user);
})
);
passport.serializeUser((user, done) => {;
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
const user = await User.findOne({where: { id }});
done(null, user);
});
},
protectRoute: (req, res, next) =>{
if(req.isAuthenticated()) {
return next();
}
res.redirect('/login?next=' + req.url);
}
};