Skip to content

Instantly share code, notes, and snippets.

@edvinerikson
Last active January 15, 2016 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save edvinerikson/74d5d8ef3574241cd1fc to your computer and use it in GitHub Desktop.
Save edvinerikson/74d5d8ef3574241cd1fc to your computer and use it in GitHub Desktop.
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
const Authenticated = React.createClass({
propTypes: {
children: PropTypes.element.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
history: PropTypes.object.isRequired,
},
componentDidMount() {
this.checkAuth(this.props);
},
componentWillReceiveProps(nextProps) {
this.checkAuth(nextProps);
},
checkAuth(props) {
if (!props.isAuthenticated) {
this.props.history.replaceState(null, '/login');
}
},
render() {
return this.props.isAuthenticated ? this.props.children : null;
},
});
export default connect(
({ sessionToken }) => ({ isAuthenticated: !!sessionToken })
)(Authenticated);
<Route path="/" component={App}>
<Route component={Authenticated}>
<IndexRoute component={Home} />
</Route>
<Route component={UnAuthenticated}>
<Route path="/login" component={Login} />
</Route>
</Route>
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
const UnAuthenticated = React.createClass({
propTypes: {
children: PropTypes.element.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
history: PropTypes.object.isRequired,
},
componentDidMount() {
this.checkAuth(this.props);
},
componentWillReceiveProps(nextProps) {
this.checkAuth(nextProps);
},
checkAuth(props) {
if (props.isAuthenticated) {
this.props.history.replaceState(null, '/');
}
},
render() {
return !this.props.isAuthenticated ? this.props.children : null;
},
});
export default connect(
({ sessionToken }) => ({ isAuthenticated: !!sessionToken })
)(UnAuthenticated);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment