Skip to content

Instantly share code, notes, and snippets.

@dabit3
Last active February 23, 2021 09:55
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dabit3/36eb8f10a0f67b601402a2ef614a3075 to your computer and use it in GitHub Desktop.
Save dabit3/36eb8f10a0f67b601402a2ef614a3075 to your computer and use it in GitHub Desktop.
Router implementation for React Authentication
import React from 'react'
import {
withRouter,
Switch,
Route,
Redirect,
BrowserRouter as Router
} from 'react-router-dom'
import { Auth } from 'aws-amplify'
import Authenticator from './Authenticator'
import {
Home,
Route1
} from './Home'
class PrivateRoute extends React.Component {
state = {
loaded: false,
isAuthenticated: false
}
componentDidMount() {
this.authenticate()
this.unlisten = this.props.history.listen(() => {
Auth.currentAuthenticatedUser()
.then(user => console.log('user: ', user))
.catch(() => {
if (this.state.isAuthenticated) this.setState({ isAuthenticated: false })
})
});
}
componentWillUnmount() {
this.unlisten()
}
authenticate() {
Auth.currentAuthenticatedUser()
.then(() => {
this.setState({ loaded: true, isAuthenticated: true })
})
.catch(() => this.props.history.push('/auth'))
}
render() {
const { component: Component, ...rest } = this.props
const { loaded , isAuthenticated} = this.state
if (!loaded) return null
return (
<Route
{...rest}
render={props => {
return isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/auth",
}}
/>
)
}}
/>
)
}
}
PrivateRoute = withRouter(PrivateRoute)
const Routes = () => (
<Router>
<Switch>
<Route path='/auth' component={Authenticator} />
<PrivateRoute path='/route1' component={Route1} />
<PrivateRoute path='/' component={Home} />
</Switch>
</Router>
)
export default Routes
@neosarchizo
Copy link

Thanks for good information! But this code doesn't work in my project. If my user signed out, because of not firing listen event so the app can't detect change of auth state. So I use Hub for detecting change of auth state.

@shahab65
Copy link

Thanks for good information! But this code doesn't work in my project. If my user signed out, because of not firing listen event so the app can't detect change of auth state. So I use Hub for detecting change of auth state.

have you installed in configured history package?
https://github.com/ReactTraining/history

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