make OpenAPI and the server url public accessible through the UmbAuthContext

This commit is contained in:
Jacob Overgaard
2024-01-31 10:45:50 +01:00
parent 57c423f63a
commit 8798d4cd86

View File

@@ -3,19 +3,22 @@ import { UMB_AUTH_CONTEXT } from './auth.context.token.js';
import type { UmbControllerHostElement } from '@umbraco-cms/backoffice/controller-api';
import { UmbBaseController } from '@umbraco-cms/backoffice/class-api';
import { UmbBooleanState } from '@umbraco-cms/backoffice/observable-api';
import { OpenAPI } from '@umbraco-cms/backoffice/backend-api';
export class UmbAuthContext extends UmbBaseController {
#isAuthorized = new UmbBooleanState<boolean>(false);
readonly isAuthorized = this.#isAuthorized.asObservable();
#isBypassed = false;
#backofficePath: string;
#serverUrl;
#backofficePath;
#authFlow;
#openApi = OpenAPI;
constructor(host: UmbControllerHostElement, serverUrl: string, backofficePath: string, isBypassed: boolean) {
super(host);
this.#isBypassed = isBypassed;
this.#serverUrl = serverUrl;
this.#backofficePath = backofficePath;
this.#authFlow = new UmbAuthFlow(serverUrl, this.#getRedirectUrl());
@@ -65,7 +68,7 @@ export class UmbAuthContext extends UmbBaseController {
*
* NB! The user may experience being redirected to the login screen if the token is expired.
*
* @example
* @example <caption>Using the latest token</caption>
* ```js
* const token = await authContext.getLatestToken();
* const result = await fetch('https://my-api.com', { headers: { Authorization: `Bearer ${token}` } });
@@ -94,6 +97,42 @@ export class UmbAuthContext extends UmbBaseController {
return this.#authFlow.signOut();
}
/**
* Get the server url to the Management API.
* @memberof UmbAuthContext
* @example <caption>Using the server url</caption>
* ```js
* const serverUrl = authContext.getServerUrl();
* OpenAPI.BASE = serverUrl;
* ```
* @example <caption></caption>
* ```js
* const serverUrl = authContext.getServerUrl();
* const token = await authContext.getLatestToken();
* const result = await fetch(`${serverUrl}/umbraco/management/api/v1/my-resource`, { headers: { Authorization: `Bearer ${token}` } });
* ```
* @returns The server url to the Management API
*/
getServerUrl() {
return this.#serverUrl;
}
/**
* Get the default OpenAPI configuration, which is set up to communicate with the Management API.
* @remark This is useful if you want to communicate with your own resources generated by the [openapi-typescript-codegen](https://github.com/ferdikoomen/openapi-typescript-codegen) library.
* @memberof UmbAuthContext
*
* @example <caption>Using the default OpenAPI configuration</caption>
* ```js
* const defaultOpenApi = authContext.getOpenApiConfiguration();
* OpenAPI = { ...OpenAPI, ...openApi };
* ```
* @returns The default OpenAPI configuration
*/
getOpenApiConfiguration() {
return this.#openApi;
}
#getRedirectUrl() {
return `${window.location.origin}${this.#backofficePath}`;
}