Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: refresh token on 401 unauthorized error

thecodrrc089ccbe1929
diff --git a/packages/core/api/token-manager.js b/packages/core/api/token-manager.js
index 937228497..b35a41a3b 100644
--- a/packages/core/api/token-manager.js
+++ b/packages/core/api/token-manager.js
@@ -18,6 +18,11 @@ class TokenManager {
constructor(storage) {
this._storage = storage;
this._refreshTokenMutex = withTimeout(new Mutex(), 10 * 1000);
+ EV.subscribe(EVENTS.refreshToken, async (url) => {
+ if (url && url.includes(ENDPOINTS.token)) return;
+
+ await this._refreshToken(true);
+ });
}
async getToken(renew = true, forceRenew = false) {
@@ -37,17 +42,11 @@ class TokenManager {
}
async getAccessToken(forceRenew = false) {
- try {
+ return await getSafeToken(async () => {
const token = await this.getToken(true, forceRenew);
if (!token) return;
return token.access_token;
- } catch (e) {
- console.error("Error getting access token:", e);
- if (e.message === "invalid_grant" || e.message === "invalid_client") {
- EV.publish(EVENTS.userSessionExpired);
- }
- throw e;
- }
+ }, "Error getting access token:");
}
async _refreshToken(forceRenew = false) {
@@ -59,15 +58,20 @@ class TokenManager {
const { refresh_token, scope } = token;
if (!refresh_token || !scope) return;
- await this.saveToken(
- await http.post(`${constants.AUTH_HOST}${ENDPOINTS.token}`, {
- refresh_token,
- grant_type: "refresh_token",
- scope: scope,
- client_id: "notesnook",
- })
- );
- EV.publish(EVENTS.tokenRefreshed);
+
+ 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:");
});
}
@@ -99,3 +103,15 @@ class TokenManager {
}
}
export default TokenManager;
+
+async function getSafeToken(action, errorMessage) {
+ try {
+ return await action();
+ } catch (e) {
+ console.error(errorMessage, e);
+ if (e.message === "invalid_grant" || e.message === "invalid_client") {
+ EV.publish(EVENTS.userSessionExpired);
+ }
+ throw e;
+ }
+}
diff --git a/packages/core/common.js b/packages/core/common.js
index 6b0314d6f..014bc6ad1 100644
--- a/packages/core/common.js
+++ b/packages/core/common.js
@@ -47,6 +47,7 @@ export const EVENTS = {
appRefreshRequested: "app:refreshRequested",
noteRemoved: "note:removed",
tokenRefreshed: "token:refreshed",
+ refreshToken: "token:refresh",
attachmentsLoading: "attachments:loading",
attachmentDeleted: "attachment:deleted",
mediaAttachmentDownloaded: "attachments:mediaDownloaded",
diff --git a/packages/core/utils/http.js b/packages/core/utils/http.js
index 228837d5a..86bf346f9 100644
--- a/packages/core/utils/http.js
+++ b/packages/core/utils/http.js
@@ -1,3 +1,5 @@
+import { EV, EVENTS } from "../common";
+
function get(url, token) {
return request(url, token, "GET");
}
@@ -42,6 +44,11 @@ function transformer(data, type) {
}
}
+/**
+ *
+ * @param {Response} response
+ * @returns
+ */
async function handleResponse(response) {
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
@@ -54,7 +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
+ else if (response.status === 401) {
+ EV.publish(EVENTS.refreshToken, response.url);
+ throw new Error("Unauthorized.");
+ } else
throw new Error(
`Request failed with status code: ${response.status} ${response.statusText}.`
);