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