-
Notifications
You must be signed in to change notification settings - Fork 0
/
passport.js
49 lines (46 loc) · 1.17 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
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const JwtStrategy = require("passport-jwt").Strategy;
const User = require("./models/User");
//Extracts cookie from request
const cookieExtractor = (req) => {
let token = null;
if (req && req.cookies) {
token = req.cookies["access_token"];
}
return token;
};
//middleware - authorization to protect endpoints
passport.use(
new JwtStrategy(
{
jwtFromRequest: cookieExtractor,
secretOrKey: "TheDevCoder",
},
(payload, done) => {
User.findById({ _id: payload.sub }, (err, user) => {
if (err) {
return done(err, false);
} else if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}
)
);
//middleware - authenticated local strategy using username and password
passport.use(
new LocalStrategy((username, password, done) => {
User.findOne({ username }, (err, user) => {
if (err) {
return done(err);
} else if (!user) {
return done(null, false);
} else {
user.comparePassword(password, done);
}
});
})
);