Skip to content
Snippets Groups Projects

Set up HCO.

Merged Defendi Alberto requested to merge fix/authorization into dev
1 file
+ 34
0
Compare changes
  • Side-by-side
  • Inline
  • 25cb876c
    Set up HCO. · 25cb876c
    Defendi Alberto authored
    This component will replace PrivateRoute and RestrictedRoute for
    user reserved area. This will prevent endless route problems and keep
    every component reusable.
+ 34
0
 
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;
 
};
Loading