86 lines
2.5 KiB
TypeScript
86 lines
2.5 KiB
TypeScript
import { useState, useEffect } from 'react';
|
|
import { Navigate, Outlet } from 'react-router-dom';
|
|
import api from '../services/api';
|
|
import { useAdminAuthStore } from '../store/adminAuthStore';
|
|
import type { ApiResponse, AuthResponseData, AdminUser } from '../types/admin';
|
|
|
|
export default function ProtectedRoute() {
|
|
const { isAuthenticated, accessToken, setAuth, clearAuth } = useAdminAuthStore();
|
|
const [isValidating, setIsValidating] = useState(true);
|
|
|
|
useEffect(() => {
|
|
let isMounted = true;
|
|
|
|
const validateSession = async () => {
|
|
if (isAuthenticated && accessToken) {
|
|
setIsValidating(false);
|
|
return;
|
|
}
|
|
|
|
if (accessToken) {
|
|
try {
|
|
const response = await api.post<ApiResponse<AuthResponseData>>('/auth/refresh');
|
|
if (response.data?.success && response.data.data?.accessToken) {
|
|
if (isMounted) {
|
|
setAuth(response.data.data.accessToken, response.data.data.user);
|
|
setIsValidating(false);
|
|
}
|
|
return;
|
|
}
|
|
} catch {
|
|
// Token invalid or refresh failed
|
|
}
|
|
}
|
|
|
|
if (accessToken) {
|
|
try {
|
|
const profileRes = await api.get<ApiResponse<AdminUser>>('/users/profile');
|
|
if (profileRes.data?.data && isMounted) {
|
|
setAuth(accessToken, profileRes.data.data);
|
|
setIsValidating(false);
|
|
return;
|
|
}
|
|
} catch {
|
|
// Token invalid
|
|
}
|
|
}
|
|
|
|
if (isMounted) {
|
|
clearAuth();
|
|
setIsValidating(false);
|
|
}
|
|
};
|
|
|
|
validateSession();
|
|
|
|
return () => {
|
|
isMounted = false;
|
|
};
|
|
}, [isAuthenticated, accessToken, setAuth, clearAuth]);
|
|
|
|
if (isValidating) {
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center bg-gray-50 font-vazir" dir="rtl">
|
|
<div className="flex flex-col items-center gap-3">
|
|
<div className="w-10 h-10 border-4 border-purple-600 border-t-transparent rounded-full animate-spin"></div>
|
|
<span className="text-sm font-bold text-gray-500">در حال اعتبارسنجی نشست کاری ادمین...</span>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
const user = useAdminAuthStore.getState().adminUser;
|
|
const isUserAuthenticated = useAdminAuthStore.getState().isAuthenticated;
|
|
|
|
if (!isUserAuthenticated || !user) {
|
|
return <Navigate to="/login" replace />;
|
|
}
|
|
|
|
const role = (user.role || '').toUpperCase();
|
|
if (role !== 'ADMIN' && role !== 'SUPER_ADMIN') {
|
|
return <Navigate to="/login" replace />;
|
|
}
|
|
|
|
return <Outlet />;
|
|
}
|