Auth: Save user ID instead of username in auth session

This commit is contained in:
Lexi / Zoe 2021-07-29 18:19:23 +02:00
parent 70093b1376
commit b890432e5b
Signed by: binaryDiv
GPG Key ID: F8D4956E224DA232
4 changed files with 22 additions and 7 deletions

View File

@ -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

View File

@ -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);
}
}

View File

@ -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);

View File

@ -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
*/