MCPcopy Create free account
hub / github.com/boringstack-xyz/boringstack / ProtectedRoute

Function ProtectedRoute

apps/ui/src/app/router/ProtectedRoute.tsx:18–85  ·  view source on GitHub ↗
({ children })

Source from the content-addressed store, hash-verified

16interface IProtectedRouteProps {
17 readonly children: ReactElement;
18}
19
20export const ProtectedRoute: FC<IProtectedRouteProps> = ({ children }) => {
21 const location = useLocation();
22 const { t } = useTranslation();
23 const me = useMe();
24 const { data, error, isPending, isFetching, refetch } = me;
25 const [timedOut, setTimedOut] = useState(false);
26
27 /*
28 * Wait when either:
29 * 1. `isPending`: first fetch ever; no cached data exists.
30 * 2. `!data && !error && isFetching`: cached `null`/undefined with
31 * a refetch in flight. Covers the post-login window: a
32 * `useMe` invalidation can race the `navigate('/dashboard')`
33 * and ProtectedRoute mounts while the refetch is still
34 * resolving; without this guard a cached `null` would
35 * redirect to /login mid-refetch.
36 */
37 const isResolving =
38 (isPending || (data == null && error == null && isFetching)) && !timedOut;
39
40 const status = resolveAuthStatus({ data, error });
41 const isLoggedOut =
42 !isResolving &&
43 (status === null ||
44 status.kind === "anonymous" ||
45 status.kind === "unauthorized");
46 const attemptedPath = `${location.pathname}${location.search}${location.hash}`;
47
48 /*
49 * Remember the page the visitor wanted, so login, email verification and
50 * the OAuth callback can send them back to it. `state.from` covers only the
51 * password login path; the stored value survives the OAuth round trip.
52 */
53 useEffect(() => {
54 if (isLoggedOut) {
55 storeReturnTo(attemptedPath);
56 }
57 }, [attemptedPath, isLoggedOut]);
58
59 useEffect(() => {
60 if (!isResolving) {
61 return undefined;
62 }
63
64 const timer = setTimeout(() => {
65 setTimedOut(true);
66 }, AUTH_CHECK_TIMEOUT_MS);
67
68 return () => {
69 clearTimeout(timer);
70 };
71 }, [isResolving]);
72
73 const handleRetry = useCallback(() => {
74 void refetch();
75 }, [refetch]);

Callers

nothing calls this directly

Calls 3

useMeFunction · 0.90
resolveAuthStatusFunction · 0.90
tFunction · 0.50

Tested by

no test coverage detected