38 lines
1014 B
TypeScript
38 lines
1014 B
TypeScript
/**
|
|
* Route guard component.
|
|
*
|
|
* Wraps protected routes. If the user is not authenticated they are
|
|
* redirected to `/login` and the intended destination is preserved so the
|
|
* user lands on it after a successful login.
|
|
*/
|
|
|
|
import { Navigate, useLocation } from "react-router-dom";
|
|
import { useAuth } from "../hooks/useAuth";
|
|
|
|
interface RequireAuthProps {
|
|
/** The protected page content to render when authenticated. */
|
|
children: React.JSX.Element;
|
|
}
|
|
|
|
/**
|
|
* Render `children` only if the user is authenticated.
|
|
*
|
|
* Redirects to `/login?next=<path>` otherwise so the intended destination is
|
|
* preserved and honoured after a successful login.
|
|
*/
|
|
export function RequireAuth({ children }: RequireAuthProps): React.JSX.Element {
|
|
const { isAuthenticated } = useAuth();
|
|
const location = useLocation();
|
|
|
|
if (!isAuthenticated) {
|
|
return (
|
|
<Navigate
|
|
to={`/login?next=${encodeURIComponent(location.pathname + location.search)}`}
|
|
replace
|
|
/>
|
|
);
|
|
}
|
|
|
|
return children;
|
|
}
|