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 <newtoncat12@yahoo.com>
This commit is contained in:
Mcat12
2019-06-29 21:34:15 -07:00
parent 20813863d3
commit 70831a3d58
3 changed files with 26 additions and 0 deletions
+17
View File
@@ -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(
+5
View File
@@ -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");
+4
View File
@@ -23,6 +23,10 @@ export class ApiClient {
});
};
checkAuthStatus = (): Promise<ApiSuccessResponse> => {
return this.http.get("auth");
};
logout = (): Promise<ApiSuccessResponse> => {
return this.http.delete("auth");
};