Skip to content

A self-hosted media server and file management system

fix: retry csrf on 419 errors to prevent random logouts

aminnausin357818a296a7
diff --git a/resources/js/service/api.ts b/resources/js/service/api.ts
index aa8add35..8a3b2cd6 100644
--- a/resources/js/service/api.ts
+++ b/resources/js/service/api.ts
@@ -1,11 +1,40 @@
+import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
+
import { useAuthStore } from '@/stores/AuthStore';
+import { AxiosError } from 'axios';
+import { getCSRF } from '@/service/authAPI';
import { toast } from '@aminnausin/cedar-ui';
-import axios, { AxiosError } from 'axios';
import nProgress from 'nprogress';
+import axios from 'axios';
+// For progress bar
let progressTimeout: NodeJS.Timeout;
+// For csrf handling
+let csrfRefreshPromise: Promise<AxiosResponse> | null = null;
+let isRefreshing = false;
+let queue: Array<(tokenReady: boolean) => void> = []; // A queue of promises that are conditionally called after attempt at refreshing csrf
+
+function refreshCsrf() {
+ if (!csrfRefreshPromise) {
+ csrfRefreshPromise = getCSRF().finally(() => {
+ csrfRefreshPromise = null;
+ });
+ }
+
+ return csrfRefreshPromise;
+}
+
+function queueRequest(cb: (ready: boolean) => void) {
+ queue.push(cb);
+}
+
+function flushQueue(success: boolean) {
+ queue.forEach((cb) => cb(success));
+ queue = [];
+}
+
const handleResponse = (response: any) => {
clearTimeout(progressTimeout);
nProgress.done(true);
@@ -16,37 +45,59 @@ const handleError = async (error: AxiosError<{ message?: string }>) => {
clearTimeout(progressTimeout);
nProgress.done(true);
- const message = error.response?.data?.message ?? error.message;
-
const auth = useAuthStore();
const status = error.response?.status ?? 0;
+ const config = error.config as InternalAxiosRequestConfig & { _retried?: boolean };
+ const message = error.response?.data?.message ?? error.message;
+ const showToast = !config?.headers?.['X-Skip-Toast'];
// if the server throws an error (404, 500 etc.)
- const knownError = [403, 422, 500, 404, 502, 401, 419].includes(status);
const isSessionExpired = status === 419;
const isAuthError = status === 401;
- const showToast = !error.config?.headers?.['X-Skip-Toast'];
- // Handle expired auth token and session timeout (CSRF token expired)
- if ((isAuthError || isSessionExpired) && auth.userData) {
- const router = (await import('@/router')).router;
+ // If 419 (CSRF token expired) and not already marked, manually refresh csrf and retry the request after marking it
+ if (isSessionExpired && config && !config._retried) {
+ if (isRefreshing) {
+ return new Promise((resolve, reject) => {
+ queueRequest((ready) => {
+ if (!ready) return reject(new AxiosError('CSRF refresh failed'));
+ config._retried = true;
+ resolve(API.request(config));
+ });
+ });
+ }
- const currentRoute = router.currentRoute.value;
+ config._retried = true;
+ isRefreshing = true;
+
+ try {
+ await refreshCsrf();
+ flushQueue(true);
+ return API.request(config);
+ } catch (e) {
+ flushQueue(false);
+ throw e; // Session Expired and Irrecoverable
+ } finally {
+ isRefreshing = false;
+ }
+ }
+ // Handle expired auth
+ if (isAuthError && auth.userData) {
auth.clearAuthState(true, status);
- if (currentRoute.meta?.protected) {
+ const router = (await import('@/router')).router;
+ if (router.currentRoute.value.meta?.protected) {
router.replace({ path: '/' });
}
- error.message = `Session Expired: ${message}`;
- } else if (showToast && !isAuthError) {
- toast.error('Error', { description: message });
+ error.message = `Login Expired: ${message}`;
+ throw error;
}
- if (!knownError) {
- console.error(error);
- return error.response;
+ // Show error for non 401/419 errors
+ if (showToast && !isAuthError && !isSessionExpired) {
+ toast.error('Error', { description: message });
}
throw error;