Skip to content

Commit

Permalink
Improved Sugar client token refresh flow (#205)
Browse files Browse the repository at this point in the history
- 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.
  • Loading branch information
eatyourgreens authored May 26, 2023
1 parent ea9de71 commit 0ecb4cc
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 12 deletions.
10 changes: 6 additions & 4 deletions lib/SugarClient/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }`;
}
}
Expand Down
2 changes: 0 additions & 2 deletions lib/api-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
},
Expand Down
1 change: 1 addition & 0 deletions lib/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
},

Expand Down
12 changes: 6 additions & 6 deletions lib/sugar.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,22 @@ 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) {
if (user) {
sugarClient.userId = user.id;
auth.checkBearerToken()
.then(function (token) {
sugarClient.authToken = token;
sugarClient.connect();
sugarClient.refreshToken(token);
})

if (process.env.NODE_ENV !== 'production') {
Expand Down

0 comments on commit 0ecb4cc

Please sign in to comment.