Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // 4o-mini-high
- /**
- * @file AuthService.php
- * @description Contains the core business logic for user authentication.
- * It handles database interactions, password verification, and
- * brute-force protection logic, independent of HTTP context.
- *
- * @version 1.0.0
- * @since 2025-07-25
- * @author Barrac0de
- */
- declare(strict_types=1);
- namespace App\Auth;
- use PDO;
- use RuntimeException;
- class AuthService
- {
- private PDO $pdo;
- private int $maxAttempts = 5;
- private int $lockDuration = 86400; // 24 hours in seconds
- public function __construct(PDO $pdo)
- {
- $this->pdo = $pdo;
- }
- /**
- * @param string $username
- * @param string $password
- * @return int The authenticated user's ID
- * @throws RuntimeException on invalid credentials or lockout
- */
- public function authenticate(string $username, string $password): int
- {
- $stmt = $this->pdo->prepare(
- 'SELECT id, password_hash, failed_login, last_failed_at
- FROM users
- WHERE username = :username
- LIMIT 1'
- );
- $stmt->execute([':username' => $username]);
- $user = $stmt->fetch(PDO::FETCH_ASSOC);
- if (!$user) {
- throw new RuntimeException('Invalid username or password.');
- }
- $failedLogin = (int)$user['failed_login'];
- $lastFailedAt = $user['last_failed_at']
- ? strtotime($user['last_failed_at'])
- : 0;
- $now = time();
- // lockout check
- if ($failedLogin >= $this->maxAttempts
- && ($now - $lastFailedAt) < $this->lockDuration
- ) {
- throw new RuntimeException('Account locked. Try again later.');
- }
- // password verify
- if (!password_verify($password, (string)$user['password_hash'])) {
- $update = $this->pdo->prepare(
- 'UPDATE users
- SET failed_login = failed_login + 1,
- last_failed_at = NOW()
- WHERE id = :id'
- );
- $update->execute([':id' => $user['id']]);
- throw new RuntimeException('Invalid username or password.');
- }
- // reset failure counter
- $reset = $this->pdo->prepare(
- 'UPDATE users
- SET failed_login = 0,
- last_failed_at = NULL
- WHERE id = :id'
- );
- $reset->execute([':id' => $user['id']]);
- return (int)$user['id'];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment