Last active
February 23, 2021 09:55
-
-
Save dabit3/36eb8f10a0f67b601402a2ef614a3075 to your computer and use it in GitHub Desktop.
Router implementation for React Authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
have you installed in configured history package?
https://github.com/ReactTraining/history