From 58633313e106f93e4c5a0d4fb443ba88f6c16649 Mon Sep 17 00:00:00 2001 From: Yasen Pramatarov Date: Sun, 23 Feb 2025 18:03:19 +0200 Subject: [PATCH] Fixes user tests --- app/classes/user.php | 54 ++++++++++++++++++++------------------------ 1 file changed, 25 insertions(+), 29 deletions(-) diff --git a/app/classes/user.php b/app/classes/user.php index f0a9628..2e29159 100644 --- a/app/classes/user.php +++ b/app/classes/user.php @@ -90,38 +90,34 @@ class User { * @return bool True if login is successful, false otherwise. */ public function login($username, $password) { - try { - // Get user's IP address - require_once __DIR__ . '/../helpers/logs.php'; - $ipAddress = getUserIP(); + // Get user's IP address + require_once __DIR__ . '/../helpers/logs.php'; + $ipAddress = getUserIP(); - // Record attempt - $this->rateLimiter->attempt($username, $ipAddress); + // Record attempt + $this->rateLimiter->attempt($username, $ipAddress); - // Check rate limiting first - if (!$this->rateLimiter->isAllowed($username, $ipAddress)) { - $remainingTime = $this->rateLimiter->getDecayMinutes(); - throw new Exception("Too many login attempts. Please try again in {$remainingTime} minutes."); - } - - // Then check credentials - $query = $this->db->prepare("SELECT * FROM users WHERE username = :username"); - $query->bindParam(':username', $username); - $query->execute(); - - $user = $query->fetch(PDO::FETCH_ASSOC); - if ($user && password_verify($password, $user['password'])) { - $_SESSION['user_id'] = $user['id']; - $_SESSION['username'] = $user['username']; - return true; - } - - // Get remaining attempts AFTER this failed attempt - $remainingAttempts = $this->rateLimiter->getRemainingAttempts($username, $ipAddress); - throw new Exception("Invalid credentials. {$remainingAttempts} attempts remaining."); - } catch (Exception $e) { - return $e->getMessage(); + // Check rate limiting first + if (!$this->rateLimiter->isAllowed($username, $ipAddress)) { + $remainingTime = $this->rateLimiter->getDecayMinutes(); + throw new Exception("Too many login attempts. Please try again in {$remainingTime} minutes."); } + + // Then check credentials + $query = $this->db->prepare("SELECT * FROM users WHERE username = :username"); + $query->bindParam(':username', $username); + $query->execute(); + + $user = $query->fetch(PDO::FETCH_ASSOC); + if ($user && password_verify($password, $user['password'])) { + $_SESSION['user_id'] = $user['id']; + $_SESSION['username'] = $user['username']; + return true; + } + + // Get remaining attempts AFTER this failed attempt + $remainingAttempts = $this->rateLimiter->getRemainingAttempts($username, $ipAddress); + throw new Exception("Invalid credentials. {$remainingAttempts} attempts remaining."); }