Log the user out when the session lapses

Signed-off-by: Mcat12 <newtoncat12@yahoo.com>
This commit is contained in:
Mcat12
2018-05-03 20:14:26 -04:00
parent c6f8e9bba5
commit 9fd526735d
2 changed files with 22 additions and 1 deletions
+6
View File
@@ -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(
(
+16 -1
View File
@@ -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() });