diff --git a/src/routeguards/AuthorizedRoute.tsx b/src/routeguards/AuthorizedRoute.tsx index 20ae557..db4d2fe 100644 --- a/src/routeguards/AuthorizedRoute.tsx +++ b/src/routeguards/AuthorizedRoute.tsx @@ -5,7 +5,7 @@ import { useLocation } from 'react-router'; import { getConfig, Config } from '../config'; import { useAuthentication } from '../hooks'; -export type Authorizer = (user: User) => boolean; +export type Authorizer = (user?: User) => boolean; export interface Props extends RouteProps { authorizer: Authorizer; @@ -35,26 +35,27 @@ export function AuthorizedRoute({ ...rest }: Props): JSX.Element { const config: Config = getConfig(); - const authentication = useAuthentication(); + const { currentUser, isLoggedIn } = useAuthentication(); const location = useLocation(); - const isLoggedIn = authentication.isLoggedIn; - /* We first check if the user is logged in before authorizing, this prevents a redirect loop where a redirect mechanism is in place within login that automatically redirects users to the previous attempted route upon login. */ if (!isLoggedIn) { - return ; + return ( + + ); } /* After we have asserted that the user is not logged in, but somehow lacks privileges, we send it to the dashboard instead of the login to prevent the loop from happening. */ - const user = authentication.currentUser as User; - const allowed = authorizer(user); + const allowed = authorizer(currentUser); if (!allowed) { return ; diff --git a/tests/routeguards/AuthorizedRoute.test.tsx b/tests/routeguards/AuthorizedRoute.test.tsx index ebfd2ab..088f266 100644 --- a/tests/routeguards/AuthorizedRoute.test.tsx +++ b/tests/routeguards/AuthorizedRoute.test.tsx @@ -57,7 +57,7 @@ describe('AuthorizedRoute', () => { - authorizer={(user) => user.isAdmin} + authorizer={(user) => !!user?.isAdmin} path="/admin" exact >