File size: 6,258 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
<?php

declare(strict_types=1);

namespace Presentation\Middlewares;

use DomainException;
use Easy\Container\Attributes\Inject;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
use InvalidArgumentException;
use Presentation\Cookies\UserCookie;
use Presentation\Jwt\UserJwt;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Shared\Infrastructure\CommandBus\Dispatcher;
use UnexpectedValueException;
use Shared\Infrastructure\CommandBus\Exception\NoHandlerFoundException;
use User\Application\Commands\ReadUserCommand;
use User\Domain\Entities\UserEntity;
use User\Domain\Exceptions\UserNotFoundException;
use User\Domain\ValueObjects\ApiKey;
use Workspace\Application\Commands\ReadWorkspaceCommand;
use Workspace\Domain\Entities\WorkspaceEntity;

class UserMiddleware implements MiddlewareInterface
{
    /**
     * @param Dispatcher $dispatcher 
     * @return void 
     */
    public function __construct(
        private Dispatcher $dispatcher,

        #[Inject('option.features.api.is_enabled')]
        private ?bool $isApiEnabled = null,

        #[Inject('option.features.admin_api.is_enabled')]
        private ?bool $isAdminApiEnabled = null,
    ) {
    }

    /**
     * @param ServerRequestInterface $request 
     * @param RequestHandlerInterface $handler 
     * @return ResponseInterface 
     * @throws InvalidArgumentException 
     * @throws UnexpectedValueException 
     * @throws NoHandlerFoundException 
     */
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $user = $this->getUser($request);
        $apiUser = $this->getApiUser($request);
        $workspace = $this->getWorkspace($request);

        $path = $request->getUri()->getPath();

        if ($apiUser) {
            if (str_starts_with($path, '/admin/api/')) {
                if ($this->isAdminApiEnabled) {
                    $user = $apiUser;
                }
            } elseif (str_starts_with($path, '/api/')) {
                if ($this->isApiEnabled) {
                    $user = $apiUser;
                }
            }
        }

        if ($user) {
            $request = $request->withAttribute(UserEntity::class, $user);
        }

        if ($workspace) {
            $request = $request->withAttribute(
                WorkspaceEntity::class,
                $workspace
            );
        }

        return $handler->handle($request);
    }

    private function getApiUser(ServerRequestInterface $request): ?UserEntity
    {
        $apiKey = $this->getTokenFromApiHeader($request);

        if (!$apiKey) {
            return null;
        }

        try {
            $cmd = new ReadUserCommand(new ApiKey($apiKey));

            /** @var UserEntity $user */
            $user = $this->dispatcher->dispatch($cmd);
        } catch (\Throwable $th) {
            return null;
        }

        return $user;
    }

    /**
     * @param ServerRequestInterface $request 
     * @return null|UserEntity 
     * @throws InvalidArgumentException 
     * @throws UnexpectedValueException 
     * @throws NoHandlerFoundException 
     */
    private function getUser(ServerRequestInterface $request): ?UserEntity
    {
        $token =
            $this->getTokenFromAuthorizationHeader($request)
            ?? $this->getTokenFromQueryParam($request)
            ?? $this->getTokenFromCookie($request);

        if (!$token) {
            return null;
        }

        try {
            $jwt = UserJwt::createFromJwtString($token);
        } catch (
            SignatureInvalidException
            | BeforeValidException
            | ExpiredException
            | DomainException $th
        ) {
            return null;
        }

        try {
            $cmd = new ReadUserCommand($jwt->getUuid());

            /** @var UserEntity $user */
            $user = $this->dispatcher->dispatch($cmd);
        } catch (UserNotFoundException $th) {
            return null;
        }

        return $user;
    }

    /**
     * @param ServerRequestInterface $request 
     * @return null|string 
     */
    private function getTokenFromAuthorizationHeader(
        ServerRequestInterface $request
    ): ?string {
        $header = $request->getHeaderLine('Authorization');

        if (!$header) {
            return null;
        }

        $token = null;

        // Check if header has Bearer token
        if (preg_match('/Bearer\s(\S+)/', $header, $matches)) {
            $token = $matches[1];
        }

        return $token;
    }

    private function getTokenFromApiHeader(
        ServerRequestInterface $request
    ): ?string {
        $header = $request->getHeaderLine('X-Api-Key');

        if (!$header) {
            return null;
        }

        return $header;
    }

    /**
     * @param ServerRequestInterface $request 
     * @return null|string 
     */
    private function getTokenFromQueryParam(
        ServerRequestInterface $request
    ): ?string {
        $params = $request->getQueryParams();

        return $params['jwt'] ?? null;
    }

    /**
     * @param ServerRequestInterface $request 
     * @return null|string 
     */
    private function getTokenFromCookie(
        ServerRequestInterface $request
    ): ?string {
        $path = $request->getUri()->getPath();

        if (
            str_starts_with($path, '/admin/api/') === false
            && str_starts_with($path, '/api/') === false
        ) {
            $cookie = UserCookie::createFromRequest($request);
            return $cookie ? $cookie->getValue() : null;
        }

        return null;
    }

    private function getWorkspace(ServerRequestInterface $req): ?WorkspaceEntity
    {
        $header = $req->getHeaderLine('X-Workspace-Id');

        if (!$header) {
            return null;
        }

        try {
            $cmd = new ReadWorkspaceCommand($header);
            return $this->dispatcher->dispatch($cmd);
        } catch (\Throwable $th) {
            // Do nothing here 
        }

        return null;
    }
}