Untitled

mail@pastecode.io avatar
unknown
typescript
a year ago
1.1 kB
1
Indexable
Never
import React from 'react';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import { getStateStore } from 'src/global-state/Store';
import { isUserHasPermissions } from 'src/utils/UserPermissions/hasPermissions';
import { useDispatch, useSelector } from 'react-redux';

interface ProtectedRouteProps extends RouteProps {
  render: (props: any) => JSX.Element;
  permissions: (match: any) => string[];
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ render, permissions, ...rest }) => {
  const userPermissions = useSelector((state: any) => state.user.permissions);
  console.log({ userPermissions });
  return (
    <Route
      {...rest}
      render={(props) => {
        const hasPermission = isUserHasPermissions(permissions(props.match));
        return hasPermission ? (
          render(props)
        ) : (
          <Redirect
            to={{
              pathname: '/',
              state: { from: props.location },
            }}
          />
        );
      }}
    />
  );
};

export default ProtectedRoute;