Skip to content

Commit

Permalink
Adding private route
Browse files Browse the repository at this point in the history
  • Loading branch information
craigstroman committed Jul 21, 2020
1 parent 2660d74 commit 76fbd05
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/src/registerServiceWorker.js
/src/apollo.js
/src/shared/util/createFileLink.js
/src/shared/util/privateRoutes.jsx
5 changes: 5 additions & 0 deletions src/pages/Dashboard/Dashboard.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from 'react';

const Dashboard = (props) => <div>Welcome to the dashboard a private route.</div>;

export default Dashboard;
3 changes: 3 additions & 0 deletions src/pages/Home/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { CssBaseline, Grid } from '@material-ui/core';
import styled from 'styled-components';
import PrivateRoute from '../../shared/util/privateRoutes';
import Register from '../Register/Register';
import Login from '../Login/Login';
import Dashboard from '../Dashboard/Dashboard';

const Home = (props) => (
<>
Expand All @@ -16,6 +18,7 @@ const Home = (props) => (
<Route path="/" exact component={Login} />
<Route path="/login" exact component={Login} />
<Route path="/register" exact component={Register} />
<PrivateRoute path="/dashboard" exact component={Dashboard} />
</Switch>
</Grid>
</Grid>
Expand Down
37 changes: 37 additions & 0 deletions src/shared/util/privateRoutes.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import decode from 'jwt-decode';

// TODO: Fix Eslint errors with this file, right now it's disabled on this file.

const isAuthenticated = () => {
const token = localStorage.getItem('token');
const refreshToken = localStorage.getItem('refreshToken');
try {
decode(token);
decode(refreshToken);
} catch (err) {
return false;
}

return true;
};

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) =>
isAuthenticated() ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/login',
}}
/>
)
}
/>
);

export default PrivateRoute;

0 comments on commit 76fbd05

Please sign in to comment.