move isAuthorized logic into the auth controller

This commit is contained in:
Jacob Overgaard
2024-04-04 14:51:18 +02:00
parent 762368c3a6
commit 951d8831cd
2 changed files with 46 additions and 22 deletions

View File

@@ -1,9 +1,50 @@
import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth';
import { UMB_AUTH_CONTEXT, UMB_STORAGE_REDIRECT_URL } from '@umbraco-cms/backoffice/auth';
import { UmbControllerBase } from '@umbraco-cms/backoffice/class-api';
import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api';
export class UmbAppAuthController extends UmbControllerBase {
async makeAuthorizationRequest() {
const authContext = await this.getContext(UMB_AUTH_CONTEXT);
return authContext.makeAuthorizationRequest();
#authContext?: typeof UMB_AUTH_CONTEXT.TYPE;
constructor(host: UmbControllerHost) {
super(host);
this.consumeContext(UMB_AUTH_CONTEXT, (context) => {
this.#authContext = context;
});
}
/**
* Checks if the user is authorized.
* If not, the authorization flow is started.
*/
async isAuthorized(): Promise<boolean> {
if (!this.#authContext) {
throw new Error('[Fatal] Auth context is not available');
}
const isAuthorized = this.#authContext.getIsAuthorized();
if (isAuthorized) {
return true;
}
// Save location.href so we can redirect to it after login
window.sessionStorage.setItem(UMB_STORAGE_REDIRECT_URL, location.href);
// Make a request to the auth server to start the auth flow
return this.makeAuthorizationRequest();
}
async makeAuthorizationRequest(): Promise<boolean> {
if (!this.#authContext) {
throw new Error('[Fatal] Auth context is not available');
}
this.#authContext.makeAuthorizationRequest();
// Reinitialize the auth flow (load the state from local storage)
this.#authContext.setInitialState();
return true;
}
}

View File

@@ -186,24 +186,7 @@ export class UmbAppElement extends UmbLitElement {
}
#isAuthorizedGuard(): Guard {
return async () => {
if (!this.#authContext) {
throw new Error('[Fatal] AuthContext requested before it was initialized');
}
if (this.#authContext.getIsAuthorized()) {
return true;
}
// Save location.href so we can redirect to it after login
window.sessionStorage.setItem(UMB_STORAGE_REDIRECT_URL, location.href);
// Make a request to the auth server to start the auth flow
await this.#authController.makeAuthorizationRequest();
// Return false to prevent the route from being rendered
return false;
};
return () => this.#authController.isAuthorized();
}
#errorPage(errorMsg: string, error?: unknown) {