import { TokenResult } from '@axinom/mosaic-id-utils'; import { MosaicError, MosaicErrors } from '@axinom/mosaic-service-common'; import { getGqlClient } from '../common/gql-client'; import { IdLinkBeErrors } from '../common/id-link-be-errors'; import { GenerateLongLivedTokenDocument, GenerateLongLivedTokenMutation, GenerateLongLivedTokenMutationVariables, } from '../generated/graphql.types'; import { getWellKnownEndpoints } from '../well-known-endpoints'; /** * This function generates a long lived access token for a user token. It can be used to invoke long running processes. * @param authEndpoint URL for id-service authEndpoint. * @param serviceAccountToken A valid service account token with permission GENERATE_LONG_LIVED_TOKEN granted. * @param userAccessToken User access token to extend the validity period for. * @param validityDurationInSeconds Token expiration time in seconds. If not given, it will be defaulted to 2592000 (30 days). * @returns {TokenResult} Long lived access token. */ export const generateLongLivedToken = async ( authEndpoint: string, serviceAccountToken: string, userAccessToken: string, validityDurationInSeconds?: number, ): Promise => { const client = getGqlClient( (await getWellKnownEndpoints(authEndpoint)).authGraphQlEndpoint, serviceAccountToken, ); const result = await client.mutate< GenerateLongLivedTokenMutation, GenerateLongLivedTokenMutationVariables >({ mutation: GenerateLongLivedTokenDocument, variables: { input: { userToken: userAccessToken, validityDurationInSeconds, }, }, errorPolicy: 'all', fetchPolicy: 'no-cache', }); if (!result.errors) { if (!result.data) { throw new MosaicError({ code: MosaicErrors.UnexpectedNullUndefined.code, message: `Unexpected null or undefined value received for 'generateLongLivedToken' result.`, }); } const tokenResponse = result.data.generateLongLivedToken; const longLivedToken = { accessToken: tokenResponse.accessToken, tokenType: tokenResponse.tokenType, expiresInSeconds: tokenResponse.expiresInSeconds, }; return longLivedToken; } else { const aggregatedErrorMessage = result.errors.reduce( (aggregatedError, gqlError) => { return (aggregatedError += gqlError.message); }, '', ); throw new MosaicError({ ...IdLinkBeErrors.LongLivedTokenGenerationError, details: { originalError: aggregatedErrorMessage, }, }); } };