import * as express from 'express' ; import { injectable } from 'inversify' ; import { BaseMiddleware } from 'inversify-express-utils' ; import { HeaderKeys , Environments } from '@centsideas/enums' ; import { SecretsConfig , GlobalConfig } from '@centsideas/config' ; import { AccessToken , UserId } from '@centsideas/types' ; const getUserId = ( accessToken , accessTokenSecret , isProd ) => { try { const { userId } = AccessToken . fromString ( accessToken , accessTokenSecret ) ; return userId ; } catch ( error ) { if ( ! isProd ) return UserId . fromString ( accessToken ) ; throw error ; } } ; @ injectable ( ) export class AuthMiddleware extends BaseMiddleware { private accessTokenSecret = this . secretsConfig . get ( 'secrets.tokens.access' ) ; private isProd = this . globalConfig . get ( 'global.environment' ) === Environments . Prod ; constructor ( private secretsConfig , private globalConfig ) { super ( ) ; } handler ( req , res , next ) { try { const authHeader = req . headers [ HeaderKeys . Auth ] ; const accessToken = authHeader ?. split ( ' ' ) [ 1 ] || '' ; const userId = getUserId ( accessToken , this . accessTokenSecret , this . isProd ) ; res . locals . userId = userId . toString ( ) ; next ( ) ; } catch ( error ) { next ( error ) ; } } } @ injectable ( ) export class OptionalAuthMiddleware extends BaseMiddleware { private accessTokenSecret = this . secretsConfig . get ( 'secrets.tokens.access' ) ; private isProd = this . globalConfig . get ( 'global.environment' ) === Environments . Prod ; constructor ( private secretsConfig , private globalConfig ) { super ( ) ; } handler ( req , res , next ) { try { const authHeader = req . headers [ HeaderKeys . Auth ] ; const accessToken = authHeader ?. split ( ' ' ) [ 1 ] || '' ; const userId = getUserId ( accessToken , this . accessTokenSecret , this . isProd ) ; res . locals . userId = userId . toString ( ) ; next ( ) ; } catch ( error ) { res . locals . userId = undefined ; next ( ) ; } } }