Guest User

Untitled

a guest
Jun 18th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { connect } from 'react-redux';
  4. import { withRouter } from 'react-router-dom';
  5. import auth from '../api/firebase';
  6. import * as routes from '../constants/routes';
  7.  
  8. // This HOC redirects to the LANDING route if the condition isn't true.
  9. // It's mainly used to redirect to the LANDING route if the user isn't signed in.
  10. const withAuthorization = (condition, route = routes.LANDING) => (Component) => {
  11. class WithAuthorization extends React.Component {
  12. componentDidMount() {
  13. auth.onAuthStateChanged((user) => {
  14. if (!condition(user)) {
  15. this.props.history.push(route);
  16. }
  17. });
  18. }
  19.  
  20. render() {
  21. return this.props.user ? <Component /> : null;
  22. }
  23. }
  24.  
  25. WithAuthorization.propTypes = {
  26. user: PropTypes.object,
  27. history: PropTypes.object.isRequired,
  28. };
  29.  
  30. const mapStateToProps = state => ({
  31. user: state.sessionState.user,
  32. });
  33.  
  34. const temp = connect(mapStateToProps)(WithAuthorization);
  35. return withRouter(temp);
  36. };
  37.  
  38. export default withAuthorization;
Add Comment
Please, Sign In to add comment