Files
frontend/src/app/routes/RouteGuards.tsx
T
ksv741 f9f0f6921e
Frontend verify / commits (pull_request) Failing after 1m19s
Frontend verify / security (pull_request) Skipped
Frontend verify / verify (pull_request) Skipped
refactor: clarify frontend module ownership
2026-09-29 07:07:36 +03:00

55 lines
1.4 KiB
TypeScript

import { type FC, type PropsWithChildren, useState } from "react";
import { Navigate, useLocation } from "react-router";
import { useAuth } from "@/features/auth";
import { RouteSkeleton } from "./RouteFallback";
const Protected: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { ready, signedOut, user } = useAuth();
const location = useLocation();
const [wasAuthenticated, setWasAuthenticated] = useState(false);
if (user && !wasAuthenticated) setWasAuthenticated(true);
if (!ready) return <RouteSkeleton variant="shell" />;
const loginState = signedOut && wasAuthenticated
? undefined
: { returnTo: `${location.pathname}${location.search}` };
return user
? <>{children}</>
: (
<Navigate
replace
state={loginState}
to="/login"
/>
);
};
const Public: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { ready, user } = useAuth();
const location = useLocation();
if (!ready) return <RouteSkeleton variant="shell" />;
const state: unknown = location.state;
const requested = state && typeof state === "object" && "returnTo" in state
? state.returnTo
: undefined;
const returnTo
= typeof requested === "string"
&& requested.startsWith("/")
&& !requested.startsWith("//")
? requested
: "/accounts";
return user ? <Navigate replace to={returnTo} /> : <>{children}</>;
};
export { Protected, Public };