Skip to content

Commit 456dfd2

Browse files
committed
requireAuth higher order component
1 parent ca69ef8 commit 456dfd2

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

client/routes.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@ import SignupPage from './components/signup/SignupPage';
77
import LoginPage from './components/login/LoginPage';
88
import NewEventPage from './components/events/NewEventPage';
99

10+
import requireAuth from './utils/requireAuth';
11+
1012
export default (
1113
<Route path="/" component={App}>
1214
<IndexRoute component={Greetings} />
1315
<Route path="signup" component={SignupPage} />
1416
<Route path="login" component={LoginPage} />
15-
<Route path="new-event" component={NewEventPage} />
17+
<Route path="new-event" component={requireAuth(NewEventPage)} />
1618
</Route>
1719
)

client/utils/requireAuth.js

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

0 commit comments

Comments
 (0)