/* tslint:disable */ /* eslint-disable */ /** * Emil PublicAPI * The Emil Public API description * * The version of the OpenAPI document: 1.0 * Contact: kontakt@emil.de * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Configuration } from "./configuration"; // Some imports not used depending on template conditions // @ts-ignore import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; export const BASE_PATH = "https://apiv2.emil.de".replace(/\/+$/, ""); const CONFIG_DIRECTORY = '.emil'; const CONFIG_FILENAME = 'credentials'; const KEY_USERNAME = 'emil_username'; const KEY_PASSWORD = 'emil_password'; const filePath = os.homedir() + path.sep + CONFIG_DIRECTORY + path.sep + CONFIG_FILENAME; /** * * @export */ export const COLLECTION_FORMATS = { csv: ",", ssv: " ", tsv: "\t", pipes: "|", }; export interface LoginClass { accessToken: string; permissions: string; } export enum Environment { Production = 'https://apiv2.emil.de', Test = 'https://apiv2-test.emil.de', Staging = 'https://apiv2-staging.emil.de', Development = 'https://apiv2-dev.emil.de', ProductionZurich = 'https://eu-central-2.apiv2.emil.de', } let _retry_count = 0 let _retry = null export function resetRetry() { _retry_count = 0 } /** * * @export * @interface RequestArgs */ export interface RequestArgs { url: string; options: AxiosRequestConfig; } const NETWORK_ERROR_MESSAGE = "Network Error"; /** * * @export * @class BaseAPI */ export class BaseAPI { protected configuration: Configuration; private username?: string; private password?: string; constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; this.basePath = configuration.basePath || this.basePath; } else { this.configuration = new Configuration({ basePath: this.basePath, }); } this.attachInterceptor(axios); } async initialize(env: Environment = Environment.Production) { this.configuration.basePath = env; await this.loadCredentials(); if (this.username) { await this.authorize(this.username, this.password); this.password = null; // to avoid keeping password loaded in memory. } } private async loadCredentials() { try { await this.readConfigFile(); } catch (error) { console.warn(`No credentials file found. Check that ${filePath} exists.`); } this.readEnvVariables(); if (!this.username) { console.info(`No credentials found in credentials file or environment variables. Either provide some or use authorize() function.`); } } private async readConfigFile() { const file = await fs.promises.readFile(filePath, 'utf-8'); const lines = file.split(os.EOL) .filter(Boolean); lines.forEach((line: string) => { if (line.startsWith(KEY_USERNAME)) { this.username = line.length > KEY_USERNAME.length + 1 ? line.substring(KEY_USERNAME.length + 1) : ''; } else if (line.startsWith(KEY_PASSWORD)) { this.password = line.length > KEY_PASSWORD.length + 1 ? line.substring(KEY_PASSWORD.length + 1) : ''; } }); } private readEnvVariables(): boolean { if (process.env.EMIL_USERNAME) { this.username = process.env.EMIL_USERNAME; this.password = process.env.EMIL_PASSWORD || ''; return true; } return false; } selectEnvironment(env: Environment) { this.configuration.basePath = env; } async authorize(username: string, password: string): Promise { const options: AxiosRequestConfig = { method: 'POST', url: `${this.configuration.basePath}/authservice/v1/login`, headers: { 'Content-Type': 'application/json' }, data: { username, password, }, withCredentials: true, }; const response = await globalAxios.request(options); const { data: { accessToken } } = response; this.configuration.username = username; this.configuration.accessToken = `Bearer ${accessToken}`; const refreshToken = this.extractRefreshToken(response) this.configuration.refreshToken = refreshToken; } async refreshTokenInternal(): Promise { const { username, refreshToken } = this.configuration; if (!username || !refreshToken) { return ''; } const options: AxiosRequestConfig = { method: 'POST', url: `${this.configuration.basePath}/authservice/v1/refresh-token`, headers: { 'Content-Type': 'application/json', Cookie: refreshToken, }, data: { username: username }, withCredentials: true, }; const { data: { accessToken } } = await globalAxios.request(options); return accessToken; } private extractRefreshToken(response: AxiosResponse): string { if (response.headers && response.headers['set-cookie'] && response.headers['set-cookie'].length > 0) { return `${response.headers['set-cookie'][0].split(';')[0]};`; } return ''; } getConfiguration(): Configuration { return this.configuration; } private attachInterceptor(axios: AxiosInstance) { axios.interceptors.response.use( (res) => { return res; }, async (err) => { let originalConfig = err.config; if (err.response) { // Access Token was expired if (err.response.status === 401 && !originalConfig._retry) { originalConfig._retry = true; try { const tokenString = await this.refreshTokenInternal(); const accessToken = `Bearer ${tokenString}`; originalConfig.headers['Authorization'] = `Bearer ${accessToken}` this.configuration.accessToken = accessToken; return axios.request(originalConfig); } catch (_error) { if (_error.response && _error.response.data) { return Promise.reject(_error.response.data); } return Promise.reject(_error); } } if (err.response.status === 403 && err.response.data) { return Promise.reject(err.response.data); } } else if(err.message === NETWORK_ERROR_MESSAGE && err.isAxiosError && originalConfig.headers.hasOwnProperty('Authorization') && _retry_count < 4 ){ _retry_count++; try { const tokenString = await this.refreshTokenInternal(); const accessToken = `Bearer ${tokenString}`; _retry = true; originalConfig.headers['Authorization'] = accessToken; this.configuration.accessToken = accessToken; return axios.request({ ...originalConfig, }); } catch (_error) { if (_error.response && _error.response.data) { return Promise.reject(_error.response.data); } return Promise.reject(_error); } } return Promise.reject(err); } ); } }; /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } }