Skip to content

Instantly share code, notes, and snippets.

@rainstormza
Forked from dabit3/Router.js
Last active May 1, 2018 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rainstormza/92e93f422075ca2087ef5f835500f9f2 to your computer and use it in GitHub Desktop.
Save rainstormza/92e93f422075ca2087ef5f835500f9f2 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
// 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