From 2398a1ebcbcce95667ac22e1ca843849541daba1 Mon Sep 17 00:00:00 2001 From: Alberto Defendi <1369-ahl-berto@users.noreply.gitlab.inf.unibz.it> Date: Thu, 20 May 2021 12:07:16 +0200 Subject: [PATCH] Restricted route component. --- src/api/RestrictedRoute/RestrictedRoute.tsx | 45 +++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/api/RestrictedRoute/RestrictedRoute.tsx diff --git a/src/api/RestrictedRoute/RestrictedRoute.tsx b/src/api/RestrictedRoute/RestrictedRoute.tsx new file mode 100644 index 0000000..1230e56 --- /dev/null +++ b/src/api/RestrictedRoute/RestrictedRoute.tsx @@ -0,0 +1,45 @@ +import React, { useState, useEffect, useContext } from 'react'; +import { Route, Redirect, RouteProps } from 'react-router-dom'; +import { AuthRoutes, NonAuthRoutes } from 'api/routes'; +import { isAuthenticated } from 'api/isAuthenticated'; + +/** + * + * */ +type Props = { + Component: React.FC<RouteProps>; + restricted: boolean; + path: string; +}; + +/** + * Wrapper for Route that basing on if the user is authenticated, + * redirects to: + * - Entry point of the private route (the homepage); + * - Login page. + */ + +/* eslint-disable react/jsx-props-no-spreading */ +export const RestrictedRoute = ({ Component, path }: Props): JSX.Element => { + const [authUser, setAuthUser] = useState<boolean>(false); + useEffect(() => { + isAuthenticated(setAuthUser); + }); + + return ( + <Route + path={path} + render={(props: RouteProps) => + authUser ? ( + // Redirect to homepage. + <Redirect + to={{ pathname: `${AuthRoutes.dashboard}${AuthRoutes.home}` }} + /> + ) : ( + // Redirect to component. + <Component {...props} /> + ) + } + /> + ); +}; -- GitLab