CPRoute.jsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  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, {action: match => ({type: 'ROUTE', match})})(RRoute)
  12. const ProtectedRoute =({ fallback='/',
  13. roles=['admin'],
  14. auth,
  15. component: Component,
  16. ...routeProps}) => {
  17. const WrapperComponent = (componentProps) => {
  18. let acl = auth?.payload?.sub?.acl
  19. if (localStorage?.authToken && acl && Array.isArray(acl) && acl.length > 0) {
  20. acl = acl.filter(item => {
  21. if(roles.includes(item)) return item
  22. })
  23. if (acl.length > 0){
  24. return <Component {...componentProps}/>
  25. }
  26. }
  27. else if (localStorage?.authToken){
  28. return <Component {...componentProps}/>
  29. }
  30. return <Redirect to={fallback}/>
  31. }
  32. return <CRRoute {...routeProps} component={WrapperComponent}/>
  33. }
  34. export const CPRoute = connect(state => ({auth: state.auth}))(ProtectedRoute)