CPRoute.jsx 1.4 KB

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