-
-
Save rainstormza/92e93f422075ca2087ef5f835500f9f2 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 | |
// https://hackernoon.com/react-authentication-in-depth-part-2-bbf90d42efc9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment