Files
mercureact/src/Http/Middleware/SecurityMiddleware.php

73 lines
2.1 KiB
PHP
Raw Normal View History

2024-03-10 20:22:28 +01:00
<?php
namespace NoccyLabs\Mercureact\Http\Middleware;
use NoccyLabs\Mercureact\Configuration;
2024-03-10 23:06:00 +01:00
use NoccyLabs\Mercureact\Http\Exception\SecurityException;
2024-03-10 20:22:28 +01:00
use NoccyLabs\SimpleJWT\JWTToken;
use NoccyLabs\SimpleJWT\Key\JWTPlaintextKey;
2024-03-10 23:06:00 +01:00
use NoccyLabs\SimpleJWT\Validator\JWTValidator;
2024-03-10 20:22:28 +01:00
use Psr\Http\Message\ServerRequestInterface;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
class SecurityMiddleware
{
public function __construct(
private Configuration $config
)
{
}
/**
*
*
* @param ServerRequestInterface $request
* @param callable $next
* @return PromiseInterface
*/
public function __invoke(ServerRequestInterface $request, callable $next): PromiseInterface
{
return new Promise(
function (callable $resolve, callable $reject) use ($request, $next) {
// Check JWT in authorization header or authorization query param
$request = $this->checkAuthorization($request);
$resolve($next($request));
}
);
}
/**
2024-03-10 23:06:00 +01:00
* Check authorization and return a new request with added attributes:
2024-03-10 20:22:28 +01:00
*
2024-03-10 23:06:00 +01:00
* 'authorization' => JWTToken
2024-03-10 20:22:28 +01:00
*
* @param ServerRequestInterface $request
* @return ServerRequestInterface
*/
private function checkAuthorization(ServerRequestInterface $request): ServerRequestInterface
{
$authorization = $request->getHeaderLine('authorization');
if (str_starts_with(strtolower($authorization), "bearer ")) {
$jwt = substr($authorization, strpos($authorization, " ")+1);
$key = new JWTPlaintextKey($this->config->getJwtSecret());
$tok = new JWTToken($key, $jwt);
if (!$tok->isValid()) {
2024-03-10 23:06:00 +01:00
throw new SecurityException(
message: "Invalid token",
code: SecurityException::ERR_ACCESS_DENIED
);
2024-03-10 20:22:28 +01:00
}
return $request
->withAttribute('authorization', $tok);
} else {
return $request
->withAttribute('authorization', null);
}
}
}