I would like to make use of react-router\'s onEnter
handler in order to prompt users to authenticate when entering a restricted route.
So far my route
If you want that you could write route.js like this:
var requireAuth = (store, nextState, replace) => {
console.log("store: ", store);
//now you have access to the store in the onEnter hook!
}
export default (store) => {
return (
);
);
I've setup an example which you could play with in this codepen.
Not sure if triggering an action in order to handle the auth is a good idea. Personally I prefer handling auth in a different way:
Instead of using an onEnter
hook, I use a wrapping function. I want the admin section of my blog protected, therefore I wrapped the AdminContainer
component in the routes with a function, requireAuthentication
, see below.
export default (store, history) => {
return (
{ /* Home (main) route */ }
{ /* */ }
);
};
requireAuthentication
is a function that
Login
You can see it below:
export default function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount () {
this.checkAuth();
}
componentWillReceiveProps (nextProps) {
this.checkAuth();
}
checkAuth () {
if (!this.props.isAuthenticated) {
let redirectAfterLogin = this.props.location.pathname;
this.context.router.replace({pathname: '/login', state: {redirectAfterLogin: redirectAfterLogin}});
}
}
render () {
return (
{this.props.isAuthenticated === true
?
: null
}
)
}
}
const mapStateToProps = (state) => ({
isAuthenticated: state.blog.get('isAuthenticated')
});
AuthenticatedComponent.contextTypes = {
router: React.PropTypes.object.isRequired
};
return connect(mapStateToProps)(AuthenticatedComponent);
}
Also, requireAuthentication
will protect all routes under /admin
. And you can reuse it wherever you like.