diff --git a/src/Auth/AuthMiddleware.php b/src/Auth/AuthMiddleware.php index 6738f6e..e32fd38 100644 --- a/src/Auth/AuthMiddleware.php +++ b/src/Auth/AuthMiddleware.php @@ -21,8 +21,7 @@ class AuthMiddleware implements MiddlewareInterface // TODO: Lots of stuff. Session middleware, auth handler class, etc... if ($uri->getPath() !== '/login') { // Check authorization via session - // TODO username or user ID? - if (empty($_SESSION['username'])) { + if (empty($_SESSION['user_id'])) { // Not logged in -> Redirect to /login $response = new Response(); return $response diff --git a/src/Common/UserHelper.php b/src/Common/UserHelper.php index e67f56b..9d65b55 100644 --- a/src/Common/UserHelper.php +++ b/src/Common/UserHelper.php @@ -19,15 +19,15 @@ class UserHelper public function isLoggedIn(): bool { - return !empty($_SESSION['username']); + return !empty($_SESSION['user_id']); } public function getCurrentUser(): AdminUser { - $username = $_SESSION['username'] ?? null; - if (empty($username)) { + $userId = $_SESSION['user_id'] ?? null; + if (empty($userId)) { throw new RuntimeException('Not logged in!'); } - return $this->adminUserRepository->getUserByName($username); + return $this->adminUserRepository->getUserById($userId); } } diff --git a/src/Frontend/Login/LoginController.php b/src/Frontend/Login/LoginController.php index 73899d9..c3695fb 100644 --- a/src/Frontend/Login/LoginController.php +++ b/src/Frontend/Login/LoginController.php @@ -66,7 +66,7 @@ class LoginController extends BaseController } // Set login session - $_SESSION['username'] = $user->getUsername(); + $_SESSION['user_id'] = $user->getId(); return $response ->withHeader('Location', '/') ->withStatus(303); diff --git a/src/Repositories/AdminUserRepository.php b/src/Repositories/AdminUserRepository.php index 31e2a41..84376f5 100644 --- a/src/Repositories/AdminUserRepository.php +++ b/src/Repositories/AdminUserRepository.php @@ -17,6 +17,22 @@ class AdminUserRepository $this->pdo = $pdo; } + /** + * @throws AdminUserNotFoundException + */ + public function getUserById(int $userId): AdminUser + { + $statement = $this->pdo->prepare('SELECT * FROM admin_users WHERE admin_id = :admin_id LIMIT 1'); + $statement->execute(['admin_id' => $userId]); + + if ($statement->rowCount() < 1) { + throw new AdminUserNotFoundException("Admin with ID '$userId' was not found."); + } + + $row = $statement->fetch(PDO::FETCH_ASSOC); + return AdminUser::createFromArray($row); + } + /** * @throws AdminUserNotFoundException */