/
requireAuth.js
46 lines (39 loc) · 1.08 KB
/
requireAuth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import React from 'react';
import { connect } from 'react-redux';
import { addFlashMessage } from '../actions/flashMessages';
export default function(ComposedComponent) {
class Authenticate extends React.Component {
componentWillMount() {
if (!this.props.isAuthenticated) {
this.props.addFlashMessage({
type: 'error',
text: 'You need to login to access this page'
});
this.context.router.push('/login');
}
}
componentWillUpdate(nextProps) {
if (!nextProps.isAuthenticated) {
this.context.router.push('/');
}
}
render() {
return (
<ComposedComponent {...this.props} />
);
}
}
Authenticate.propTypes = {
isAuthenticated: React.PropTypes.bool.isRequired,
addFlashMessage: React.PropTypes.func.isRequired
}
Authenticate.contextTypes = {
router: React.PropTypes.object.isRequired
}
function mapStateToProps(state) {
return {
isAuthenticated: state.auth.isAuthenticated
};
}
return connect(mapStateToProps, { addFlashMessage })(Authenticate);
}