CPRoute.jsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import {connect} from "react-redux";
  2. import {Redirect} from "react-router-dom";
  3. import Route from "react-router-dom/es/Route";
  4. import {actionMyRoute} from "../reducers/RouteReducer";
  5. const RRoute = ({action, component: Component, ...routeProps}) => {
  6. const WrapperComponent = (componentProps) => {
  7. action(componentProps.match)
  8. return <Component {...componentProps}/>
  9. }
  10. return <Route {...routeProps} component={WrapperComponent}/>
  11. }
  12. export const CRRoute = connect(null,
  13. {action: actionMyRoute})(RRoute)
  14. const ProtectedRoute =({ fallback='/',
  15. roles=['admin'],
  16. auth,
  17. component: Component,
  18. ...routeProps}) => {
  19. const WrapperComponent = (componentProps) => {
  20. let acl = auth?.payload?.sub?.acl
  21. if (localStorage?.authToken && acl && Array.isArray(acl) && acl.length > 0) {
  22. acl = acl.filter(item => {
  23. if(roles.includes(item)) return item
  24. })
  25. if (acl.length > 0){
  26. return <Component {...componentProps}/>
  27. }
  28. }
  29. else if (localStorage?.authToken){
  30. return <Component {...componentProps}/>
  31. }
  32. return <Redirect to={fallback}/>
  33. }
  34. return <CRRoute {...routeProps} component={WrapperComponent}/>
  35. }
  36. export const CPRoute = connect(state => ({auth: state.auth}))(ProtectedRoute)