import { ClientType, getClientOptions } from './types' import axios from 'axios' import { Tokens } from './types' import type EntityManagerClient from '@rlvt/entity-manager-openapi-client' export const standaloneAxios = axios.create() export const basePathForClient: Record = { [ClientType.DATASOURCES]: '/v2/datasources', [ClientType.WORKFLOWS]: '/v2/', [ClientType.CONTENTS]: '/v2/', [ClientType.ENTITIES]: '/v2/' } export const verifyTokenValidity = async (client: EntityManagerClient, clientId: string, tokens: Tokens) => { return client.Authentification.describeToken({ token: tokens.accessToken }) } const tokenAuth = async (client: EntityManagerClient, clientId: string, refreshToken: string): Promise => { const tokens = await client.Authentification.getToken({}, { grant_type: 'refresh_token', client_id: clientId, refresh_token: refreshToken }) return { accessToken: tokens.data.access_token, refreshToken: tokens.data.refresh_token ?? refreshToken } } const passwordAuth = async (client: EntityManagerClient, clientId: string, email: string, password: string): Promise => { const tokens = await client.Authentification.getToken({}, { grant_type: 'password', client_id: clientId, username: email, password }) return { accessToken: tokens.data.access_token, refreshToken: tokens.data.refresh_token as string } } export const clientDefaults: Partial = { gatewayEndpoint: `https://api.reelevant.com`, onAuthenticationFailure: (error: Error) => { if (axios.isAxiosError(error)) { console.error(`Failed to authenticate with Reelevant APIs`, { message: error.message, data: error.response?.data, request: error.config }) } else { console.error(`Failed to authenticate with Reelevant APIs`, error) } }, onAuthenticationRequired: async ({ currentTokens, options, client }) => { switch (options.authenticationType.type) { case 'password': { if (currentTokens.refreshToken === undefined) { return passwordAuth(client, options.clientId, options.authenticationType.email, options.authenticationType.password) } return tokenAuth(client, options.clientId, currentTokens.refreshToken) } case 'refresh_token': { if (currentTokens.refreshToken === undefined) { throw new Error(`Tried to renew token but no refresh token is defined`) } return tokenAuth(client, options.clientId, currentTokens.refreshToken) } default: { throw new Error(`Unknown authentication type: ${options.authenticationType}`) } } }, onAuthenticationSuccess: (profile) => { console.log(`Logged within Reelevant with account ${profile.email}`) }, // @ts-expect-error authenticationType: { type: 'refresh_token' } }