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
|
|
|
|