fac19 / week11-where-is-whippy

An ice cream truck finder to connect local ice cream vendors with customers
https://where-is-whippy.netlify.app
1 stars 3 forks source link

RE feedback point 3, protected routes #75

Open Ivo-Evans opened 4 years ago

Ivo-Evans commented 4 years ago

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 commented 4 years ago


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 commented 4 years ago

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