From 3674594832fbad1b75a572d81405ff7ebda04314 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Fri, 17 Mar 2023 17:00:15 +0500 Subject: [PATCH] core: do a healthcheck before logging out user on session revoke --- packages/core/api/healthcheck.js | 31 +++++++++++++++++++++++++++++++ packages/core/api/user-manager.js | 17 ++++++++++++----- 2 files changed, 43 insertions(+), 5 deletions(-) create mode 100644 packages/core/api/healthcheck.js diff --git a/packages/core/api/healthcheck.js b/packages/core/api/healthcheck.js new file mode 100644 index 000000000..5152e0eaa --- /dev/null +++ b/packages/core/api/healthcheck.js @@ -0,0 +1,31 @@ +/* +This file is part of the Notesnook project (https://notesnook.com/) + +Copyright (C) 2023 Streetwriters (Private) Limited + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ +import hosts from "../utils/constants"; +import http from "../utils/http"; + +export class HealthCheck { + static async isAuthServerHealthy() { + try { + const response = await http.get(`${hosts.AUTH_HOST}/health`); + return response.trim() === "Healthy"; + } catch { + return false; + } + } +} diff --git a/packages/core/api/user-manager.js b/packages/core/api/user-manager.js index 64dc1505e..62f447c5b 100644 --- a/packages/core/api/user-manager.js +++ b/packages/core/api/user-manager.js @@ -22,6 +22,7 @@ import http from "../utils/http"; import constants from "../utils/constants"; import TokenManager from "./token-manager"; import { EV, EVENTS } from "../common"; +import { HealthCheck } from "./healthcheck"; const ENDPOINTS = { signup: "/users", @@ -48,14 +49,20 @@ class UserManager { this.tokenManager = new TokenManager(storage); EV.subscribe(EVENTS.userUnauthorized, async (url) => { - if (url.includes("/connect/token")) return; + if ( + url.includes("/connect/token") || + !(await HealthCheck.isAuthServerHealthy()) + ) + return; try { await this.tokenManager._refreshToken(true); } catch (e) { - await this.logout( - false, - `Your token has been revoked. Error: ${e.message}.` - ); + if (e.message === "invalid_grant" || e.message === "invalid_client") { + await this.logout( + false, + `Your token has been revoked. Error: ${e.message}.` + ); + } } }); }