From 18c4ece87ab6abb4b1b045d09e750fd59590acbe Mon Sep 17 00:00:00 2001 From: "J. Ryan Stinnett" Date: Mon, 29 Jul 2019 14:41:57 +0100 Subject: [PATCH] Improve error handling for IS auth --- src/IdentityAuthClient.js | 41 ++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/src/IdentityAuthClient.js b/src/IdentityAuthClient.js index 94109ff265..f3ec400148 100644 --- a/src/IdentityAuthClient.js +++ b/src/IdentityAuthClient.js @@ -19,6 +19,7 @@ import MatrixClientPeg from './MatrixClientPeg'; export default class IdentityAuthClient { constructor() { this.accessToken = null; + this.authEnabled = true; } hasCredentials() { @@ -27,34 +28,52 @@ export default class IdentityAuthClient { // Returns a promise that resolves to the access_token string from the IS async getAccessToken() { + if (!this.authEnabled) { + // The current IS doesn't support authentication + return null; + } + let token = this.accessToken; if (!token) { token = window.localStorage.getItem("mx_is_access_token"); } if (!token) { - return this.registerForToken(); + token = await this.registerForToken(); + this.accessToken = token; + window.localStorage.setItem("mx_is_access_token", token); } try { - return await this._checkToken(token); + await this._checkToken(token); } catch (e) { - return await this.registerForToken(); + // Retry in case token expired + token = await this.registerForToken(); + this.accessToken = token; + window.localStorage.setItem("mx_is_access_token", token); } + + return token; } _checkToken(token) { // TODO: Test current API token via /account endpoint - return token; } async registerForToken() { - const hsOpenIdToken = await MatrixClientPeg.get().getOpenIdToken(); - const { access_token: isAccessToken } = - await MatrixClientPeg.get().registerWithIdentityServer(hsOpenIdToken); - await this._checkToken(isAccessToken); - this.accessToken = isAccessToken; - window.localStorage.setItem("mx_is_access_token", isAccessToken); - return isAccessToken; + try { + const hsOpenIdToken = await MatrixClientPeg.get().getOpenIdToken(); + const { access_token: isAccessToken } = + await MatrixClientPeg.get().registerWithIdentityServer(hsOpenIdToken); + await this._checkToken(isAccessToken); + return isAccessToken; + } catch (err) { + if (err.cors === "rejected" || err.httpStatus === 404) { + // Assume IS only supports deprecated v1 API for now + // TODO: Remove this path once v2 is only supported version + console.warn("IS doesn't support v2 auth"); + this.authEnabled = false; + } + } } }