import { IClusterClientProvider } from "../../typings/IClusterClientProvider"; import { AuthService as Auth } from "../../portal/Auth"; import ip = require("ip"); export type PortalAutoAuthProviderDeps = { clusterClientProvider: IClusterClientProvider; apiKey: string; portalLogin: string; portalPassword: string; }; const SID_DURATION_TIMESTAMP = 86400000; // 1 * 24 * 60 * 60 * 1000 export class PortalAutoAuthProvider { private _apiKey: string; private _sid?: string; private _login: string; private _password: string; private _lastSidUpdate: number; private _auth: Auth; constructor({ apiKey, clusterClientProvider, portalLogin, portalPassword }: PortalAutoAuthProviderDeps) { if (!apiKey || !clusterClientProvider) { throw new TypeError("portalApiKey & clusterClientProvider is required"); } if (!portalLogin || !portalPassword) { throw new TypeError("portalLogin & portalPassword is required"); } this._apiKey = apiKey; this._login = portalLogin; this._password = portalPassword; this._lastSidUpdate = 0; this._auth = new Auth({ clusterClientProvider, apiKey }); } async updateSid(useForce?: boolean) { let promise = null; const timestamp = new Date().getTime(); if (useForce || timestamp - SID_DURATION_TIMESTAMP > this._lastSidUpdate) { const realIp = ip.address(); promise = this._auth .authenticateByPassword(this._login, this._password, realIp) .then(response => { this._sid = response.data.Sid; this._lastSidUpdate = timestamp; }); } else { promise = Promise.resolve(); } return promise; } async getSid() { await this.updateSid(); return this._sid; } async getAuthParams(){ await this.updateSid(); return { "api-key": this._apiKey, "auth.sid": this._sid }; } async getAuthHeaders() : Promise<{ Authorization: string; "X-Kontur-Apikey": string; }>{ await this.updateSid(); return { Authorization: `auth.sid ${this._sid}`, "X-Kontur-Apikey": this._apiKey }; } }