Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RE feedback point 3, protected routes #75

Open
Ivo-Evans opened this issue May 29, 2020 · 2 comments
Open

RE feedback point 3, protected routes #75

Ivo-Evans opened this issue May 29, 2020 · 2 comments
Labels
code review enhancement New feature or request

Comments

@Ivo-Evans
Copy link
Member

Ivo-Evans commented May 29, 2020

What we did is write a component called ProtectedRoute that either returned a Route or a Redirect depending on whether the user was logged in. If they were logged in it returned the route, otherwise a redirect to the login page. We then put it in our router switch statement whenever we wanted a protected route. The component ended up looking like this:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

export default function ProtectedRoute({ path, component }) {
	if (authorised()) {
		return <Route exact path={path} component={component} />;
	}
	return <Redirect to="/" />;
}

And our authorised() function looked like this

export default function authorised() {
	const authString = localStorage.getItem('auth');
	if (authString) {
		const auth = JSON.parse(authString);
		if (validateExp(auth.expires)) {
			return true;
		}
	}
	return false;
}

validateExp is another one we wrote ourselves. It compares the time in the JWT against the present.

This method doesn't stop a hacker getting to the route. That would require a server request. It just stops a normal user who isnt logged in getting to a route, so it makes routes semi-protected. For us, the specifics, like the cards on the page, required a server request, and there we checked that the JWT was verified

@Ivo-Evans Ivo-Evans added code review enhancement New feature or request labels May 29, 2020
@Ivo-Evans
Copy link
Member Author

export default function validateExp(exp) {
	const date = new Date();
	const now = Math.round(date.getTime() / 1000); // JavaSript dates are accurate to the millisecond but the JWT standard specifies dates accurate to the second
	return Number(exp) > now;
}

@Joepock123
Copy link
Collaborator

Sweet cheers for this @Ivo-Evans really useful :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
code review enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants