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 {
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;
}
}
}
}