update usermanagement to legacy mode

This commit is contained in:
mengstabketemaw
2026-06-18 11:25:26 +03:00
parent 3a528c9515
commit 2feaaf1ee4
13 changed files with 158 additions and 57 deletions

View File

@@ -0,0 +1,24 @@
import { Navigate, Outlet, useLocation } from 'react-router-dom';
import type { ReactNode } from 'react';
import { authStorage } from '../utils/auth-storage';
interface ProtectedRouteProps {
children?: ReactNode;
loginPath?: string;
}
function getTokenFromCookie(): string | undefined {
const match = document.cookie.match(/(?:^|;\s*)auth-token=([^;]*)/);
return match ? decodeURIComponent(match[1]) : undefined;
}
export function ProtectedRoute({ children, loginPath = '/login' }: ProtectedRouteProps) {
const location = useLocation();
const token = authStorage.getToken() ?? getTokenFromCookie();
if (!token) {
return <Navigate to={loginPath} state={{ from: location }} replace />;
}
return children ? <>{children}</> : <Outlet />;
}

View File

@@ -25,5 +25,7 @@ export const authStorage = {
[key('auth-token'), key('refresh-token'), key('auth-user')].forEach((k) =>
localStorage.removeItem(k),
);
document.cookie =
'auth-token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC; SameSite=Lax';
},
};

View File

@@ -0,0 +1,31 @@
import { authStorage } from './auth-storage';
const BASE_API_URL =
(import.meta as { env?: Record<string, string> }).env?.['VITE_BASE_API_URL'] ??
'http://localhost:3001/api';
interface RefreshResponse {
token: string;
refreshToken: string;
}
export async function refreshAccessToken(): Promise<string> {
const refreshToken = authStorage.getRefreshToken();
if (!refreshToken) throw new Error('No refresh token available');
const response = await fetch(`${BASE_API_URL}/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken }),
});
if (!response.ok) {
authStorage.clear();
throw new Error('Token refresh failed');
}
const data: RefreshResponse = await response.json();
authStorage.setToken(data.token);
if (data.refreshToken) authStorage.setRefreshToken(data.refreshToken);
return data.token;
}