|
| 1 | +/* eslint no-underscore-dangle: ["error", { "allow": ["_id"] }] */ |
| 2 | +import { Strategy, ExtractJwt } from 'passport-jwt'; |
| 3 | +import passport from 'passport'; |
| 4 | +import mongoose from 'mongoose'; |
| 5 | + |
| 6 | +export default (app) => { |
| 7 | + const UserModel = mongoose.model('User'); |
| 8 | + |
| 9 | + passport.use(new Strategy( |
| 10 | + { |
| 11 | + jwtFromRequest: ExtractJwt.fromExtractors([ |
| 12 | + ExtractJwt.fromUrlQueryParameter('auth_token'), |
| 13 | + ExtractJwt.fromAuthHeaderAsBearerToken(), |
| 14 | + ]), |
| 15 | + secretOrKey: process.env.AUTH_JWT_SECRET, |
| 16 | + }, |
| 17 | + async (jwtPayload, done) => { |
| 18 | + try { |
| 19 | + const user = await UserModel.findById(jwtPayload._id); |
| 20 | + if (!user) { |
| 21 | + return done(null, false); |
| 22 | + } |
| 23 | + return done(null, user); |
| 24 | + } catch (err) { |
| 25 | + return done(err, false); |
| 26 | + } |
| 27 | + }, |
| 28 | + )); |
| 29 | + |
| 30 | + app.use((req, res, next) => { |
| 31 | + passport.authenticate('jwt', { session: true }, (err, user) => { |
| 32 | + // console.log(info); |
| 33 | + if (user) { |
| 34 | + req.user = user; |
| 35 | + } |
| 36 | + next(); |
| 37 | + })(req, res, next); |
| 38 | + }); |
| 39 | + |
| 40 | + app.get('/test', (req, res) => { |
| 41 | + res.send({ query: req.query, user: req.user }); |
| 42 | + }); |
| 43 | +}; |
0 commit comments