|
| 1 | +const { sign } = require('jsonwebtoken'); |
| 2 | +const GitHubStrategy = require('passport-github2').Strategy; |
| 3 | +const passport = require('passport'); |
| 4 | +const passportJwt = require('passport-jwt'); |
| 5 | + |
| 6 | +function authJwt(email) { |
| 7 | + return sign({ user: { email } }, `SECRET`); |
| 8 | +} |
| 9 | + |
| 10 | +passport.use( |
| 11 | + new GitHubStrategy( |
| 12 | + { |
| 13 | + clientID: `GITHUB_CLIENT_ID`, |
| 14 | + clientSecret: `GITHUB_CLIENT_SECRET`, |
| 15 | + // callbackURL: `${BASE_URL}${ENDPOINT}/auth/github/callback`, |
| 16 | + scope: ['user:email'], |
| 17 | + }, |
| 18 | + async (accessToken, refreshToken, profile, done) => { |
| 19 | + try { |
| 20 | + //* can include other required attributes |
| 21 | + const email = profile.emails[0].value; |
| 22 | + |
| 23 | + // Here you'd typically create a new or load an existing user and |
| 24 | + // store the bare necessary informations about the user in the JWT. |
| 25 | + const jwt = authJwt(email); |
| 26 | + |
| 27 | + return done(null, { email, jwt }); |
| 28 | + } catch (error) { |
| 29 | + return done(error); |
| 30 | + } |
| 31 | + } |
| 32 | + ) |
| 33 | +); |
| 34 | + |
| 35 | +// ? this can act as a common strategy for authtication using jwt |
| 36 | +passport.use( |
| 37 | + new passportJwt.Strategy( |
| 38 | + { |
| 39 | + jwtFromRequest(req) { |
| 40 | + if (!req.cookies) throw new Error('Missing cookie-parser middleware'); |
| 41 | + return req.cookies.jwt; |
| 42 | + }, |
| 43 | + secretOrKey: `SECRET`, |
| 44 | + }, |
| 45 | + async ({ user: { email } }, done) => { |
| 46 | + try { |
| 47 | + // Here you'd typically load an existing user |
| 48 | + // and use the data to create the JWT. |
| 49 | + const jwt = authJwt(email); |
| 50 | + |
| 51 | + return done(null, { email, jwt }); |
| 52 | + } catch (error) { |
| 53 | + return done(error); |
| 54 | + } |
| 55 | + } |
| 56 | + ) |
| 57 | +); |
0 commit comments