fix(auth): prevent logout on transient API failures
This commit is contained in:
@@ -1,19 +1,20 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
import { initializeAuthenticatedApp } from '@/services/initializer.service';
|
import { initializeAuthenticatedApp } from '@/services/initializer.service';
|
||||||
import { useAppStore } from '@/store/app.store';
|
import { useAppStore } from '@/store/app.store';
|
||||||
import { useAuthStore } from '@/store/auth.store';
|
import { useAuthStore } from '@/store/auth.store';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
import { useEffect } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
export default function AppInitializer({ children }: { children: ReactNode }) {
|
export default function AppInitializer({ children }: { children: ReactNode }) {
|
||||||
const accessToken = useAuthStore((state) => state.accessToken);
|
const accessToken = useAuthStore((state) => state.accessToken);
|
||||||
const logout = useAuthStore((state) => state.logout);
|
|
||||||
const user = useAppStore((state) => state.user);
|
const user = useAppStore((state) => state.user);
|
||||||
|
const loadStatus = useAppStore((state) => state.loadStatus);
|
||||||
const setLoading = useAppStore((state) => state.setLoading);
|
const setLoading = useAppStore((state) => state.setLoading);
|
||||||
const setLoaded = useAppStore((state) => state.setLoaded);
|
const setLoaded = useAppStore((state) => state.setLoaded);
|
||||||
const setLoadError = useAppStore((state) => state.setLoadError);
|
const setLoadError = useAppStore((state) => state.setLoadError);
|
||||||
const clearApp = useAppStore((state) => state.clear);
|
const [retryAttempt, setRetryAttempt] = useState(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let isActive = true;
|
let isActive = true;
|
||||||
@@ -30,8 +31,6 @@ export default function AppInitializer({ children }: { children: ReactNode }) {
|
|||||||
await initializeAuthenticatedApp();
|
await initializeAuthenticatedApp();
|
||||||
} catch {
|
} catch {
|
||||||
if (isActive) {
|
if (isActive) {
|
||||||
logout();
|
|
||||||
clearApp();
|
|
||||||
setLoadError();
|
setLoadError();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -42,15 +41,32 @@ export default function AppInitializer({ children }: { children: ReactNode }) {
|
|||||||
return () => {
|
return () => {
|
||||||
isActive = false;
|
isActive = false;
|
||||||
};
|
};
|
||||||
}, [
|
}, [accessToken, retryAttempt, setLoaded, setLoadError, setLoading, user]);
|
||||||
accessToken,
|
|
||||||
clearApp,
|
if (accessToken && !user && loadStatus === 'error') {
|
||||||
logout,
|
return (
|
||||||
setLoaded,
|
<main className="flex min-h-screen items-center justify-center bg-background px-6">
|
||||||
setLoadError,
|
<div
|
||||||
setLoading,
|
className="flex max-w-md flex-col items-center gap-4 text-center"
|
||||||
user,
|
role="alert"
|
||||||
]);
|
>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h1 className="text-xl font-semibold">Unable to load workspace</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
We could not load your account details. Your session has been
|
||||||
|
kept, so you can safely try again.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setRetryAttempt((value) => value + 1)}
|
||||||
|
>
|
||||||
|
Try again
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return children;
|
return children;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,62 @@ const axiosClient = axios.create({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const axiosAuth = axios.create({
|
||||||
|
baseURL: BASE_URL,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let refreshPromise: Promise<string> | null = null;
|
||||||
|
|
||||||
|
const isInvalidSessionResponse = (error: unknown) => {
|
||||||
|
if (!axios.isAxiosError(error)) return false;
|
||||||
|
|
||||||
|
return error.response?.status === 401 || error.response?.status === 403;
|
||||||
|
};
|
||||||
|
|
||||||
|
const refreshAccessToken = () => {
|
||||||
|
if (!refreshPromise) {
|
||||||
|
refreshPromise = axiosAuth
|
||||||
|
.post(
|
||||||
|
'api/auth/refresh',
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
withCredentials: true,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.then((response) => {
|
||||||
|
const accessToken = response.data?.access_token;
|
||||||
|
|
||||||
|
if (!accessToken) {
|
||||||
|
throw new Error('Refresh failed: no access token');
|
||||||
|
}
|
||||||
|
|
||||||
|
useAuthStore.getState().setAccessToken(accessToken);
|
||||||
|
|
||||||
|
return accessToken;
|
||||||
|
})
|
||||||
|
.catch((error: unknown) => {
|
||||||
|
if (isInvalidSessionResponse(error)) {
|
||||||
|
useAuthStore.getState().logout();
|
||||||
|
useAppStore.getState().clear();
|
||||||
|
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.location.href = '/login';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
refreshPromise = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return refreshPromise;
|
||||||
|
};
|
||||||
|
|
||||||
axiosClient.interceptors.request.use(
|
axiosClient.interceptors.request.use(
|
||||||
(config) => {
|
(config) => {
|
||||||
const token = useAuthStore.getState().accessToken;
|
const token = useAuthStore.getState().accessToken;
|
||||||
@@ -49,31 +105,11 @@ axiosClient.interceptors.response.use(
|
|||||||
originalRequest._retry = true;
|
originalRequest._retry = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await axiosAuth.post(
|
const accessToken = await refreshAccessToken();
|
||||||
'api/auth/refresh',
|
|
||||||
{},
|
|
||||||
{
|
|
||||||
withCredentials: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const accessToken = response.data?.access_token;
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
throw new Error('Refresh failed: no access token');
|
|
||||||
}
|
|
||||||
|
|
||||||
useAuthStore.getState().setAccessToken(accessToken);
|
|
||||||
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
|
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
|
||||||
|
|
||||||
return axiosClient(originalRequest);
|
return axiosClient(originalRequest);
|
||||||
} catch (refreshError) {
|
} catch (refreshError) {
|
||||||
useAuthStore.getState().logout();
|
|
||||||
useAppStore.getState().clear();
|
|
||||||
|
|
||||||
if (typeof window !== 'undefined') {
|
|
||||||
window.location.href = '/login';
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.reject(refreshError);
|
return Promise.reject(refreshError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,11 +118,4 @@ axiosClient.interceptors.response.use(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
export const axiosAuth = axios.create({
|
|
||||||
baseURL: BASE_URL,
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
export default axiosClient;
|
export default axiosClient;
|
||||||
|
|||||||
Reference in New Issue
Block a user