Test Setup Failed
Branch v0.30.0 (cce41f)
by Mauro
02:50
created

AuthMiddleware::checkToken()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4888
c 0
b 0
f 0
cc 5
nc 7
nop 1
1
<?php declare(strict_types=1);
2
3
namespace App\Middleware;
4
5
use App\Exception\AuthException;
6
use Psr\Http\Message\ResponseInterface;
7
use Slim\Http\Request;
8
use Slim\Http\Response;
9
use \Firebase\JWT\JWT;
10
11
class AuthMiddleware
12
{
13
    public function __invoke(Request $request, Response $response, $next): ResponseInterface
14
    {
15
        $jwtHeader = $request->getHeaderLine('Authorization');
16
        if (empty($jwtHeader) === true) {
17
            throw new AuthException('JWT Token required.', 400);
18
        }
19
        $jwt = explode('Bearer ', $jwtHeader);
20
        if (!isset($jwt[1])) {
21
            throw new AuthException('JWT Token invalid.', 400);
22
        }
23
        $decoded = $this->checkToken($jwt[1]);
24
        $object = $request->getParsedBody();
25
        $object['decoded'] = $decoded;
26
27
        return $next($request->withParsedBody($object), $response);
28
    }
29
30
    /**
31
     * @param string $token
32
     * @return mixed
33
     * @throws AuthException
34
     */
35
    public function checkToken(string $token)
36
    {
37
        try {
38
            $decoded = JWT::decode($token, getenv('SECRET_KEY'), ['HS256']);
39
            if (is_object($decoded) && isset($decoded->sub)) {
40
                return $decoded;
41
            }
42
            throw new AuthException('error: Forbidden, not authorized.', 403);
43
        } catch (\UnexpectedValueException $e) {
44
            throw new AuthException('error: Forbidden, not authorized.', 403);
45
        } catch (\DomainException $e) {
46
            throw new AuthException('error: Forbidden, not authorized.', 403);
47
        }
48
    }
49
}
50