|
| 1 | +import passportJWT from 'passport-jwt'; |
| 2 | +import { UnauthenticatedError } from '../../errors'; |
| 3 | +import MESSAGES from '../../utils/messages'; |
| 4 | +import {mergedEnvironmentConfig} from '../../../config/env.config'; |
| 5 | +const JwtStrategy = passportJWT.Strategy; |
| 6 | +import { HEADERS } from '../../utils/constants'; |
| 7 | +var httpContext = require('express-http-context'); |
| 8 | +let currentUserToken = ''; |
| 9 | +const tokenExtractor = function (req) { |
| 10 | + let token = null; |
| 11 | + let tokenArray = []; |
| 12 | + |
| 13 | + if (req) { |
| 14 | + token = req.get(HEADERS.ACCESS_TOKEN); |
| 15 | + |
| 16 | + if (!token) { |
| 17 | + throw new UnauthenticatedError( |
| 18 | + MESSAGES.LOGIN_ERROR_USER_ACCESS_TOKEN_INVALID |
| 19 | + ); |
| 20 | + } |
| 21 | + |
| 22 | + tokenArray = token.split(' '); |
| 23 | + } |
| 24 | + currentUserToken =tokenArray[1]; |
| 25 | + return tokenArray[1]; |
| 26 | +}; |
| 27 | + |
| 28 | +const opts = { |
| 29 | + jwtFromRequest: tokenExtractor, //ExtractJwt.fromAuthHeaderAsBearerToken(), |
| 30 | + secretOrKey: mergedEnvironmentConfig.jwtSecret, |
| 31 | + passReqToCallback: true, |
| 32 | +}; |
| 33 | + |
| 34 | +const passportJwtStrategy = new JwtStrategy( |
| 35 | + opts, |
| 36 | + async (req, jwtPayload, done) => { |
| 37 | + try { |
| 38 | + let user = {}; |
| 39 | + |
| 40 | + // if jwt payload contains user obj then its an inter service communication call |
| 41 | + if (jwtPayload.user) { |
| 42 | + user = jwtPayload.user; |
| 43 | + } else if (jwtPayload.userId) { |
| 44 | + //TODO: add db level auth check |
| 45 | + |
| 46 | + // user = await User.findOne({ |
| 47 | + // where: { |
| 48 | + // id: jwtPayload.userId |
| 49 | + // }, |
| 50 | + // include: [{ model: UserOrganization, include: [{ model: Role }] }] |
| 51 | + // }); |
| 52 | + |
| 53 | + if (!user) { |
| 54 | + throw new UnauthenticatedError( |
| 55 | + MESSAGES.LOGIN_ERROR_USER_ACCESS_TOKEN_INVALID |
| 56 | + ); |
| 57 | + } else if (user.enabled === false) { |
| 58 | + throw new UnauthenticatedError( |
| 59 | + MESSAGES.LOGIN_ERROR_USER_ACCOUNT_DEACTIVATED |
| 60 | + ); |
| 61 | + } |
| 62 | + |
| 63 | + |
| 64 | + user = user.toJSON(); |
| 65 | + } |
| 66 | + // httpContext.set('request.req.user.token',currentUserToken); |
| 67 | + // httpContext.set('request.req.user.id',user.id); |
| 68 | + user.currentUserToken = currentUserToken; |
| 69 | + return done(null, user); |
| 70 | + } catch (err) { |
| 71 | + return done(err, null); |
| 72 | + } |
| 73 | + } |
| 74 | +); |
| 75 | + |
| 76 | +export default passportJwtStrategy; |
0 commit comments