|
1 | 1 | import { signal } from "@preact/signals";
|
2 | 2 | import { hash, ArgonType } from "argon2-browser";
|
3 |
| -import createClient from "openapi-fetch"; |
| 3 | +import createClient, { Middleware } from "openapi-fetch"; |
4 | 4 | import type { paths } from "./schema";
|
5 | 5 | import { logout } from "./components/Navbar";
|
6 | 6 |
|
@@ -66,7 +66,24 @@ export const PASSWORD_PATTERN = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/;
|
66 | 66 | export const BACKEND = import.meta.env.VITE_BACKEND_URL;
|
67 | 67 | export const FRONTEND_URL = import.meta.env.VITE_FRONTEND_URL;
|
68 | 68 |
|
| 69 | +let auth_already_failed = false; |
69 | 70 | export const fetchClient = createClient<paths>({baseUrl: BACKEND});
|
| 71 | +const AuthMiddleware: Middleware = { |
| 72 | + async onResponse({request, response, options}) { |
| 73 | + // Ingnore jwt refresh route since it will cause a deadlock when failing |
| 74 | + if (request.url.indexOf("/jwt_refresh") !== -1) { |
| 75 | + return undefined; |
| 76 | + } |
| 77 | + |
| 78 | + if (response.status === 401 && !auth_already_failed) { |
| 79 | + await refresh_access_token(); |
| 80 | + return await fetch(request); |
| 81 | + } else { |
| 82 | + return response; |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | +fetchClient.use(AuthMiddleware); |
70 | 87 |
|
71 | 88 | export let enableLogging = false;
|
72 | 89 |
|
@@ -108,6 +125,7 @@ export function refresh_access_token() {
|
108 | 125 | }
|
109 | 126 | loggedIn.value = AppState.LoggedIn;
|
110 | 127 | } else {
|
| 128 | + auth_already_failed = true; |
111 | 129 | localStorage.removeItem("loginSalt");
|
112 | 130 | localStorage.removeItem("secretKey");
|
113 | 131 | loggedIn.value = AppState.LoggedOut;
|
|
0 commit comments