From 0ecb4cc89eef47a0a565df74555c57d3a302750c Mon Sep 17 00:00:00 2001 From: Jim O'Donnell Date: Fri, 26 May 2023 12:08:53 +0100 Subject: [PATCH] Improved Sugar client token refresh flow (#205) - Emit a 'refresh' event from `auth` for each new token. - Refactor `sugarClient.refreshToken()` to update the Sugar client token on `refresh` events. - Reconnect to Primus when the token changes, so that the Primus URL changes. --- lib/SugarClient/client.js | 10 ++++++---- lib/api-client.js | 2 -- lib/auth.js | 1 + lib/sugar.js | 12 ++++++------ 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/lib/SugarClient/client.js b/lib/SugarClient/client.js index ca952e8..1a2fb07 100644 --- a/lib/SugarClient/client.js +++ b/lib/SugarClient/client.js @@ -45,14 +45,16 @@ class SugarClient { return SugarClient.host; } - async refreshToken() { - const token = await auth.checkBearerToken(); - this.authToken = token; + async refreshToken(token) { + const tokenChanged = token !== this.authToken; + if (this.userId && tokenChanged) { + this.authToken = token; + this.connect(); + } } primusUrl(baseUrl) { if (this.userId && this.authToken) { - this.refreshToken() return baseUrl.query = `user_id=${ this.userId }&auth_token=${ this.authToken }`; } } diff --git a/lib/api-client.js b/lib/api-client.js index 6afd3d6..5d67f13 100644 --- a/lib/api-client.js +++ b/lib/api-client.js @@ -8,8 +8,6 @@ var apiClient = new JSONAPIClient(config.host + '/api', { params: config.params, beforeEveryRequest: function() { - var { sugarClient } = require('./sugar'); - sugarClient.refreshToken(); var auth = require('./auth'); return auth.checkBearerToken(); }, diff --git a/lib/auth.js b/lib/auth.js index 8754a5e..7522cf7 100644 --- a/lib/auth.js +++ b/lib/auth.js @@ -54,6 +54,7 @@ const authClient = new Model({ this._bearerTokenExpiration = Date.now() + (response.expires_in * 1000); this._refreshToken = response.refresh_token; + this.emit('refresh', this._bearerToken); return this._bearerToken; }, diff --git a/lib/sugar.js b/lib/sugar.js index c223d5b..615156c 100644 --- a/lib/sugar.js +++ b/lib/sugar.js @@ -15,13 +15,14 @@ if (typeof navigator !== 'undefined') { 'Accept': 'application/json', }, { beforeEveryRequest: function() { - return auth.checkBearerToken() - .then(function (token) { - sugarClient.authToken = token; - }); + return auth.checkBearerToken(); } }); + auth.listen('refresh', function (token) { + sugarClient.refreshToken(token); + }); + auth.listen('change', function() { auth.checkCurrent() .then(function(user) { @@ -29,8 +30,7 @@ if (typeof navigator !== 'undefined') { sugarClient.userId = user.id; auth.checkBearerToken() .then(function (token) { - sugarClient.authToken = token; - sugarClient.connect(); + sugarClient.refreshToken(token); }) if (process.env.NODE_ENV !== 'production') {