import { isNil } from 'lodash' ; import { AuthenticationContext , TokenResponse } from 'adal-node' ; import { RetryHelper , System } from 'common' ; import { Logger } from 'logger' ; import { ExtendOptions , Got } from 'got' ; export class A11yServiceCredential { private readonly authContext : AuthenticationContext ; constructor ( private readonly clientId , private readonly clientSecret , private readonly resourceId , authorityUrl , private readonly logger , context ? , private readonly maxTokenAttempts = 5 , private readonly msecBetweenRetries = 1000 , private readonly retryHelper = new RetryHelper ( ) ) { this . authContext = context || new ( < any > AuthenticationContext ) ( authorityUrl , undefined , undefined , '' ) ; } public async getToken ( ) { try { return await this . retryHelper . executeWithRetries ( ( ) => this . tryGetToken ( ) , ( err ) => this . handleGetTokenError ( err ) , this . maxTokenAttempts , this . msecBetweenRetries ) ; } catch ( error ) { throw new Error ( `Error while acquiring Azure AD client token. ${ System . serializeError ( error ) }` ) ; } } public async getHeaders ( ) { const accessToken = await this . getToken ( ) ; return { authorization : `${ accessToken . tokenType } ${ accessToken . accessToken }` } ; } public async signRequest ( gotRequest ) { const accessToken = await this . getToken ( ) ; const authOptions = { headers : { authorization : `${ accessToken . tokenType } ${ accessToken . accessToken }` , } , } ; return gotRequest . extend ( authOptions ) ; } private async tryGetToken ( ) { return new Promise ( ( resolve , reject ) => { this . authContext . acquireTokenWithClientCredentials ( this . resourceId , this . clientId , this . clientSecret , ( err , tokenResponse ) => { if ( ! isNil ( err ) ) { reject ( err ) ; } else { resolve ( tokenResponse as TokenResponse ) ; } } ) ; } ) ; } private async handleGetTokenError ( err ) { this . logger . logError ( `Error while acquiring Azure AD client token. ${ System . serializeError ( err ) }` ) ; } }