1
- import React from 'react' ;
1
+ import React , { useEffect , useState } from 'react' ;
2
2
import { Navigate } from 'react-router-dom' ;
3
+ import userService from '../../services/users' ;
3
4
4
- // Authenticate user only if they log in once, token is available until they close the tab/browser for now
5
- const isAuthenticated = ( ) => {
6
- const token = sessionStorage . getItem ( 'jwt_token' ) ; // Get token stored in session storage
7
- if ( ! token ) {
8
- return false ;
9
- }
5
+ const Loading = ( ) => {
6
+ return (
7
+ < div className = "d-flex flex-column justify-content-center align-items-center" style = { { minHeight : '100vh' } } >
8
+ < div className = "spinner-border text-primary" role = "status" style = { { width : '3rem' , height : '3rem' } } >
9
+ </ div >
10
+ < p className = "mt-3" > Loading, please wait...</ p >
11
+ </ div >
12
+ )
13
+ }
14
+
15
+ const ProtectedRoute = ( { children } ) => {
16
+ const [ isAuthenticated , setIsAuthenticated ] = useState ( null ) ;
17
+
18
+ useEffect ( ( ) => {
19
+ const token = sessionStorage . getItem ( 'jwt_token' ) ;
20
+ const authHeader = {
21
+ headers : {
22
+ 'Authorization' : `Bearer ${ token } ` ,
23
+ } ,
24
+ } ;
10
25
11
- return true ;
12
- } ;
26
+ // verify token asynchronously, set auth status only after request completes
27
+ userService . verifyToken ( authHeader )
28
+ . then ( response => {
29
+ console . log ( response ) ;
30
+ setIsAuthenticated ( true ) ;
31
+ } )
32
+ . catch ( e => {
33
+ console . log ( 'Error:' , e ) ;
34
+ setIsAuthenticated ( false ) ;
35
+ } ) ;
36
+ } , [ ] ) ;
37
+
38
+ // To wait for isAuth to generate, render loading spinner
39
+ if ( isAuthenticated == null ) {
40
+ return < Loading /> ;
41
+ }
13
42
14
- const ProtectedRoute = ( { children} ) => {
15
- return isAuthenticated ( ) ? children : < Navigate to = '/login' /> ;
16
- } ;
43
+ return isAuthenticated ? children : < Navigate to = "/login" />
44
+ }
17
45
18
- export default ProtectedRoute ;
46
+ export default ProtectedRoute ;
0 commit comments