|
| 1 | +// src/components/ProtectedRoute.tsx |
| 2 | +import { ReactElement } from 'react'; |
| 3 | +import { useValidateUserPermissions } from '@src/data/hooks'; |
| 4 | +import LoadingPage from 'components/LoadingPage'; |
| 5 | +import { CustomErrors } from 'constants'; |
| 6 | +import { CONTENT_COURSE_PERMISSIONS, CONTENT_LIBRARY_PERMISSIONS } from 'authz-module/constants'; |
| 7 | + |
| 8 | +const REQUIRED_USER_PERMISSIONS = [ |
| 9 | + CONTENT_LIBRARY_PERMISSIONS.VIEW_LIBRARY_TEAM, |
| 10 | + CONTENT_LIBRARY_PERMISSIONS.MANAGE_LIBRARY_TEAM, |
| 11 | + CONTENT_COURSE_PERMISSIONS.VIEW_COURSE_TEAM, |
| 12 | + CONTENT_COURSE_PERMISSIONS.MANAGE_COURSE_TEAM, |
| 13 | +]; |
| 14 | + |
| 15 | +type ProtectedRouteProps = { |
| 16 | + children: ReactElement; |
| 17 | + fallback?: ReactElement; |
| 18 | +}; |
| 19 | + |
| 20 | +export const ProtectedRoute = ({ |
| 21 | + children, |
| 22 | + fallback, |
| 23 | +}: ProtectedRouteProps) => { |
| 24 | + // TODO: which scope? |
| 25 | + const requiredPermissions = REQUIRED_USER_PERMISSIONS.map(action => ({ action, scope: '*' })); |
| 26 | + const { data: permissions, isLoading, isError } = useValidateUserPermissions(requiredPermissions); |
| 27 | + |
| 28 | + if (isLoading) { |
| 29 | + return <LoadingPage />; |
| 30 | + } |
| 31 | + |
| 32 | + if (isError && fallback) { |
| 33 | + return fallback; |
| 34 | + } |
| 35 | + if (isError) { |
| 36 | + throw new Error(CustomErrors.SERVER_ERROR); |
| 37 | + } |
| 38 | + |
| 39 | + const hasAccess = permissions.some(permission => permission.allowed); |
| 40 | + |
| 41 | + if (!hasAccess) { |
| 42 | + throw new Error(CustomErrors.NO_ACCESS); |
| 43 | + } |
| 44 | + |
| 45 | + return children; |
| 46 | +}; |
0 commit comments