forked from finos/architecture-as-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProtectedRoute.tsx
More file actions
39 lines (33 loc) · 1.12 KB
/
ProtectedRoute.tsx
File metadata and controls
39 lines (33 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import React, { ReactNode, useEffect, useState } from 'react';
import { User } from 'oidc-client';
import { authService } from './authService.js';
interface ProtectedRouteProps {
children: ReactNode;
}
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const authenticate = async () => {
const currentUser = await authService.getUser();
if (currentUser && !currentUser.expired) {
setUser(currentUser);
} else if (window.location.search.includes('code=')) {
const loggedInUser = await authService.processRedirect();
setUser(loggedInUser);
} else {
await authService.login();
}
setLoading(false);
};
authenticate();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (!user) {
return <div>Redirecting to login...</div>;
}
return <>{children}</>;
};
export default ProtectedRoute;