@stevederico/skateboard-ui 1.2.14 → 1.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ProtectedRoute.jsx +28 -2
- package/package.json +1 -1
package/ProtectedRoute.jsx
CHANGED
|
@@ -1,8 +1,34 @@
|
|
|
1
|
+
import { useState, useEffect } from 'react';
|
|
1
2
|
import { Navigate, Outlet } from 'react-router-dom';
|
|
2
|
-
import { isAuthenticated } from './Utilities';
|
|
3
|
+
import { isAuthenticated, apiRequest, getAppKey } from './Utilities';
|
|
3
4
|
|
|
4
5
|
const ProtectedRoute = () => {
|
|
5
|
-
|
|
6
|
+
const [status, setStatus] = useState('checking'); // 'checking' | 'valid' | 'invalid'
|
|
7
|
+
|
|
8
|
+
useEffect(() => {
|
|
9
|
+
if (!isAuthenticated()) {
|
|
10
|
+
setStatus('invalid');
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Validate session with backend
|
|
15
|
+
apiRequest('/me')
|
|
16
|
+
.then(() => setStatus('valid'))
|
|
17
|
+
.catch(() => {
|
|
18
|
+
// Clear stale localStorage data
|
|
19
|
+
const csrfKey = getAppKey('csrf');
|
|
20
|
+
const userKey = getAppKey('user');
|
|
21
|
+
localStorage.removeItem(csrfKey);
|
|
22
|
+
localStorage.removeItem(userKey);
|
|
23
|
+
setStatus('invalid');
|
|
24
|
+
});
|
|
25
|
+
}, []);
|
|
26
|
+
|
|
27
|
+
if (status === 'checking') {
|
|
28
|
+
return null; // Or a loading spinner
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return status === 'valid' ? <Outlet /> : <Navigate to="/signin" replace />;
|
|
6
32
|
};
|
|
7
33
|
|
|
8
34
|
export default ProtectedRoute;
|