aboutsummaryrefslogtreecommitdiffhomepage
path: root/services/app/src/Middlewares/AdminRequiredMiddleware.php
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2024-01-17 02:11:31 +0900
committernsfisis <nsfisis@gmail.com>2024-01-17 02:11:31 +0900
commitdeacd0dfc195bca41af631114804d29937337cd8 (patch)
treef1f83580e5bc892c0794ac41632bc0cce3498f65 /services/app/src/Middlewares/AdminRequiredMiddleware.php
parent38ddeb28ec846ee966d0fe6873585d697a9ef373 (diff)
downloadphperkaigi-2024-albatross-deacd0dfc195bca41af631114804d29937337cd8.tar.gz
phperkaigi-2024-albatross-deacd0dfc195bca41af631114804d29937337cd8.tar.zst
phperkaigi-2024-albatross-deacd0dfc195bca41af631114804d29937337cd8.zip
.
Diffstat (limited to 'services/app/src/Middlewares/AdminRequiredMiddleware.php')
-rw-r--r--services/app/src/Middlewares/AdminRequiredMiddleware.php43
1 files changed, 43 insertions, 0 deletions
diff --git a/services/app/src/Middlewares/AdminRequiredMiddleware.php b/services/app/src/Middlewares/AdminRequiredMiddleware.php
new file mode 100644
index 0000000..dc81b42
--- /dev/null
+++ b/services/app/src/Middlewares/AdminRequiredMiddleware.php
@@ -0,0 +1,43 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Nsfisis\Albatross\Middlewares;
+
+use LogicException;
+use Nsfisis\Albatross\Models\User;
+use Psr\Http\Message\ResponseFactoryInterface;
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use Slim\App;
+
+final class AdminRequiredMiddleware implements MiddlewareInterface
+{
+ private function __construct(
+ private readonly ResponseFactoryInterface $responseFactory,
+ ) {
+ }
+
+ public static function create(App $app): self
+ {
+ return new self($app->getResponseFactory());
+ }
+
+ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
+ {
+ $current_user = $request->getAttribute('current_user');
+ if (!$current_user instanceof User) {
+ throw new LogicException('The route that has this middleware must have the CurrentUserMiddleware before this one');
+ }
+
+ if (!$current_user->is_admin) {
+ $response = $this->responseFactory->createResponse(403);
+ $response->getBody()->write('Forbidden');
+ return $response->withHeader('Content-Type', 'text/plain');
+ }
+
+ return $handler->handle($request);
+ }
+}