Skip to content

Instantly share code, notes, and snippets.

@rcdexta
Forked from fdidron/App.js
Last active May 3, 2017 04:40
Show Gist options
  • Save rcdexta/41088646257d83158ea69209f40adc58 to your computer and use it in GitHub Desktop.
Save rcdexta/41088646257d83158ea69209f40adc58 to your computer and use it in GitHub Desktop.
React Router v4 Auth
//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 { 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';
export default class AuthRoute extends React.Component {
render() {
const {component} = this.props
const { isPrivate } = component;
if (isAuthenticated()) {
//User is Authenticated
if (isPrivate) {
//If the route is private the user may proceed.
return <Route { ...this.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) {
//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 { ...this.props } component={ component } />;
}
}
}
AuthRoute.PropTypes = {
component: React.PropTypes.oneOfType([
React.PropTypes.element,
React.PropTypes.func
])
}
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>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment