Improve error handling for IS auth

This commit is contained in:
J. Ryan Stinnett 2019-07-29 14:41:57 +01:00
parent 4d01d6a5b1
commit 18c4ece87a

View file

@ -19,6 +19,7 @@ import MatrixClientPeg from './MatrixClientPeg';
export default class IdentityAuthClient { export default class IdentityAuthClient {
constructor() { constructor() {
this.accessToken = null; this.accessToken = null;
this.authEnabled = true;
} }
hasCredentials() { hasCredentials() {
@ -27,34 +28,52 @@ export default class IdentityAuthClient {
// Returns a promise that resolves to the access_token string from the IS // Returns a promise that resolves to the access_token string from the IS
async getAccessToken() { async getAccessToken() {
if (!this.authEnabled) {
// The current IS doesn't support authentication
return null;
}
let token = this.accessToken; let token = this.accessToken;
if (!token) { if (!token) {
token = window.localStorage.getItem("mx_is_access_token"); token = window.localStorage.getItem("mx_is_access_token");
} }
if (!token) { if (!token) {
return this.registerForToken(); token = await this.registerForToken();
this.accessToken = token;
window.localStorage.setItem("mx_is_access_token", token);
} }
try { try {
return await this._checkToken(token); await this._checkToken(token);
} catch (e) { } 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) { _checkToken(token) {
// TODO: Test current API token via /account endpoint // TODO: Test current API token via /account endpoint
return token;
} }
async registerForToken() { async registerForToken() {
try {
const hsOpenIdToken = await MatrixClientPeg.get().getOpenIdToken(); const hsOpenIdToken = await MatrixClientPeg.get().getOpenIdToken();
const { access_token: isAccessToken } = const { access_token: isAccessToken } =
await MatrixClientPeg.get().registerWithIdentityServer(hsOpenIdToken); await MatrixClientPeg.get().registerWithIdentityServer(hsOpenIdToken);
await this._checkToken(isAccessToken); await this._checkToken(isAccessToken);
this.accessToken = isAccessToken;
window.localStorage.setItem("mx_is_access_token", isAccessToken);
return 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;
}
}
} }
} }