-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpassport_jwt.js
32 lines (25 loc) · 924 Bytes
/
passport_jwt.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
const passport = require('passport');
const User = require('../models/user');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
//Options for jwt_strategy note key in header for token is authorization
const JwtOptions = {
jwtFromRequest: ExtractJwt.fromHeader('authorization'),
secretOrKey: process.env.JWT_SECRET
};
//Passport_jwt strategy 1. create new strategy 2. supply options as above 3.find user by sub which is user.id
const jwtLogin = new JwtStrategy(JwtOptions, (payload, done) => {
User.findById(payload.sub, (err, user) => {
if (err) {
return next(err);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
});
//wire up strategy to passport middleware
passport.use(jwtLogin);