import fs = require ( 'fs' ) ; import https = require ( 'https' ) ; import request = require ( 'request' ) ; import { Authenticator } from './auth' ; import { User } from './config_types' ; export class FileAuth implements Authenticator { private token : string | null = null ; private lastRead : Date | null = null ; public isAuthProvider ( user ) { return user . authProvider && user . authProvider . config && user . authProvider . config . tokenFile ; } public async applyAuthentication ( user , opts ) { if ( this . token == null ) { this . refreshToken ( user . authProvider . config . tokenFile ) ; } if ( this . isTokenExpired ( ) ) { this . refreshToken ( user . authProvider . config . tokenFile ) ; } if ( this . token ) { opts . headers ! . Authorization = `Bearer ${ this . token }` ; } } private refreshToken ( filePath ) { this . token = fs . readFileSync ( filePath ) . toString ( 'UTF-8' ) ; this . lastRead = new Date ( ) ; } private isTokenExpired ( ) { if ( this . lastRead === null ) { return true ; } const now = new Date ( ) ; const delta = ( now . getTime ( ) - this . lastRead . getTime ( ) ) / 1000 ; return delta > 60 ; } }