62 lines
1.8 KiB
PHP
62 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace Ulmus\User\Authorize\Header;
|
|
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Ulmus\User\Authorize\Bearer\JsonWebTokenDecoder;
|
|
use Ulmus\User\Entity\UserInterface;
|
|
use Ulmus\User\Lib\Authenticate;
|
|
use Ulmus\User\Lib\AuthenticationMethodEnum;
|
|
|
|
class BearerMethod implements MethodInterface
|
|
{
|
|
protected JsonWebTokenDecoder $jwt;
|
|
|
|
public function __construct(
|
|
protected string $token
|
|
) {}
|
|
|
|
public function execute(ServerRequestInterface $request) : ServerRequestInterface
|
|
{
|
|
switch($this->autodetectTokenType()) {
|
|
case BearerTokenTypeEnum::JsonWebToken:
|
|
$this->jwt->decode();
|
|
|
|
$payload = $this->jwt->getPayload();
|
|
|
|
if ( $payload['sub'] ?? false) {
|
|
$request = $request
|
|
->withAttribute('authentication_middleware:method', AuthenticationMethodEnum::ForceLogin)
|
|
->withAttribute('authentication_middleware:jwt', $payload)
|
|
->withAttribute('authentication_middleware:user_id', $payload['sub']);
|
|
}
|
|
else {
|
|
throw new \InvalidArgumentException("Given JsonWebToken is missing a 'sub' key (which match with a user's id)");
|
|
}
|
|
|
|
break;
|
|
|
|
case BearerTokenTypeEnum::UniqueKey:
|
|
# @TODO
|
|
break;
|
|
|
|
default:
|
|
}
|
|
|
|
return $request;
|
|
}
|
|
|
|
public function autodetectTokenType() : BearerTokenTypeEnum
|
|
{
|
|
try {
|
|
$this->jwt = new JsonWebTokenDecoder($this->token, hash('sha512', getenv('LEAN_RANDOM')));
|
|
|
|
if ( $this->jwt->isJWT() ) {
|
|
return BearerTokenTypeEnum::JsonWebToken;
|
|
}
|
|
}
|
|
catch(\Throwable $ex) {/* Not a JWT */}
|
|
|
|
return BearerTokenTypeEnum::UniqueKey;
|
|
}
|
|
} |