feat(auth): enhance access control in PrivateRoute and display error message in LoginPage
This commit is contained in:
+16
-2
@@ -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>;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user