| 316 | } |
| 317 | |
| 318 | export class CloudApiClient |
| 319 | implements IApiClientBase, ICloudApiClient, IFronteggApiClient |
| 320 | { |
| 321 | #appConfig: Readonly<CloudAppConfig>; |
| 322 | cloudGlobalApiBasePath: string; |
| 323 | fronteggApiBasePath: string; |
| 324 | type = "cloud" as const; |
| 325 | isImpersonating = false as const; |
| 326 | mzHttpUrlScheme: HttpScheme; |
| 327 | mzWebsocketUrlScheme: WebsocketScheme; |
| 328 | |
| 329 | constructor({ appConfig }: { appConfig: Readonly<CloudAppConfig> }) { |
| 330 | this.#appConfig = appConfig; |
| 331 | this.cloudGlobalApiBasePath = this.#appConfig.cloudGlobalApiUrl; |
| 332 | this.fronteggApiBasePath = this.#appConfig.fronteggUrl; |
| 333 | this.mzHttpUrlScheme = this.#appConfig.environmentdScheme; |
| 334 | this.mzWebsocketUrlScheme = this.#appConfig.environmentdWebsocketScheme; |
| 335 | } |
| 336 | |
| 337 | #getAccessToken() { |
| 338 | // Get the access token from Frontegg's context holder |
| 339 | const accessToken = ContextHolder.for("default").getAccessToken(); |
| 340 | |
| 341 | // The token will most likely always exist since this function |
| 342 | // will be called when logged in. If not, we should alert Sentry. |
| 343 | if (!accessToken) { |
| 344 | Sentry.addBreadcrumb({ |
| 345 | level: "error", |
| 346 | category: "auth", |
| 347 | message: "Failed to refresh auth token", |
| 348 | }); |
| 349 | } |
| 350 | return accessToken; |
| 351 | } |
| 352 | |
| 353 | #authMiddleware: Middleware = (next) => { |
| 354 | return async (...fetchArgs) => { |
| 355 | const [input, options = {}] = fetchArgs; |
| 356 | const accessToken = this.#getAccessToken(); |
| 357 | |
| 358 | const headers = copyHeaders(fetchArgs); |
| 359 | if (accessToken) { |
| 360 | headers.set("Authorization", `Bearer ${accessToken}`); |
| 361 | if (this.#appConfig.sentryConfig?.release) { |
| 362 | Object.entries( |
| 363 | buildConsoleVersionHeaders(this.#appConfig.sentryConfig?.release), |
| 364 | ).forEach(([key, value]) => { |
| 365 | headers.set(key, value); |
| 366 | }); |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | const request = new Request(input, { ...options, headers }); |
| 371 | return next(request); |
| 372 | }; |
| 373 | }; |
| 374 | |
| 375 | mzApiFetch = withMiddleware(globalFetch, this.#authMiddleware); |
nothing calls this directly
no test coverage detected