diff options
| author | nsfisis <nsfisis@gmail.com> | 2024-01-17 02:11:31 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2024-01-17 02:11:31 +0900 |
| commit | deacd0dfc195bca41af631114804d29937337cd8 (patch) | |
| tree | f1f83580e5bc892c0794ac41632bc0cce3498f65 /services/app/src/Middlewares/CurrentUserMiddleware.php | |
| parent | 38ddeb28ec846ee966d0fe6873585d697a9ef373 (diff) | |
| download | phperkaigi-2024-albatross-deacd0dfc195bca41af631114804d29937337cd8.tar.gz phperkaigi-2024-albatross-deacd0dfc195bca41af631114804d29937337cd8.tar.zst phperkaigi-2024-albatross-deacd0dfc195bca41af631114804d29937337cd8.zip | |
.
Diffstat (limited to 'services/app/src/Middlewares/CurrentUserMiddleware.php')
| -rw-r--r-- | services/app/src/Middlewares/CurrentUserMiddleware.php | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/services/app/src/Middlewares/CurrentUserMiddleware.php b/services/app/src/Middlewares/CurrentUserMiddleware.php new file mode 100644 index 0000000..a58a327 --- /dev/null +++ b/services/app/src/Middlewares/CurrentUserMiddleware.php @@ -0,0 +1,43 @@ +<?php + +declare(strict_types=1); + +namespace Nsfisis\Albatross\Middlewares; + +use Nsfisis\Albatross\Repositories\UserRepository; +use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Server\MiddlewareInterface; +use Psr\Http\Server\RequestHandlerInterface; + +final class CurrentUserMiddleware implements MiddlewareInterface +{ + public function __construct( + private UserRepository $userRepo, + ) { + } + + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + $request = $this->setCurrentUserAttribute($request); + return $handler->handle($request); + } + + private function setCurrentUserAttribute(ServerRequestInterface $request): ServerRequestInterface + { + if (session_status() !== PHP_SESSION_ACTIVE) { + return $request; + } + $user_id = $_SESSION['user_id'] ?? null; + if ($user_id === null) { + return $request; + } + assert(is_int($user_id) || (is_string($user_id) && is_numeric($user_id))); + $user_id = (int) $user_id; + $user = $this->userRepo->findById($user_id); + if ($user === null) { + return $request; + } + return $request->withAttribute('current_user', $user); + } +} |
