Last active
May 6, 2016 13:51
-
-
Save dominictobias/403aecf46e1af6c5580f2a47619a8420 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Authenticate component using a wrapper | |
*/ | |
import React, {Component} from 'react'; | |
import { connect } from 'react-redux'; | |
export default function(ComposedComponent) { | |
class Auth extends Component { | |
static contextTypes = { | |
router: React.PropTypes.object | |
} | |
componentWillMount() { | |
if (!this.props.authenticated) { | |
this.props.history.pushState(null, '/login'); | |
} | |
} | |
componentWillUpdate(nextProps) { | |
if (!nextProps.authenticated) { | |
this.props.history.pushState(null, '/login'); | |
} | |
} | |
render() { | |
return <ComposedComponent {...this.props} /> | |
} | |
} | |
function mapStateToProps(state) { | |
return {authenticated: state.auth.authenticated}; | |
} | |
return connect(mapStateToProps)(Auth); | |
} | |
/* | |
Alternatively in route handler events: | |
*/ | |
function requireAuth(nextState, replace) { | |
if (!auth.loggedIn()) { | |
replace({ | |
pathname: '/login', | |
state: { nextPathname: nextState.location.pathname } | |
}) | |
} | |
} | |
// Note: An onChange which can be used on a parent route was recently added | |
// which could be used to authenticate a group of routes. | |
render(( | |
<Router history={browserHistory}> | |
<Route path="/" component={App}> | |
<Route path="login" component={Login} /> | |
<Route path="logout" component={Logout} /> | |
<Route path="about" component={About} /> | |
<Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> | |
</Route> | |
</Router> | |
), document.getElementById('example')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment