diff --git a/src/components/Authorization/Authorization.tsx b/src/components/Authorization/Authorization.tsx new file mode 100644 index 0000000000000000000000000000000000000000..99762a2035ac8fa1958e650628e8280271db8e8f --- /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; +};