From 646b3a69fe24564ca736da45730c96c04488f371 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Mon, 31 Oct 2022 17:08:35 +0000 Subject: [PATCH] Fix authedRequest including `Authorization: Bearer undefined` for password resets (#2822) --- spec/unit/http-api/fetch.spec.ts | 10 ++++++++++ src/client.ts | 2 +- src/http-api/fetch.ts | 24 +++++++++++++----------- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/spec/unit/http-api/fetch.spec.ts b/spec/unit/http-api/fetch.spec.ts index e100f2d93..1af230211 100644 --- a/spec/unit/http-api/fetch.spec.ts +++ b/spec/unit/http-api/fetch.spec.ts @@ -220,4 +220,14 @@ describe("FetchHttpApi", () => { expect(api.authedRequest(Method.Get, "/path")).rejects.toThrow("Ye shall ask for consent"), ]); }); + + describe("authedRequest", () => { + it("should not include token if unset", () => { + const fetchFn = jest.fn(); + const emitter = new TypedEventEmitter(); + const api = new FetchHttpApi(emitter, { baseUrl, prefix, fetchFn }); + api.authedRequest(Method.Post, "/account/password"); + expect(fetchFn.mock.calls[0][1].headers.Authorization).toBeUndefined(); + }); + }); }); diff --git a/src/client.ts b/src/client.ts index 7652845d9..753b0a6f6 100644 --- a/src/client.ts +++ b/src/client.ts @@ -8087,7 +8087,7 @@ export class MatrixClient extends TypedEventEmitter { diff --git a/src/http-api/fetch.ts b/src/http-api/fetch.ts index bce1fbd96..35698bb62 100644 --- a/src/http-api/fetch.ts +++ b/src/http-api/fetch.ts @@ -143,18 +143,20 @@ export class FetchHttpApi { ): Promise> { if (!queryParams) queryParams = {}; - if (this.opts.useAuthorizationHeader) { - if (!opts.headers) { - opts.headers = {}; + if (this.opts.accessToken) { + if (this.opts.useAuthorizationHeader) { + if (!opts.headers) { + opts.headers = {}; + } + if (!opts.headers.Authorization) { + opts.headers.Authorization = "Bearer " + this.opts.accessToken; + } + if (queryParams.access_token) { + delete queryParams.access_token; + } + } else if (!queryParams.access_token) { + queryParams.access_token = this.opts.accessToken; } - if (!opts.headers.Authorization) { - opts.headers.Authorization = "Bearer " + this.opts.accessToken; - } - if (queryParams.access_token) { - delete queryParams.access_token; - } - } else if (!queryParams.access_token) { - queryParams.access_token = this.opts.accessToken; } const requestPromise = this.request(method, path, queryParams, body, opts);