From 974b98f0ac55c9d8d71710080af00b8b0f64e7ce Mon Sep 17 00:00:00 2001
From: wukko <me@wukko.me>
Date: Sat, 17 Aug 2024 00:59:59 +0600
Subject: [PATCH] api/core: fix & clean up auth middleware

---
 api/src/core/api.js | 58 +++++++++++++++++++++++----------------------
 1 file changed, 30 insertions(+), 28 deletions(-)

diff --git a/api/src/core/api.js b/api/src/core/api.js
index 396551eb..a1c2692a 100644
--- a/api/src/core/api.js
+++ b/api/src/core/api.js
@@ -99,39 +99,41 @@ export function runAPI(express, app, __dirname) {
     }));
 
     app.post('/', (req, res, next) => {
+        if (!env.turnstileSecret || !env.jwtSecret) {
+            return next();
+        }
+
         try {
-            if (env.turnstileSecret && env.jwtSecret) {
-                const authorization = req.header("Authorization");
-                if (!authorization) {
-                    return fail(res, "error.api.auth.jwt.missing");
-                }
-
-                if (!authorization.startsWith("Bearer ") || authorization.length > 256) {
-                    return fail(res, "error.api.auth.jwt.invalid");
-                }
-
-                const verifyJwt = jwt.verify(
-                    authorization.split("Bearer ", 2)[1]
-                );
-
-                if (!verifyJwt) {
-                    return fail(res, "error.api.auth.jwt.invalid");
-                }
-
-                if (!acceptRegex.test(req.header('Accept'))) {
-                    return fail(res, 'ErrorInvalidAcceptHeader');
-                }
-
-                if (!acceptRegex.test(req.header('Content-Type'))) {
-                    return fail(res, 'ErrorInvalidContentType');
-                }
-
-                req.authorized = true;
-                next();
+            const authorization = req.header("Authorization");
+            if (!authorization) {
+                return fail(res, "error.api.auth.jwt.missing");
             }
+
+            if (!authorization.startsWith("Bearer ") || authorization.length > 256) {
+                return fail(res, "error.api.auth.jwt.invalid");
+            }
+
+            const verifyJwt = jwt.verify(
+                authorization.split("Bearer ", 2)[1]
+            );
+
+            if (!verifyJwt) {
+                return fail(res, "error.api.auth.jwt.invalid");
+            }
+
+            if (!acceptRegex.test(req.header('Accept'))) {
+                return fail(res, 'ErrorInvalidAcceptHeader');
+            }
+
+            if (!acceptRegex.test(req.header('Content-Type'))) {
+                return fail(res, 'ErrorInvalidContentType');
+            }
+
+            req.authorized = true;
         } catch {
             return fail(res, "error.api.generic");
         }
+        next();
     });
 
     app.post('/', apiLimiter);