{"size": 999, "ext": "js", "max_stars_repo_path": "frontend/src/components/AuthenticatedComponent.js", "max_stars_repo_name": "OpenCollective/app", "max_stars_repo_stars_event_min_datetime": "2016-04-03T02:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-30T19:20:15.000Z", "max_issues_repo_path": "frontend/src/components/AuthenticatedComponent.js", "max_issues_repo_name": "OpenCollective/opencollective-app", "max_issues_repo_issues_event_min_datetime": "2016-06-06T22:00:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-06T22:05:50.000Z", "max_forks_repo_path": "frontend/src/components/AuthenticatedComponent.js", "max_forks_repo_name": "OpenCollective/opencollective-app", "max_forks_repo_forks_event_min_datetime": "2016-07-09T22:18:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-01-27T10:45:50.000Z"}
{"max_stars_count": 6, "max_issues_count": 17, "max_forks_count": 3, "avg_line_length": 23.2325581395, "max_line_length": 125, "alphanum_fraction": 0.6656656657}
import React from 'react';
import { connect } from 'react-redux';
import { pushState } from 'redux-router';

// Taken from https://github.com/joshgeller/react-redux-jwt-auth-example/blob/master/src/components/AuthenticatedComponent.js
export function requireAuthentication(Component) {

  class AuthenticatedComponent extends React.Component {

    componentWillMount() {
      this.checkAuth();
    }

    componentWillReceiveProps() {
      this.checkAuth();
    }

    checkAuth() {
      if (!this.props.isAuthenticated) {
        const redirectAfterLogin = this.props.location.pathname;
        this.props
        .dispatch(pushState(null, `/login?next=${redirectAfterLogin}`));
      }
    }

    render() {

      if (this.props.isAuthenticated) {
        return <Component {...this.props}/>;
      }

      return null;
    }
  }

  const mapStateToProps = (state) => ({
    isAuthenticated: state.session.isAuthenticated
  });

  return connect(mapStateToProps)(AuthenticatedComponent);

}
