From 035771de8181f130513a9ce1663b45a8a5ddfa2e Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Sat, 27 Mar 2021 23:18:51 +0100 Subject: [PATCH] web: add middleware that shows message for failed API requests Signed-off-by: Jens Langhammer --- web/src/api/Config.ts | 6 ++++-- web/src/elements/messages/Middleware.ts | 18 ++++++++++++++++++ web/src/elements/notifications/APIDrawer.ts | 4 ++-- 3 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 web/src/elements/messages/Middleware.ts diff --git a/web/src/api/Config.ts b/web/src/api/Config.ts index 10a96aa27..71dba42a0 100644 --- a/web/src/api/Config.ts +++ b/web/src/api/Config.ts @@ -4,7 +4,8 @@ import { VERSION } from "../constants"; import { SentryIgnoredError } from "../common/errors"; import { Config, Configuration, RootApi } from "authentik-api"; import { getCookie } from "../utils"; -import { MIDDLEWARE } from "../elements/notifications/APIDrawer"; +import { API_DRAWER_MIDDLEWARE } from "../elements/notifications/APIDrawer"; +import { MessageMiddleware } from "../elements/messages/Middleware"; export const DEFAULT_CONFIG = new Configuration({ basePath: "/api/v2beta", @@ -13,7 +14,8 @@ export const DEFAULT_CONFIG = new Configuration({ "X-Authentik-Prevent-Basic": "true" }, middleware: [ - MIDDLEWARE + API_DRAWER_MIDDLEWARE, + new MessageMiddleware(), ], }); diff --git a/web/src/elements/messages/Middleware.ts b/web/src/elements/messages/Middleware.ts new file mode 100644 index 000000000..b01861950 --- /dev/null +++ b/web/src/elements/messages/Middleware.ts @@ -0,0 +1,18 @@ +import { Middleware, ResponseContext } from "authentik-api"; +import { gettext } from "django"; +import { MessageLevel } from "./Message"; +import { showMessage } from "./MessageContainer"; + +export class MessageMiddleware implements Middleware { + + post(context: ResponseContext): Promise { + if (!context.response.ok) { + showMessage({ + level: MessageLevel.error, + message: gettext("API request failed"), + description: `${context.init.method} ${context.url}: ${context.response.status}` + }); + } + return Promise.resolve(context.response); + } +} diff --git a/web/src/elements/notifications/APIDrawer.ts b/web/src/elements/notifications/APIDrawer.ts index 7134b6dee..74d2db018 100644 --- a/web/src/elements/notifications/APIDrawer.ts +++ b/web/src/elements/notifications/APIDrawer.ts @@ -39,7 +39,7 @@ export class APIMiddleware implements Middleware { } export const MAX_REQUESTS = 50; -export const MIDDLEWARE = new APIMiddleware(); +export const API_DRAWER_MIDDLEWARE = new APIMiddleware(); @customElement("ak-api-drawer") export class APIDrawer extends LitElement { @@ -76,7 +76,7 @@ export class APIDrawer extends LitElement {
    - ${MIDDLEWARE.requests.map(n => this.renderItem(n))} + ${API_DRAWER_MIDDLEWARE.requests.map(n => this.renderItem(n))}