From 25cb876cd64bf2dd915ec1a8a5e19eb6ab31e8b9 Mon Sep 17 00:00:00 2001 From: Alberto Defendi <1369-ahl-berto@users.noreply.gitlab.inf.unibz.it> Date: Thu, 27 May 2021 08:44:02 +0200 Subject: [PATCH] Set up HCO. This component will replace PrivateRoute and RestrictedRoute for user reserved area. This will prevent endless route problems and keep every component reusable. --- .../Authorization/Authorization.tsx | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/components/Authorization/Authorization.tsx diff --git a/src/components/Authorization/Authorization.tsx b/src/components/Authorization/Authorization.tsx new file mode 100644 index 0000000..99762a2 --- /dev/null +++ b/src/components/Authorization/Authorization.tsx @@ -0,0 +1,34 @@ +import { Unauthorized } from 'components/NonAuthUser/Unauthorized/Unauthorized'; +import React, { ComponentType, FC } from 'react'; + +interface WithAuthProps { + allowedRoles: string[]; +} + +export interface Props extends WithAuthProps { + children: React.ReactNode; +} + +/* eslint-disable react/jsx-props-no-spreading */ +export const withAuthorization = <T extends WithAuthProps = WithAuthProps>( + WrappedComponent: React.ComponentType<T>, +): FC<T> => { + // Creating the inner component. The calculated Props type here is the where the magic happens. + const ComponentWithAuthorization: FC<T> = ( + props: Omit<T, keyof WithAuthProps>, + ) => { + const { allowedRoles } = props as T; + + const role = 'admin'; + const isAuth = true; + + // props comes afterwards so the can override the default ones. + return allowedRoles.includes(role) && isAuth ? ( + <WrappedComponent {...(props as T)} /> + ) : ( + <Unauthorized /> + ); + }; + + return ComponentWithAuthorization; +}; -- GitLab