diff --git a/src/index.tsx b/src/index.tsx index fcb1712..17c09dc 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -26,6 +26,23 @@ import { getBasePath } from "./util/basePath"; // will set loggedIn to false if necessary api.loggedIn = document.cookie.includes("user_id="); +// Verify the loggedIn status with the server. If we thought we were logged out +// but the API does not require authentication, refresh the page so we start +// in logged-in mode. +// +// An alternative to refreshing the page is to provide the loggedIn status via +// React context or some other mechanism. With the current infrastructure of +// the web interface, it is very messy to use React context for this as +// `api.loggedIn` is used in a few hard to reach spots. We should look into +// Redux for a cleaner approach. +api.checkAuthStatus().then(() => { + if (!api.loggedIn) { + // No authentication is required for this API. Refresh the page so we start + // in logged-in mode + window.location.reload(); + } +}); + setupI18n(); ReactDOM.render( diff --git a/src/util/__tests__/api.test.tsx b/src/util/__tests__/api.test.tsx index cff6bd3..8c60ec8 100644 --- a/src/util/__tests__/api.test.tsx +++ b/src/util/__tests__/api.test.tsx @@ -65,6 +65,11 @@ describe("ApiClient", () => { }); }); + it("should call auth endpoint with no headers", async () => { + await expect(api.checkAuthStatus()).resolves.toEqual(getData); + expect(httpClient.get).toHaveBeenCalledWith("auth"); + }); + it("should call logout endpoint", async () => { await expect(api.logout()).resolves.toEqual(deleteData); expect(httpClient.delete).toHaveBeenCalledWith("auth"); diff --git a/src/util/api.tsx b/src/util/api.tsx index 0a20452..992f73c 100644 --- a/src/util/api.tsx +++ b/src/util/api.tsx @@ -23,6 +23,10 @@ export class ApiClient { }); }; + checkAuthStatus = (): Promise => { + return this.http.get("auth"); + }; + logout = (): Promise => { return this.http.delete("auth"); };