All files AuthHandler.ts

100% Statements 28/28
100% Branches 20/20
100% Functions 7/7
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59  2x             2x 2x   2x 6x 6x   6x 1x   1x 3x 2x       1x     5x 5x     9x       7x 3x 4x 1x     3x       2x 3x       3x   4x 6x       2x  
import { Application, Request } from 'express'
import * as expressJWT from 'express-jwt'
 
export interface ICache {
  // tslint:disable-next-line no-any
  [key: string]: any
}
 
export class AuthHandler {
  private static cache: Map<string, ICache> = new Map<string, ICache>()
 
  public static addPath (path: string, target: ICache, propertyKey?: string) {
    const className = target.name || target.constructor.name
    const cache: ICache = AuthHandler.cache.get(className) || {}
 
    if (!propertyKey) {
      const props = Object.getOwnPropertyNames(target.prototype)
 
      props.forEach((p: string) => {
        if (p !== 'constructor' && p in cache) {
          cache[p] = `${path}${cache[p]}`
        }
      })
 
      return
    }
 
    cache[propertyKey] = path
    AuthHandler.cache.set(className, cache)
  }
 
  public static readonly createDefaultJWTOptions = (secret: string): expressJWT.Options => ({
    secret,
    credentialsRequired: true,
    getToken: (req: Request): string | undefined => {
      if (req.headers.authorization && (req.headers.authorization as string).split(' ')[0] === 'Bearer') {
        return (req.headers.authorization as string).split(' ')[1]
      } else if (req.query && req.query.token) {
        return req.query.token
      }
 
      return undefined
    }
  })
 
  public static configure (app: Application, options: string | expressJWT.Options) {
    const ops = typeof options === 'string'
      ? AuthHandler.createDefaultJWTOptions(options)
      : options
 
    AuthHandler.cache.forEach((cache: ICache) => {
      // tslint:disable-next-line forin
      for (const route in cache) {
        app.use(cache[route], expressJWT(ops))
      }
    })
  }
}