Skip to content

Instantly share code, notes, and snippets.

@PierBover
Created July 16, 2016 01:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PierBover/220b2f7d5f790158790d3adb55f0a140 to your computer and use it in GitHub Desktop.
Save PierBover/220b2f7d5f790158790d3adb55f0a140 to your computer and use it in GitHub Desktop.
JWT Auth React Router async wait
render((
<div>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Start}/>
<Route path="login" component={Login}/>
// Everything inside Main is private
<Route component={Main}>
<Route path="home" component={Home}/>
<Route path="setting" component={Settings}/>
// etc
</Route>
</Route>
<Route path="*" component={Ooops}/>
</Router>
</div>
), document.getElementById('app-react'))
import React from 'react'
export default class Main extends React.Component {
constructor(props){
super(props)
this.state = {}
}
componentWillMount(){
this.checkAuth()
}
checkAuth(){
// Here we do stuff to check if the user is already logged in or not
// Since we are using Firebase with JWT it takes a bit to know if a user
// is logged or not.
// This is our own specific implementation so stateManager and eventBus are our own
let isLogged = this.stateManager.getState('isLogged')
if(isLogged == undefined){
this.eventBus.addListener(this.events.auth.loggedIn,this.checkAuth,this)
this.eventBus.addListener(this.events.auth.loggedOut,this.checkAuth,this)
} else {
this.eventBus.removeListener(this.events.auth.loggedIn,this.checkAuth,this)
this.eventBus.removeListener(this.events.auth.loggedOut,this.checkAuth,this)
// Once we have a known state of either logged in or out we can show the children
this.setState({
showChildren:true
})
// And redirect appropirately
this.redirect(isLogged)
}
}
redirect(isLogged){
if(isLogged) {
// If the user is logged we push the actual path again so the Main component loads again
this.history.push(this.props.location.pathname)
} else {
//If not we send the user to the login form
this.history.push('/login')
}
}
render(){
return(
<div>
{this.state.showChildren ? this.props.chidlren : null}
</div>
)
}
}
@PierBover
Copy link
Author

I didn't test this exact code, but you get the idea...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment