import { inject, injectable } from "inversify"; import { IAuth, IAuthParams, IGetAccessTokenParams, IGetAccessTokenResponse, IAccessTokenResponse, IHttpClient, IGetAccessTokenError, } from "./interfaces"; import AuthRequestBuilder from "./authRequestBuilder"; import * as TYPES from "./types"; @injectable() export default class Auth implements IAuth { clientId: string; host: string; redirectUri: string; @inject(TYPES.HttpClient) http: IHttpClient; constructor(@inject(TYPES.AuthParams) { clientId, host }: IAuthParams) { this.clientId = clientId; this.host = host; } private buildAccessTokenUrl(scope: string[]) { return new AuthRequestBuilder({ host: this.host, options: { clientId: this.clientId, scope, redirectUri: `${this.host.replace(/http:/, "https:")}/sso`, } }) .getAccessTokenUrl(); } getAccessToken(params: IGetAccessTokenParams) { return new Promise((resolve, reject) => { this.http.fetch(this.buildAccessTokenUrl(params.scope), { headers: params.headers, }) .then((response) => { if (response.error) { return reject(new Error(response.error_description)); } resolve({ accessToken: response.access_token, }); }) .catch((e: IGetAccessTokenError) => reject(e)); }); } }