|
| 1 | +import React, { useEffect, useState } from 'react'; |
| 2 | +import { Navigate } from 'react-router-dom'; |
| 3 | +import { useAuth } from '../../auth/AuthProvider'; |
| 4 | +import { getUIRouteAuth } from '../../services/config'; |
| 5 | +import CircularProgress from '@material-ui/core/CircularProgress'; |
| 6 | + |
| 7 | +interface RouteGuardProps { |
| 8 | + component: React.ComponentType<any>; |
| 9 | + fullRoutePath: string; |
| 10 | +} |
| 11 | + |
| 12 | +interface UIRouteAuth { |
| 13 | + enabled: boolean; |
| 14 | + rules: { |
| 15 | + pattern: string; |
| 16 | + adminOnly: boolean; |
| 17 | + loginRequired: boolean; |
| 18 | + }[]; |
| 19 | +} |
| 20 | + |
| 21 | +const RouteGuard = ({ component: Component, fullRoutePath }: RouteGuardProps) => { |
| 22 | + const { user, isLoading } = useAuth(); |
| 23 | + |
| 24 | + const [loginRequired, setLoginRequired] = useState(false); |
| 25 | + const [adminOnly, setAdminOnly] = useState(false); |
| 26 | + const [authChecked, setAuthChecked] = useState(false); |
| 27 | + |
| 28 | + useEffect(() => { |
| 29 | + getUIRouteAuth((uiRouteAuth: UIRouteAuth) => { |
| 30 | + if (uiRouteAuth?.enabled) { |
| 31 | + for (const rule of uiRouteAuth.rules) { |
| 32 | + if (new RegExp(rule.pattern).test(fullRoutePath)) { |
| 33 | + // Allow multiple rules to be applied according to route precedence |
| 34 | + // Ex: /dashboard/admin/* will override /dashboard/* |
| 35 | + setLoginRequired(loginRequired || rule.loginRequired); |
| 36 | + setAdminOnly(adminOnly || rule.adminOnly); |
| 37 | + } |
| 38 | + } |
| 39 | + } else { |
| 40 | + console.log('UI route auth is not enabled.'); |
| 41 | + } |
| 42 | + setAuthChecked(true); |
| 43 | + }); |
| 44 | + }, [fullRoutePath]); |
| 45 | + |
| 46 | + if (!authChecked || isLoading) { |
| 47 | + return <CircularProgress />; |
| 48 | + } |
| 49 | + |
| 50 | + if (loginRequired && !user) { |
| 51 | + return <Navigate to="/login" />; |
| 52 | + } |
| 53 | + |
| 54 | + if (adminOnly && !user?.admin) { |
| 55 | + return <Navigate to="/not-authorized" />; |
| 56 | + } |
| 57 | + |
| 58 | + return <Component />; |
| 59 | +}; |
| 60 | + |
| 61 | +export default RouteGuard; |
0 commit comments