2016-08-10 21:36:11 +02:00
|
|
|
/**
|
|
|
|
* Container wrapping elements neeeding a valid session. Automatically
|
|
|
|
* redirects to login form in case such session does not exist.
|
|
|
|
*/
|
2016-07-07 23:23:18 +02:00
|
|
|
import React, { Component, PropTypes } from "react";
|
|
|
|
import { connect } from "react-redux";
|
|
|
|
|
2016-08-10 21:36:11 +02:00
|
|
|
|
2016-07-07 23:23:18 +02:00
|
|
|
export class RequireAuthentication extends Component {
|
2016-08-10 23:50:23 +02:00
|
|
|
componentWillMount() {
|
2016-08-10 21:36:11 +02:00
|
|
|
// Check authentication on mount
|
2016-07-07 23:23:18 +02:00
|
|
|
this.checkAuth(this.props.isAuthenticated);
|
|
|
|
}
|
|
|
|
|
2016-08-10 23:50:23 +02:00
|
|
|
componentWillUpdate(newProps) {
|
2016-08-10 21:36:11 +02:00
|
|
|
// Check authentication on update
|
2016-08-06 17:20:02 +02:00
|
|
|
this.checkAuth(newProps.isAuthenticated);
|
2016-07-07 23:23:18 +02:00
|
|
|
}
|
|
|
|
|
2016-08-10 21:36:11 +02:00
|
|
|
/**
|
|
|
|
* Handle redirection in case user is not authenticated.
|
|
|
|
*
|
|
|
|
* @param isAuthenticated A boolean stating whether user has a valid
|
|
|
|
* session or not.
|
|
|
|
*/
|
2016-08-10 23:50:23 +02:00
|
|
|
checkAuth(isAuthenticated) {
|
2016-07-07 23:23:18 +02:00
|
|
|
if (!isAuthenticated) {
|
2016-08-10 21:36:11 +02:00
|
|
|
// Redirect to login, redirecting to the actual page after login.
|
2016-07-07 23:23:18 +02:00
|
|
|
this.context.router.replace({
|
|
|
|
pathname: "/login",
|
|
|
|
state: {
|
|
|
|
nextPathname: this.props.location.pathname,
|
2016-08-10 23:50:23 +02:00
|
|
|
nextQuery: this.props.location.query,
|
|
|
|
},
|
2016-07-07 23:23:18 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-10 23:50:23 +02:00
|
|
|
render() {
|
2016-07-07 23:23:18 +02:00
|
|
|
return (
|
|
|
|
<div>
|
2016-08-10 21:36:11 +02:00
|
|
|
{this.props.isAuthenticated === true
|
|
|
|
? this.props.children
|
|
|
|
: null
|
|
|
|
}
|
2016-07-07 23:23:18 +02:00
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
RequireAuthentication.propTypes = {
|
|
|
|
// Injected by React Router
|
2016-08-10 23:50:23 +02:00
|
|
|
children: PropTypes.node,
|
2016-07-07 23:23:18 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
RequireAuthentication.contextTypes = {
|
2016-08-10 23:50:23 +02:00
|
|
|
router: PropTypes.object.isRequired,
|
2016-07-07 23:23:18 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
const mapStateToProps = (state) => ({
|
2016-08-10 23:50:23 +02:00
|
|
|
isAuthenticated: state.auth.isAuthenticated,
|
2016-07-07 23:23:18 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
export default connect(mapStateToProps)(RequireAuthentication);
|