Guest User

Untitled

a guest
Dec 18th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. import React from 'react';
  2. import { Route } from 'react-router-dom';
  3. import PropTypes from 'prop-types';
  4. import AuthContext from './AuthContext';
  5.  
  6. const PrivateRoute = ({component: Component, scopes, ...rest}) => {
  7. return (
  8. <AuthContext.Consumer>
  9. { auth => (
  10. <Route
  11. {...rest}
  12. render={props => {
  13. // 1. Redirect to login if not logged in.
  14. if (!auth.isAuthenticated()) return auth.login();
  15.  
  16. // 2. Display message if user lacks required scope(s).
  17. if(scopes.length > 0 && !auth.userHasScopes(scopes)) {
  18. return (
  19. <h1>
  20. Unauthorized - You need the following scope(s) to view this page: {" "}
  21. {scopes.join(",")}.
  22. </h1>
  23. );
  24. }
  25.  
  26. // 3. Render component
  27. return <Component auth={auth} {...props} />;
  28. }}
  29. />
  30. )}
  31. </AuthContext.Consumer>
  32. );
  33. };
  34.  
  35. PrivateRoute.propTypes = {
  36. component: PropTypes.func.isRequired,
  37. scopes: PropTypes.array
  38. };
  39.  
  40. PrivateRoute.defaultProps = {
  41. scopes: []
  42. };
  43.  
  44. export default PrivateRoute;
Add Comment
Please, Sign In to add comment