This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { type FC, type ReactNode } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useGetAdminMe } from '@/pages/admin/hooks/useAdminData'
|
||||
import {
|
||||
getDefaultAdminPath,
|
||||
hasPermission,
|
||||
} from '@/config/permissions'
|
||||
|
||||
type Props = {
|
||||
permission: string | string[]
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocks route access when the current admin lacks the required permission(s).
|
||||
* Pass an array to allow access if the user has any of them.
|
||||
*/
|
||||
const PermissionGuard: FC<Props> = ({ permission, children }) => {
|
||||
const { data: adminMe, isLoading } = useGetAdminMe()
|
||||
|
||||
if (isLoading) {
|
||||
return null
|
||||
}
|
||||
|
||||
const permissions =
|
||||
adminMe?.data?.role?.permissions?.map((p) => p.name) ?? []
|
||||
|
||||
if (!hasPermission(permissions, permission)) {
|
||||
return <Navigate to={getDefaultAdminPath(permissions)} replace />
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default PermissionGuard
|
||||
Reference in New Issue
Block a user