Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
JwtValidator
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
2 / 2
5
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 run
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3namespace Dynart\Micro\Middleware;
4
5use Dynart\Micro\AuthorizationException;
6use Dynart\Micro\ConfigInterface;
7use Dynart\Micro\JwtAuthInterface;
8use Dynart\Micro\MiddlewareInterface;
9use Dynart\Micro\RequestInterface;
10use Firebase\JWT\JWT;
11use Firebase\JWT\Key;
12
13class JwtValidator implements MiddlewareInterface {
14
15    public function __construct(
16        private RequestInterface $request,
17        private JwtAuthInterface $jwtAuth,
18        private ConfigInterface $config
19    ) {}
20
21    public function run(): void {
22        $header = $this->request->header('Authorization');
23        if (!$header || !str_starts_with($header, 'Bearer ')) {
24            return;
25        }
26        $token = substr($header, 7);
27        $secret = $this->config->get('jwt.secret', '');
28        $algorithm = $this->config->get('jwt.algorithm', 'HS256');
29        try {
30            $payload = JWT::decode($token, new Key($secret, $algorithm));
31            $user = $this->jwtAuth->resolveUser($payload->sub, $payload);
32            $this->jwtAuth->setUser($user);
33        } catch (\Exception $e) {
34            throw new AuthorizationException(401);
35        }
36    }
37}