From 70831a3d5828ca90e8c423dc2a8a5979538d0fc5 Mon Sep 17 00:00:00 2001 From: Mcat12 Date: Sat, 29 Jun 2019 21:34:15 -0700 Subject: [PATCH] Auto-login the user if no password is required See pi-hole/api#173 for more details. This implementation refreshes the page if it was started in a logged out state and it is found that the API doesn't require authentication. It is explained in more detail in a code comment, but we should look into Redux to make this and many other things cleaner and more testable. Signed-off-by: Mcat12 --- src/index.tsx | 17 +++++++++++++++++ src/util/__tests__/api.test.tsx | 5 +++++ src/util/api.tsx | 4 ++++ 3 files changed, 26 insertions(+) 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"); };