ampache_react/app/containers/RequireAuthentication.js

65 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

/**
* 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-07-07 23:23:18 +02:00
export class RequireAuthentication extends Component {
componentWillMount() {
// Check authentication on mount
2016-07-07 23:23:18 +02:00
this.checkAuth(this.props.isAuthenticated);
}
componentWillUpdate(newProps) {
// Check authentication on update
2016-08-06 17:20:02 +02:00
this.checkAuth(newProps.isAuthenticated);
2016-07-07 23:23:18 +02:00
}
/**
* Handle redirection in case user is not authenticated.
*
* @param isAuthenticated A boolean stating whether user has a valid
* session or not.
*/
checkAuth(isAuthenticated) {
2016-07-07 23:23:18 +02:00
if (!isAuthenticated) {
// 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,
nextQuery: this.props.location.query,
},
2016-07-07 23:23:18 +02:00
});
}
}
render() {
2016-07-07 23:23:18 +02:00
return (
<div>
{this.props.isAuthenticated === true
? this.props.children
: null
}
2016-07-07 23:23:18 +02:00
</div>
);
}
}
RequireAuthentication.propTypes = {
// Injected by React Router
children: PropTypes.node,
2016-07-07 23:23:18 +02:00
};
RequireAuthentication.contextTypes = {
router: PropTypes.object.isRequired,
2016-07-07 23:23:18 +02:00
};
const mapStateToProps = (state) => ({
isAuthenticated: state.auth.isAuthenticated,
2016-07-07 23:23:18 +02:00
});
export default connect(mapStateToProps)(RequireAuthentication);