mirror of
https://github.com/SamyRai/turash.git
synced 2025-12-26 23:01:33 +00:00
76 lines
2.1 KiB
TypeScript
76 lines
2.1 KiB
TypeScript
import React from 'react';
|
|
import { Navigate, useLocation } from 'react-router-dom';
|
|
import { useAuth } from '@/contexts/AuthContext';
|
|
import { usePermissions } from '@/hooks/usePermissions';
|
|
import { Permission } from '@/types/permissions';
|
|
import { Alert } from '@/components/ui';
|
|
|
|
export interface AdminRouteProps {
|
|
children: React.ReactNode;
|
|
permission?: Permission | Permission[];
|
|
requireAll?: boolean;
|
|
fallbackPath?: string;
|
|
}
|
|
|
|
/**
|
|
* Route protection specifically for admin routes
|
|
* Automatically checks for admin role and optional permissions
|
|
*/
|
|
export const AdminRoute = ({
|
|
children,
|
|
permission,
|
|
requireAll = false,
|
|
fallbackPath = '/',
|
|
}: AdminRouteProps) => {
|
|
const { isAuthenticated, isLoading } = useAuth();
|
|
const { isAdmin, checkAnyPermission, checkAllPermissions } = usePermissions();
|
|
const location = useLocation();
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="flex h-screen w-full items-center justify-center bg-background">
|
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (!isAuthenticated) {
|
|
return <Navigate to="/login" state={{ from: location }} replace />;
|
|
}
|
|
|
|
if (!isAdmin) {
|
|
return (
|
|
<div className="flex h-screen w-full items-center justify-center bg-background p-4">
|
|
<Alert
|
|
variant="error"
|
|
title="Access Denied"
|
|
description="You must be an administrator to access this page."
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// Check additional permissions if specified
|
|
if (permission) {
|
|
const permissions = Array.isArray(permission) ? permission : [permission];
|
|
const hasAccess = requireAll
|
|
? checkAllPermissions(permissions)
|
|
: checkAnyPermission(permissions);
|
|
|
|
if (!hasAccess) {
|
|
return (
|
|
<div className="flex h-screen w-full items-center justify-center bg-background p-4">
|
|
<Alert
|
|
variant="error"
|
|
title="Access Denied"
|
|
description="You don't have the required permissions to access this page."
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
}
|
|
|
|
return <>{children}</>;
|
|
};
|
|
|