From f39ab26ceafa26be27120b006a186e054ebbb795 Mon Sep 17 00:00:00 2001
From: Zef Hemel <zef@zef.me>
Date: Tue, 4 Jul 2023 16:53:39 +0200
Subject: [PATCH] Replace unauthorized status with a redirect

---
 common/spaces/http_space_primitives.ts | 14 +++++++-------
 server/http_server.ts                  |  9 +++------
 2 files changed, 10 insertions(+), 13 deletions(-)

diff --git a/common/spaces/http_space_primitives.ts b/common/spaces/http_space_primitives.ts
index 8673ca9..2b3bd62 100644
--- a/common/spaces/http_space_primitives.ts
+++ b/common/spaces/http_space_primitives.ts
@@ -21,13 +21,13 @@ export class HttpSpacePrimitives implements SpacePrimitives {
       options.headers = { ...options.headers, ...{ "X-Sync-Mode": "true" } };
     }
 
-    const result = await fetch(url, { ...options });
-    if (
-      this.getRealStatus(result) === 401
-    ) {
-      // Invalid credentials, reloading the browser should trigger authentication
-      console.log("Going to redirect after", url);
-      location.href = "/.auth?refer=" + location.pathname;
+    const result = await fetch(url, {
+      ...options,
+    });
+    if (result.redirected) {
+      // Got a redirect, we'll assume this is due to invalid credentials and redirecting to an auth page
+      console.log("Got a redirect via the API so will redirect to URL", url);
+      location.href = result.url;
       throw new Error("Invalid credentials");
     }
     return result;
diff --git a/server/http_server.ts b/server/http_server.ts
index af71600..194a99c 100644
--- a/server/http_server.ts
+++ b/server/http_server.ts
@@ -218,8 +218,7 @@ export class HttpServer {
           }
           return;
         } else {
-          response.status = 401;
-          response.body = "Unauthorized";
+          response.redirect("/.auth");
           return;
         }
       } else {
@@ -232,8 +231,7 @@ export class HttpServer {
         if (!excludedPaths.includes(request.url.pathname)) {
           const authCookie = await cookies.get("auth");
           if (!authCookie) {
-            response.status = 401;
-            response.body = "Unauthorized, please authenticate";
+            response.redirect("/.auth");
             return;
           }
           const [username, hashedPassword] = authCookie.split(":");
@@ -243,8 +241,7 @@ export class HttpServer {
               hashedPassword,
             )
           ) {
-            response.status = 401;
-            response.body = "Invalid username/password, please reauthenticate";
+            response.redirect("/.auth");
             return;
           }
         }