-
-
Save fdidron/ebcf52dc1ed62ff7d80725854d631a9e to your computer and use it in GitHub Desktop.
//Usage | |
import React from 'react'; | |
import { BrowserRouter as Router } from 'react-router-dom'; | |
import Route from './AuthRoute'; | |
import Login from './Login'; | |
import Private from './Private'; | |
export default () => | |
<Router> | |
<div> | |
<Route component={ Login } path="/login" /> | |
<Route component={ Private } path="/private" /> | |
</div> | |
</Router>; |
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { Redirect, Route } from 'react-router-dom'; | |
//Mock of an Auth method, can be replaced with an async call to the backend. Must return true or false | |
const isAuthenticated = () => true; | |
const PRIVATE_ROOT = '/private'; | |
const PUBLIC_ROOT = '/login'; | |
const AuthRoute = ({component, ...props}) => { | |
const { isPrivate } = component; | |
if (isAuthenticated()) { | |
//User is Authenticated | |
if (isPrivate === true) { | |
//If the route is private the user may proceed. | |
return <Route { ...props } component={ component } />; | |
} | |
else { | |
//If the route is public, the user is redirected to the app's private root. | |
return <Redirect to={ PRIVATE_ROOT } />; | |
} | |
} | |
else { | |
//User is not Authenticated | |
if (isPrivate === true) { | |
//If the route is private the user is redirected to the app's public root. | |
return <Redirect to={ PUBLIC_ROOT } />; | |
} | |
else { | |
//If the route is public, the user may proceed. | |
return <Route { ...props } component={ component } />; | |
} | |
} | |
}; | |
AuthRoute.propTypes = { | |
component: PropTypes.oneOfType([ | |
PropTypes.element, | |
PropTypes.func | |
]) | |
}; | |
export default AuthRoute; |
import React from 'react'; | |
export default class Login extends React.Component { | |
static isPrivate = false | |
render() { | |
return <h1>{' Login '}</h1>; | |
} | |
} |
import React from 'react'; | |
export default class Private extends React.Component { | |
static isPrivate = true | |
render() { | |
return <h1>{' Private '}</h1>; | |
} | |
} |
@bramchi since this comment my <PrivateRoute/>
has been updated a few times. Here is what I have been using in a number of production apps. It is possible it isn't the best practice but I haven't had problems with it so I haven't touched it in a while. Let me know if I can explain parts. Happy to help. 😄
Note: I use Firebase in most of my apps and so you will see that integrated here as well.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import firebase from 'firebase'
//import PropTypes from 'prop-types'
import {
Route,
Redirect,
withRouter
} from 'react-router-dom'
/**
* Component that protects route from unauthorized users.
* @type {Object}
*/
class PrivateRoute extends Component{
render(){
const { component: Component, requiredUserType, userPermissions, ...rest } = this.props
//This catches the infinite loop and warning I was getting from the animation.
if (rest.location.pathname === '/signIn'){ return null }
if (firebase.auth().currentUser){
if (requiredUserType){
if (userPermissions[requiredUserType]){
return <Route {...rest} render={ props => <Component {...props}/> }/>
}
return <Route {...rest} render={ () => <Redirect to={{ pathname: '/portal/403' }} /> }/>
}
return <Route {...rest} render={ props => <Component {...props}/> }/>
}
return <Route {...rest} render={ props => <Redirect to={{ pathname: '/signIn', state: { from: props.location } }}/> }/>
}
}
PrivateRoute.propTypes = {}
PrivateRoute.defaultProps = {}
const mapStateToProps = (state) => {
const { userPermissions } = state.Auth
return { userPermissions }
}
export default withRouter(connect(mapStateToProps)(PrivateRoute))
If someone else get the error:
Warning: You tried to redirect to the same route you're currently on: "/login" react router
, here is the solution:
First thanks for sharing this!
@stephenhandley You probably don't make an async call at all from the AuthRoute. The async should be done from a login form to authenticate and then save the session (cookie or JWT). The isAuthenticated() is then a sync call to check if there is a session.I just followed this article http://www.thegreatcodeadventure.com/jwt-authentication-with-react-redux/ which works great with this. With that approach you can just pass the redux state "session" to the AuthRoute component and check if there session os true or false.
What about checking if user is authorized if they leave the page and want to come back to it, like a simple refresh is going to remove store state. I am trying to achieve authentication while using httpOnly cookies so I have to make requests to my backend to authenticate the user. As far as I am concerned the only way I could do that is by making an async call, but I am assuming I might have to use something like a wrapper or an HOC to achieve this, any thoughts?
@arr0nax @SCasarotto Could you share an example snippet of your solution? I'm having similar redirect issues since I added react-transition-group, but I'm not sure where and how to return that null route... Thanks! 😄