UNPKG

@vaadin/hilla-react-auth

Version:

Hilla auth utils for React

70 lines 2.11 kB
import { useContext } from "react"; import { Navigate, useLocation } from "react-router"; import { AuthContext } from "./useAuth.js"; import { jsx as _jsx } from "react/jsx-runtime"; function ProtectedRoute({ redirectPath, access, element }) { const { state: { initializing, loading }, hasAccess } = useContext(AuthContext); const location = useLocation(); if (initializing || loading) { return _jsx( "div", // This is for copilot to recognize this {} ); } if (!hasAccess(access)) { return _jsx(Navigate, { to: redirectPath, state: { from: location }, replace: true }); } return element; } ProtectedRoute.type = "ProtectedRoute"; function* traverse(routes) { for (const route of routes) { yield route; if (route.children) { yield* traverse(route.children); } } } /** * Adds protection to a single route that requires authentication. * These route should contain the {@link AccessProps.loginRequired} and/or * {@link AccessProps.rolesAllowed} property to get the protection. Route * without that property won't be protected. * * @param route - the route to protect * @param redirectPath - the path to redirect to if the route is protected * and the user is not authenticated. * @returns the route extended with protection if needed */ export function protectRoute(route, redirectPath = "/login") { const { handle } = route; const requiresAuth = handle?.loginRequired ?? handle?.requiresLogin ?? handle?.rolesAllowed?.length; if (requiresAuth) { route.element = _jsx(ProtectedRoute, { redirectPath, access: handle, element: route.element }); } return route; } /** * Protects a route tree with {@link protectRoute} function. * * @param routes - the roots of the route tree that requires protection. * @param redirectPath - the path to redirect to if the route is * protected and the user is not authenticated. * @returns the protected route tree */ export function protectRoutes(routes, redirectPath = "/login") { for (const route of traverse(routes)) { protectRoute(route, redirectPath); } return routes; } //# sourceMappingURL=./ProtectedRoute.js.map