From dca6fb6b816881ed1f7a4d8b4618f8b635c6dbf7 Mon Sep 17 00:00:00 2001 From: Travis Ralston Date: Sat, 16 Dec 2017 20:04:32 -0700 Subject: [PATCH] Attempt to re-register for a scalar token if ours is invalid This mostly helps with people migrating between integration managers where their old scalar token may no longer be valid. This also solves the problem of people switching between scalar and scalar-staging in the wild. Signed-off-by: Travis Ralston --- src/ScalarAuthClient.js | 50 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/src/ScalarAuthClient.js b/src/ScalarAuthClient.js index 3e775a94ab..0d67a08eac 100644 --- a/src/ScalarAuthClient.js +++ b/src/ScalarAuthClient.js @@ -38,11 +38,53 @@ class ScalarAuthClient { // Returns a scalar_token string getScalarToken() { - const tok = window.localStorage.getItem("mx_scalar_token"); - if (tok) return Promise.resolve(tok); + const token = window.localStorage.getItem("mx_scalar_token"); - // No saved token, so do the dance to get one. First, we - // need an openid bearer token from the HS. + if (!token) { + return this.registerForToken(); + } else { + return this.validateToken(token).then(userId => { + const me = MatrixClientPeg.get().getUserId(); + if (userId !== me) { + throw new Error("Scalar token is owned by someone else: " + me); + } + return token; + }).catch(err => { + console.error(err); + + // Something went wrong - try to get a new token. + console.warn("Registering for new scalar token"); + return this.registerForToken(); + }) + } + } + + validateToken(token) { + let url = SdkConfig.get().integrations_rest_url + "/account"; + + const defer = Promise.defer(); + request({ + method: "GET", + uri: url, + qs: {scalar_token: token}, + json: true, + }, (err, response, body) => { + if (err) { + defer.reject(err); + } else if (response.statusCode / 100 !== 2) { + defer.reject({statusCode: response.statusCode}); + } else if (!body || !body.user_id) { + defer.reject(new Error("Missing user_id in response")); + } else { + defer.resolve(body.user_id); + } + }); + + return defer.promise; + } + + registerForToken() { + // Get openid bearer token from the HS as the first part of our dance return MatrixClientPeg.get().getOpenIdToken().then((token_object) => { // Now we can send that to scalar and exchange it for a scalar token return this.exchangeForScalarToken(token_object);