diff --git a/packages/core/api/token-manager.js b/packages/core/api/token-manager.js index f5d13c977..8290785ad 100644 --- a/packages/core/api/token-manager.js +++ b/packages/core/api/token-manager.js @@ -54,19 +54,17 @@ class TokenManager { const { refresh_token, scope } = token; if (!refresh_token || !scope) return; - await getSafeToken(async () => { - const refreshTokenResponse = await await http.post( - `${constants.AUTH_HOST}${ENDPOINTS.token}`, - { - refresh_token, - grant_type: "refresh_token", - scope: scope, - client_id: "notesnook", - } - ); - await this.saveToken(refreshTokenResponse); - EV.publish(EVENTS.tokenRefreshed); - }, "Error getting refresh token:"); + const refreshTokenResponse = await await http.post( + `${constants.AUTH_HOST}${ENDPOINTS.token}`, + { + refresh_token, + grant_type: "refresh_token", + scope: scope, + client_id: "notesnook", + } + ); + await this.saveToken(refreshTokenResponse); + EV.publish(EVENTS.tokenRefreshed); }); } diff --git a/packages/core/api/user-manager.js b/packages/core/api/user-manager.js index af2c96c32..0b838163d 100644 --- a/packages/core/api/user-manager.js +++ b/packages/core/api/user-manager.js @@ -30,8 +30,16 @@ class UserManager { this._db = db; this.tokenManager = new TokenManager(storage); - EV.subscribe(EVENTS.logoutUser, async (reason) => { - await this.logout(true, reason); + EV.subscribe(EVENTS.userUnauthorized, async (url) => { + if (url.includes("/connect/token")) return; + try { + await this.tokenManager._refreshToken(true); + } catch (e) { + await this.logout( + false, + `Your token has been revoked. Error: ${e.message}.` + ); + } }); } diff --git a/packages/core/common.js b/packages/core/common.js index d16dd5aa5..ad33183ea 100644 --- a/packages/core/common.js +++ b/packages/core/common.js @@ -47,7 +47,7 @@ export const EVENTS = { appRefreshRequested: "app:refreshRequested", noteRemoved: "note:removed", tokenRefreshed: "token:refreshed", - logoutUser: "user:logout", + userUnauthorized: "user:unauthorized", attachmentsLoading: "attachments:loading", attachmentDeleted: "attachment:deleted", mediaAttachmentDownloaded: "attachments:mediaDownloaded", diff --git a/packages/core/utils/http.js b/packages/core/utils/http.js index 8eb9e69fe..c167fefc9 100644 --- a/packages/core/utils/http.js +++ b/packages/core/utils/http.js @@ -61,11 +61,10 @@ async function handleResponse(response) { if (response.status === 429) throw new Error("You are being rate limited."); if (response.ok) return await response.text(); - // else if (response.status === 401) { - // EV.publish(EVENTS.logoutUser, `401 unauthorized.`); - // throw new Error("Unauthorized."); - // } - else + else if (response.status === 401) { + EV.publish(EVENTS.userUnauthorized, response.url); + throw new Error("Unauthorized."); + } else throw new Error( `Request failed with status code: ${response.status} ${response.statusText}.` );