Auth: Save user ID instead of username in auth session
This commit is contained in:
parent
70093b1376
commit
b890432e5b
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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
|
||||
*/
|
||||
|
|
|
|||
Loading…
Reference in New Issue