feat(auth): enhance access control in PrivateRoute and display error message in LoginPage

This commit is contained in:
hamed
2026-06-15 11:41:52 +03:30
parent 8c0b3d8282
commit 3d33cf09b8
2 changed files with 29 additions and 2 deletions
+16 -2
View File
@@ -43,9 +43,12 @@ import PwaInstallBanner from './components/ui/PwaInstallBanner';
// ── Guards ──────────────────────────────────────────────────────────────────
const ALLOWED_ROLES = ['admin', 'doctor', 'clinic', 'secretary'] as const;
function PrivateRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, primaryRole, availableContexts, dbUuid, fetchMe } = useAuthStore();
const { isAuthenticated, primaryRole, availableContexts, dbUuid, fetchMe, logout } = useAuthStore();
const location = useLocation();
const [accessDenied, setAccessDenied] = React.useState(false);
useEffect(() => {
if (isAuthenticated && !primaryRole) {
@@ -53,10 +56,21 @@ function PrivateRoute({ children }: { children: React.ReactNode }) {
}
}, [isAuthenticated, primaryRole, fetchMe]);
useEffect(() => {
if (isAuthenticated && primaryRole && !ALLOWED_ROLES.includes(primaryRole as any)) {
setAccessDenied(true);
logout();
}
}, [isAuthenticated, primaryRole, logout]);
if (accessDenied) {
return <Navigate to="/admin/login?error=access_denied" replace />;
}
if (!isAuthenticated) return <Navigate to="/admin/login" replace />;
// اگر context هنوز لود نشده — صبر کن
if (isAuthenticated && !primaryRole) {
if (!primaryRole) {
return <div style={{ padding: 40, textAlign: 'center' }}>در حال بارگذاری...</div>;
}