Skip to content

Commit

Permalink
Fixed an hard refresh issues with the AuthorizedRoute
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
botenbreuk authored and gidomanders committed Jan 12, 2023
1 parent b7a9d97 commit 9095ae1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
15 changes: 8 additions & 7 deletions src/routeguards/AuthorizedRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useLocation } from 'react-router';
import { getConfig, Config } from '../config';
import { useAuthentication } from '../hooks';

export type Authorizer<User> = (user: User) => boolean;
export type Authorizer<User> = (user?: User) => boolean;

export interface Props<User> extends RouteProps {
authorizer: Authorizer<User>;
Expand Down Expand Up @@ -35,26 +35,27 @@ export function AuthorizedRoute<User>({
...rest
}: Props<User>): JSX.Element {
const config: Config = getConfig();
const authentication = useAuthentication();
const { currentUser, isLoggedIn } = useAuthentication<User>();
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 <Redirect to={{ pathname: config.loginRoute, state: location }} />;
return (
<Redirect
to={{ pathname: config.loginRoute, state: { from: location } }}
/>
);
}

/*
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 <Redirect to={{ pathname: config.dashboardRoute }} />;
Expand Down
2 changes: 1 addition & 1 deletion tests/routeguards/AuthorizedRoute.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe('AuthorizedRoute', () => {
</PrivateRoute>

<AuthorizedRoute<User>
authorizer={(user) => user.isAdmin}
authorizer={(user) => !!user?.isAdmin}
path="/admin"
exact
>
Expand Down

0 comments on commit 9095ae1

Please sign in to comment.