aboutsummaryrefslogtreecommitdiffhomepage
path: root/services/app/src/Middlewares/AdminRequiredMiddleware.php
blob: dc81b42484636ad1c5e6e6bb668fc834112125c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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);
    }
}