Skip to content

Instantly share code, notes, and snippets.

@Janekk
Created September 25, 2017 11:48
Show Gist options
  • Save Janekk/d6566c5e39e384b901c42d5aea7814ff to your computer and use it in GitHub Desktop.
Save Janekk/d6566c5e39e384b901c42d5aea7814ff to your computer and use it in GitHub Desktop.
Higher Order Compoennt - AuthenticatedPage
import React from 'react';
import {connect} from 'react-redux';
import _ from 'lodash';
/**
* Higher ordered component for pages requiring authentication.
*/
const AuthenticatedPage = (PageComponent) => {
class AuthenticatedPageHOC extends React.Component {
componentWillReceiveProps(nextProps) {
const isLoggedOut = !_.get(this.props, 'auth.token') && _.get(nextProps, 'auth.token');
if(isLoggedOut) {
this.redirectOnLogout(nextProps);
}
}
redirectOnLogout(props) {
const {location} = props;
if (location.pathname !== '/login') {
this.context.router.push('/login');
}
}
render() {
const {auth, apProfile} = this.props;
if (!auth.token || !apProfile) {
return null;
}
return (<PageComponent {...this.props}/>);
}
}
AuthenticatedPageHOC.displayName = 'AuthenticatedPageHOC';
AuthenticatedPageHOC.contextTypes = {
router: React.PropTypes.object.isRequired
};
function mapStateToProps(state) {
return {
auth: state.auth,
profile: _.get(state.profile, 'profile')
};
}
// Wrap the component to inject dispatch and state into it
return connect(mapStateToProps)(AuthenticatedPageHOC);
};
export default AuthenticatedPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment