-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpassport.js
50 lines (46 loc) · 1.14 KB
/
passport.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
const passport = require("passport");
const LocalStrategy = require("passport-local");
const JwtStrategy = require("passport-jwt").Strategy;
const User = require("./models/user.model");
const cookieExtractor = (req) => {
let token = null;
if (req && req.cookies) {
token = req.cookies["access_token"];
}
return token;
};
passport.use(
new JwtStrategy(
{
jwtFromRequest: cookieExtractor,
secretOrKey: process.env.JWTKey,
},
(payload, next) => {
User.findById({ _id: payload.userId }, (err, user) => {
if (err) return next(err);
if (user) {
const { _id, email, role } = user;
const userData = {_id, email, role}
return next(null, userData);
}
else return next(null, false);
});
}
)
);
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
(email, password, next) => {
User.findOne({ email }, (err, user) => {
if (err) return next(err);
if (!user) return next(null, false);
user.comparePassword(password, next);
});
}
)
);
module.exports = passport;