import { NextFunction , Request , RequestHandler , Response } from "express" ; import ILogger from "../../common/ILogger" ; import IAuthenticator from "../authentication/IAuthenticator" ; import BlobStorageContext from "../context/BlobStorageContext" ; import StorageErrorFactory from "../errors/StorageErrorFactory" ; import ExpressRequestAdapter from "../generated/ExpressRequestAdapter" ; import { DEFAULT_CONTEXT_PATH } from "../utils/constants" ; export default class AuthenticationMiddlewareFactory { constructor ( private readonly logger ) { } public createAuthenticationMiddleware ( authenticators ) { return ( req , res , next ) => { const context = new BlobStorageContext ( res . locals , DEFAULT_CONTEXT_PATH ) ; this . authenticate ( req , res , authenticators ) . then ( pass => { if ( pass ) { next ( ) ; } else { next ( StorageErrorFactory . getAuthorizationFailure ( context . contextId ! ) ) ; } } ) . catch ( next ) ; } ; } private async authenticate ( req , res , authenticators ) { const request = new ExpressRequestAdapter ( req ) ; const context = new BlobStorageContext ( res . locals , DEFAULT_CONTEXT_PATH ) ; this . logger . verbose ( `AuthenticationMiddlewareFactory:createAuthenticationMiddleware() Validating authentications.` , context . contextId ) ; let pass = false ; for ( const authenticator of authenticators ) { pass = await authenticator . validate ( request , context ) ; if ( pass === true ) { return true ; } } return false ; } }