From 9095ae169504156140390d72306796eb18432399 Mon Sep 17 00:00:00 2001 From: Robin de Boer Date: Fri, 6 Jan 2023 14:46:49 +0100 Subject: [PATCH] Fixed an hard refresh issues with the AuthorizedRoute When hard refreshing a AuthorizedRoute it would always redirect to the dashboard even if the user is already logged in. - In AuthorizedRoute changed the state of the Redirect. This state need the from as a location instead of location being the whole state. Now the Redirect looks the same a the PrivateRoute and this doesn't have this problem. --- src/routeguards/AuthorizedRoute.tsx | 15 ++++++++------- tests/routeguards/AuthorizedRoute.test.tsx | 2 +- 2 files changed, 9 insertions(+), 8 deletions(-) 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 >