Skip to content

Instantly share code, notes, and snippets.

@alexbeletsky
Created November 17, 2017 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbeletsky/c6366776b5f37f2204b3f079a975fe98 to your computer and use it in GitHub Desktop.
Save alexbeletsky/c6366776b5f37f2204b3f079a975fe98 to your computer and use it in GitHub Desktop.
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
export default function requiresAuth(Component) {
class AuthenticatedComponent extends React.Component {
static propTypes = {
user: PropTypes.object,
dispatch: PropTypes.func.isRequired,
};
componentDidMount() {
this._checkAndRedirect();
}
componentDidUpdate() {
this._checkAndRedirect();
}
_checkAndRedirect() {
const { dispatch } = this.props;
if (!this.props.user) {
dispatch(push('/signin'));
}
}
render() {
return (
<div className="authenticated">
{' '}
{this.props.user ? <Component {...this.props} /> : null}{' '}
</div>
);
}
}
const mapStateToProps = state => {
return { user: state.account.user };
};
return connect(mapStateToProps)(AuthenticatedComponent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment