diff --git a/src/index.js b/src/index.js index cf71897..9337d82 100644 --- a/src/index.js +++ b/src/index.js @@ -13,6 +13,12 @@ import ReactDOM from 'react-dom'; import { HashRouter, Route, Switch } from 'react-router-dom' import 'ionicons/dist/css/ionicons.min.css'; import Full from './containers/Full' +import { api } from "./utils"; + +// Before rendering anything, check if there is a session cookie. +// Note: the user could have an old session, so the first API call +// will set loggedIn to false if necessary +api.loggedIn = document.cookie.includes("user_id="); ReactDOM.render( ( diff --git a/src/utils.js b/src/utils.js index c122e4f..1397679 100644 --- a/src/utils.js +++ b/src/utils.js @@ -33,7 +33,7 @@ export const makeCancelable = (promise, { repeat = null, interval = 0 } = {}) => const handle = (resolve, reject, val, isError) => { if(hasCanceled) - reject({isCanceled: true}); + reject({ isCanceled: true }); else { if(isError) reject(val); @@ -134,6 +134,7 @@ export const api = { return fetch(api.urlFor(url), { credentials: this.credentialType() }) + .then(api.checkIfLoggedOut) .then(api.convertJSON) .then(api.checkForErrors); }, @@ -155,6 +156,20 @@ export const api = { .then(api.convertJSON) .then(api.checkForErrors); }, + /** + * If the user is logged in, check if the user's session has lapsed. + * If so, log them out and refresh the page. + */ + checkIfLoggedOut(response) { + if(api.loggedIn && response.status === 401) { + // Clear the user's old session and refresh the page + document.cookie = 'user_id=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; + window.location.reload(); + return Promise.reject({ isCanceled: true }) + } + + return Promise.resolve(response); + }, async convertJSON(data) { if(!data.ok) return Promise.reject({ data, json: await data.json() });