-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassport.js
50 lines (47 loc) · 1.2 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').Strategy;
const JWTStrategy = require('passport-jwt').Strategy;
const User = require('./models/User');
const cookieExtractor = (req) => {
let token = null;
if (req && req.cookies) {
token = req.cookies['access_token'];
}
return token;
};
// authorization, protecting endpoints
passport.use(
new JWTStrategy(
{
jwtFromRequest: cookieExtractor,
secretOrKey: '0NtbJkk6hr',
},
(payload, done) => {
// user id will be the same as the payload sub
User.findById({ _id: payload.sub }, (err, res) => {
if (err) {
return done(err, false); // return error
} else if (res) {
return done(null, res); // return user
} else {
return done(null, false);
}
});
}
)
);
// authentication
passport.use(
new LocalStrategy((username, password, done) => {
User.findOne({ username }, (err, res) => {
if (err) {
// database error
return done(err);
} else if (!res) {
// no user exists
return done(null, false);
}
res.comparePassword(password, done); // check password
});
})
);