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