let the auth context know if a 401 is encountered, which most likely means the user is timed out

This commit is contained in:
Jacob Overgaard
2024-04-05 14:23:42 +02:00
parent 0755d4d410
commit e838c0ea1b
2 changed files with 31 additions and 14 deletions

View File

@@ -95,6 +95,16 @@ export class UmbAuthContext extends UmbContextBase<UmbAuthContext> {
return this.#authFlow.clearTokenStorage();
}
/**
* Handles the case where the user has timed out, i.e. the token has expired.
* This will clear the token storage and set the user as unauthorized.
* @memberof UmbAuthContext
*/
timeOut() {
this.clearTokenStorage();
this.#isAuthorized.setValue(false);
}
/**
* Signs the user out by removing any tokens from the browser.
* @memberof UmbAuthContext

View File

@@ -1,4 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { UMB_AUTH_CONTEXT } from '../auth/index.js';
import { isApiError, isCancelError, isCancelablePromise } from './apiTypeValidators.function.js';
import { UMB_NOTIFICATION_CONTEXT, type UmbNotificationOptions } from '@umbraco-cms/backoffice/notification';
import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api';
@@ -11,6 +12,8 @@ export class UmbResourceController extends UmbControllerBase {
#notificationContext?: typeof UMB_NOTIFICATION_CONTEXT.TYPE;
#authContext?: typeof UMB_AUTH_CONTEXT.TYPE;
constructor(host: UmbControllerHost, promise: Promise<any>, alias?: string) {
super(host, alias);
@@ -19,6 +22,10 @@ export class UmbResourceController extends UmbControllerBase {
new UmbContextConsumerController(host, UMB_NOTIFICATION_CONTEXT, (_instance) => {
this.#notificationContext = _instance;
});
new UmbContextConsumerController(host, UMB_AUTH_CONTEXT, (_instance) => {
this.#authContext = _instance;
});
}
hostConnected(): void {
@@ -78,21 +85,21 @@ export class UmbResourceController extends UmbControllerBase {
// Go through the error status codes and act accordingly
switch (error.status ?? 0) {
case 401:
// Unauthorized
console.log('Unauthorized');
// TODO: Do not remove the token here but instead let whatever is listening to the event decide what to do
localStorage.removeItem('umb:userAuthTokenResponse');
// TODO: Show a modal dialog to login either by bubbling an event to UmbAppElement or by showing a modal directly
this.#notificationContext?.peek('warning', {
data: {
headline: 'Session Expired',
message: 'Your session has expired. Please refresh the page.',
},
});
case 401: {
// See if we can get the UmbAuthContext and let it know the user is timed out
if (this.#authContext) {
this.#authContext.timeOut();
} else {
// If we can't get the auth context, show a notification
this.#notificationContext?.peek('warning', {
data: {
headline: 'Session Expired',
message: 'Your session has expired. Please refresh the page.',
},
});
}
break;
}
case 500:
// Server Error