about summary refs log tree commit diff stats
path: root/classes/Handler/LoginHandler.php
diff options
context:
space:
mode:
authorfox <fox@fakecake.org>2026-06-21 14:51:01 +0300
committerfox <fox@fakecake.org>2026-06-21 14:51:01 +0300
commit8e569855249dda7a17402e5ae20044e8149d992e (patch)
tree6a6acc9a378e2402d048a02e47b5ab99dc5247e2 /classes/Handler/LoginHandler.php
parent23ca9695d1b38c7a27cf132d517a6ed6b19f607a (diff)
parent17296a2ef8fa2658dca471285bce40ee67469179 (diff)
downloadthe-epube-8e569855249dda7a17402e5ae20044e8149d992e.tar.gz
the-epube-8e569855249dda7a17402e5ae20044e8149d992e.tar.xz
Merge branch 'dev' into 'master'
rework login throttling to use database field check instead of APCu

See merge request git/the-epube!64
Diffstat (limited to 'classes/Handler/LoginHandler.php')
-rw-r--r--classes/Handler/LoginHandler.php77
1 files changed, 68 insertions, 9 deletions
diff --git a/classes/Handler/LoginHandler.php b/classes/Handler/LoginHandler.php
index e317054..7b6fabb 100644
--- a/classes/Handler/LoginHandler.php
+++ b/classes/Handler/LoginHandler.php
@@ -11,15 +11,61 @@ use Response;
 
 class LoginHandler implements RequestHandlerInterface
 {
-    /** @return array{result: string, user: string, csrf_token: string}|null */
-    private function doLocalLogin(string $username, string $password): ?array
+    const USER_NOT_FOUND = 1;
+    const USER_RATE_LIMITED = 2;
+    const USER_WRONG_PASSWORD = 3;
+    const USER_AUTH_SUCCESS = 4;
+
+    private function isRateLimited(object $user): bool
+    {
+        // Skip rate limiting during integration tests or schema is older than required
+        if (getenv('IS_INTEGRATION_TESTING') || Config::get_schema_version() < 3) {
+            return false;
+        }
+
+        $windowSeconds = 60;
+        $lastAttempt   = $user->last_auth_attempt;
+
+        if ($lastAttempt !== null && is_numeric($lastAttempt) && (int) $lastAttempt > 0) {
+            if ((time() - (int) $lastAttempt) < $windowSeconds) {
+
+                // Bump login attempt timestamp
+                $user->last_auth_attempt = time();
+                $user->save();
+
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * Record a failed authentication attempt for rate limiting purposes.
+     */
+    private function recordFailedAttempt(object $user): void
+    {
+        if (Config::get_schema_version() >= 3) {
+            $user->last_auth_attempt = time();
+            $user->save();
+        }
+    }
+
+    /** @return array{array{result: string, user: string, csrf_token: string}|null, int} */
+    private function doLocalLogin(string $username, string $password): array
     {
         $user = ORM::for_table('epube_users')
             ->where('username', $username)
             ->find_one();
 
         if (!$user) {
-            return null;
+            return [null, self::USER_NOT_FOUND];
+        }
+
+        // Check rate limit against the *previous* attempt before updating.
+        // This avoids blocking the first attempt in any window.
+        if ($this->isRateLimited($user)) {
+            return [null, self::USER_RATE_LIMITED];
         }
 
         // Verify password against stored hash (legacy or modern)
@@ -29,7 +75,8 @@ class LoginHandler implements RequestHandlerInterface
             : password_verify($password, $user->pass);
 
         if (!$valid) {
-            return null;
+            $this->recordFailedAttempt($user);
+            return [null, self::USER_WRONG_PASSWORD];
         }
 
         // Upgrade legacy hash to bcrypt
@@ -37,6 +84,12 @@ class LoginHandler implements RequestHandlerInterface
             $this->upgradePassword($user, $password);
         }
 
+        // Reset last login attempt on successful login
+        if (Config::get_schema_version() >= 3) {
+            $user->last_auth_attempt = 0;
+            $user->save();
+        }
+
         // Set up session
         if (session_status() != PHP_SESSION_ACTIVE) {
             session_start();
@@ -51,7 +104,7 @@ class LoginHandler implements RequestHandlerInterface
         setcookie("epube_csrf_token", $_SESSION["csrf_token"], time() + Config::get(Config::SESSION_LIFETIME),
             "/", "", Config::is_server_https());
 
-        return ["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]];
+        return [["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]], self::USER_AUTH_SUCCESS];
     }
 
     /**
@@ -183,12 +236,18 @@ class LoginHandler implements RequestHandlerInterface
                     ->withBody(json_encode(["error" => "Username and password are required."]));
             }
 
-            $result = $this->doLocalLogin($username, $password);
+            [$result, $status] = $this->doLocalLogin($username, $password);
 
             if (!$result) {
-                return (new Response())
-                    ->withStatus(401)
-                    ->withBody(json_encode(["error" => "Incorrect username or password."]));
+                if ($status === self::USER_RATE_LIMITED) {
+                    return (new Response())
+                        ->withStatus(429)
+                        ->withBody(json_encode(["error" => "Too many login attempts."]));
+                } else {
+                    return (new Response())
+                        ->withStatus(401)
+                        ->withBody(json_encode(["error" => "Incorrect username or password."]));
+                }
             }
 
             return (new Response())