import { ExtractJwt , JwtFromRequestFunction , Strategy as JwtStrategy , StrategyOptions , VerifiedCallback } from 'passport-jwt' ; import config from '../config/main' ; import { User } from '../models/User' ; import * as cookie from 'cookie' ; interface PassportJwtStrategyFactoryOptions { name ? : String ; extractJwtFromCookie ? : Boolean ; extractJwtFromAuthHeaderWithScheme ? : Boolean ; extractJwtFromUrlQueryParameter ? : Boolean ; } function passportJwtStrategyFactory ( { name = 'jwt' , extractJwtFromCookie = true , extractJwtFromAuthHeaderWithScheme = false , extractJwtFromUrlQueryParameter = false , } = { } ) { const jwtFromRequestLayers = [ ] ; if ( extractJwtFromCookie ) { jwtFromRequestLayers . push ( ( req ) => req && typeof req . headers . cookie === 'string' && cookie . parse ( req . headers . cookie ) . token ) ; } if ( extractJwtFromAuthHeaderWithScheme ) { jwtFromRequestLayers . push ( ExtractJwt . fromAuthHeaderWithScheme ( 'jwt' ) ) ; } if ( extractJwtFromUrlQueryParameter ) { jwtFromRequestLayers . push ( ExtractJwt . fromUrlQueryParameter ( 'jwt' ) ) ; } const jwtFromRequest = ( request ) => { let token = null ; for ( const layer of jwtFromRequestLayers ) { token = layer ( request ) ; if ( token ) { break ; } } return token ; } ; const opts = { jwtFromRequest , secretOrKey : config . secret } ; const verify = async ( payload , done ) => { try { if ( await User . findById ( payload . _id ) ) { done ( null , { tokenPayload : payload } ) ; } else { done ( null , false ) ; } } catch ( error ) { done ( error ) ; } } ; const jwtStrategy = new JwtStrategy ( opts , verify ) ; ( jwtStrategy as any ) . name = name ; return jwtStrategy ; } export default passportJwtStrategyFactory ;