diff --git a/src/Authorize/AuthorizeMethodInterface.php b/src/Authorize/AuthorizeMethodInterface.php index f3ddc56..f1a3392 100644 --- a/src/Authorize/AuthorizeMethodInterface.php +++ b/src/Authorize/AuthorizeMethodInterface.php @@ -7,7 +7,7 @@ use Ulmus\User\Entity\UserInterface; interface AuthorizeMethodInterface { - public function connect(ServerRequestInterface $request, UserInterface $user) : bool; + public function connect(ServerRequestInterface $request) : ServerRequestInterface; public function catchRequest(ServerRequestInterface $request) : bool; } \ No newline at end of file diff --git a/src/Authorize/Bearer/JsonWebTokenDecoder.php b/src/Authorize/Bearer/JsonWebTokenDecoder.php index 039896b..5604684 100644 --- a/src/Authorize/Bearer/JsonWebTokenDecoder.php +++ b/src/Authorize/Bearer/JsonWebTokenDecoder.php @@ -70,11 +70,11 @@ class JsonWebTokenDecoder public function isJWT() : bool { try { - return $this->parse(); + return strlen($this->encoded) > 23 && count(explode('.', $this->encoded)) === 3; + } + catch(\Throwable $t) { + return false; } - catch(\Throwable $t) {} - - return false; } public function getPayload() : array diff --git a/src/Authorize/Bearer/JsonWebTokenValidate.php b/src/Authorize/Bearer/JsonWebTokenValidate.php index 0fb2c7c..25a1bba 100644 --- a/src/Authorize/Bearer/JsonWebTokenValidate.php +++ b/src/Authorize/Bearer/JsonWebTokenValidate.php @@ -53,7 +53,7 @@ abstract class JsonWebTokenValidate if ( ($compare ?? null) !== $decodedSignature) { throw new JsonWebTokenDecodingError( - sprintf("Given signature (%s) do not match computed signature (%s)", $encodedSignature, JsonWebTokenEncoder::base64url_encode($compare)) + sprintf("Given signature (%s) do not match computed signature", $encodedSignature) ); } } diff --git a/src/Authorize/CookieAuthentication.php b/src/Authorize/CookieAuthentication.php new file mode 100644 index 0000000..24952f2 --- /dev/null +++ b/src/Authorize/CookieAuthentication.php @@ -0,0 +1,33 @@ +cookie->get('jwt')); + + if (isset($methodObj)) { + $request = $methodObj->execute($request); + } + + return $request; + } + + public function catchRequest(ServerRequestInterface $request) : bool + { + return $this->cookie->has('jwt'); + } +} \ No newline at end of file diff --git a/src/Authorize/Header/BasicMethod.php b/src/Authorize/Header/BasicMethod.php index 4cd06bd..ecdbbb1 100644 --- a/src/Authorize/Header/BasicMethod.php +++ b/src/Authorize/Header/BasicMethod.php @@ -3,37 +3,31 @@ namespace Ulmus\User\Authorize\Header; use Psr\Http\Message\ServerRequestInterface; -use Ulmus\User\Entity\BasicAuthUserInterface; -use Ulmus\User\Entity\UserInterface; -use Ulmus\User\Lib\Authenticate; -use Ulmus\User\Lib\Authorize; +use Ulmus\User\Lib\AuthenticationMethodEnum; class BasicMethod implements MethodInterface { public function __construct( - protected Authenticate $authorize, - protected BasicAuthUserInterface $user, protected string|array $arguments ) {} - public function execute(ServerRequestInterface $request) : bool + public function execute(ServerRequestInterface $request) : ServerRequestInterface { if ( false === $decoded = base64_decode($this->arguments) ) { throw new \RuntimeException("Base64 decoding of given username:password failed"); } - list($userName, $password) = explode(':', $decoded) + [ null, null ]; + list($username, $password) = explode(':', $decoded) + [ null, null ]; - if ( empty($userName) ) { + if ( empty($username) ) { throw new \RuntimeException("A username must be provided"); } elseif ( empty($password) ) { throw new \RuntimeException("A password must be provided"); } - $this->authorize->user = $this->user; - $this->authorize->authenticate([ $this->user->usernameField() => $userName ], $password); - - return $this->user->loggedIn(); + return $request->withAttribute('authentication_middleware:method', AuthenticationMethodEnum::UsernamePassword) + ->withAttribute('authentication_middleware:username', $username) + ->withAttribute('authentication_middleware:password', $password); } } \ No newline at end of file diff --git a/src/Authorize/Header/BearerMethod.php b/src/Authorize/Header/BearerMethod.php index 99d731f..004e053 100644 --- a/src/Authorize/Header/BearerMethod.php +++ b/src/Authorize/Header/BearerMethod.php @@ -3,37 +3,35 @@ namespace Ulmus\User\Authorize\Header; use Psr\Http\Message\ServerRequestInterface; -use Ulmus\User\Authorize\Bearer\JsonWebToken; use Ulmus\User\Authorize\Bearer\JsonWebTokenDecoder; use Ulmus\User\Entity\UserInterface; use Ulmus\User\Lib\Authenticate; -use Ulmus\User\Lib\Authorize; +use Ulmus\User\Lib\AuthenticationMethodEnum; class BearerMethod implements MethodInterface { protected JsonWebTokenDecoder $jwt; public function __construct( - protected Authenticate $authorize, - protected UserInterface $user, protected string $token ) {} - public function execute(ServerRequestInterface $request) : bool + public function execute(ServerRequestInterface $request) : ServerRequestInterface { - $this->authorize->user = $this->user; - switch($this->autodetectTokenType()) { case BearerTokenTypeEnum::JsonWebToken: + $this->jwt->decode(); + $payload = $this->jwt->getPayload(); - if ($payload['sub'] ?? false) { - if ( ! $this->authorize->logUser($payload['sub']) ) { - throw new \Exception("Given user id do not match with an existing/active user"); - } + 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 concords to user id)"); + throw new \InvalidArgumentException("Given JsonWebToken is missing a 'sub' key (which match with a user's id)"); } break; @@ -41,25 +39,24 @@ class BearerMethod implements MethodInterface case BearerTokenTypeEnum::UniqueKey: # @TODO break; + + default: } - - return $this->user->loggedIn(); + return $request; } public function autodetectTokenType() : BearerTokenTypeEnum { - $this->jwt = new JsonWebTokenDecoder($this->token, getenv('LEAN_RANDOM')); + try { + $this->jwt = new JsonWebTokenDecoder($this->token, hash('sha512', getenv('LEAN_RANDOM'))); - if ( $this->jwt->isJWT() ) { - return BearerTokenTypeEnum::JsonWebToken; + if ( $this->jwt->isJWT() ) { + return BearerTokenTypeEnum::JsonWebToken; + } } + catch(\Throwable $ex) {/* Not a JWT */} return BearerTokenTypeEnum::UniqueKey; } - - protected function userFromJWT() : UserInterface - { - - } } \ No newline at end of file diff --git a/src/Authorize/Header/DigestMethod.php b/src/Authorize/Header/DigestMethod.php index 1dfbd7c..ed2660d 100644 --- a/src/Authorize/Header/DigestMethod.php +++ b/src/Authorize/Header/DigestMethod.php @@ -9,12 +9,12 @@ use Ulmus\User\Lib\Authenticate; class DigestMethod implements MethodInterface { public function __construct( - protected Authenticate $authorize, - protected DigestAuthUserInterface $user, + # protected Authenticate $authorize, + # protected DigestAuthUserInterface $user, protected string|array $arguments ) {} - public function execute(ServerRequestInterface $request) : bool + public function execute(ServerRequestInterface $request) : ServerRequestInterface { $arguments = $this->parseDigestArguments($this->arguments); @@ -28,7 +28,7 @@ class DigestMethod implements MethodInterface $arguments['nc'] = str_pad($arguments['nc'] ?? "1", 8, '0', STR_PAD_LEFT); - $ha1 = $this->getSecretHash(); + $ha1 = "@TODO !@"; # $this->authorize->user->getSecretHash(); if ($isSess) { $ha1 = hash($hashMethod, implode(':', [ @@ -41,14 +41,14 @@ class DigestMethod implements MethodInterface $ha2 = hash($hashMethod, implode(':', [ strtoupper($request->getMethod()), $arguments['uri'], hash($hashMethod, $body ?? "") ])); - break; + break; case 'auth': default: $ha2 = hash($hashMethod, implode(':', [ strtoupper($request->getMethod()), $arguments['uri'] ])); - break; + break; } if (isset($arguments['qop'])) { @@ -62,7 +62,13 @@ class DigestMethod implements MethodInterface ])); } - return $response === $arguments['response']; + if ($response === $arguments['response']) { + $request = $request->withAttribute('authentication_middleware:user_id', $arguments['username']); + + # @TODO ! Add Type here to match login with Username Only + } + + return $request; } diff --git a/src/Authorize/Header/MethodInterface.php b/src/Authorize/Header/MethodInterface.php index 3f12ed1..eceac12 100644 --- a/src/Authorize/Header/MethodInterface.php +++ b/src/Authorize/Header/MethodInterface.php @@ -6,5 +6,5 @@ use Psr\Http\Message\ServerRequestInterface; interface MethodInterface { - public function execute(ServerRequestInterface $request) : bool; + public function execute(ServerRequestInterface $request) : ServerRequestInterface; } \ No newline at end of file diff --git a/src/Authorize/HeaderAuthentication.php b/src/Authorize/HeaderAuthentication.php index 749d0b0..74a14dd 100644 --- a/src/Authorize/HeaderAuthentication.php +++ b/src/Authorize/HeaderAuthentication.php @@ -6,6 +6,7 @@ use Psr\Http\Message\ServerRequestInterface; use Ulmus\User\Common\AuthorizeContentTypeEnum; use Ulmus\User\Entity\{ DigestAuthUserInterface, UserInterface }; use Ulmus\User\Lib\Authenticate; +use Ulmus\User\Lib\HeaderAuthenticationTypeEnum; class HeaderAuthentication implements AuthorizeMethodInterface { @@ -13,51 +14,55 @@ class HeaderAuthentication implements AuthorizeMethodInterface protected Authenticate $authorize, ) { } - public function connect(ServerRequestInterface $request, UserInterface $user): bool + public function connect(ServerRequestInterface $request): ServerRequestInterface { - if (null !== ( $auth = $request->getHeaderLine('Authorization') )) { - list($method, $value) = explode(' ', $auth, 2) + [ null, null ]; + $type = HeaderAuthenticationTypeEnum::fromRequest($request); - switch(strtolower($method)) { - case "basic": - $methodObj = new Header\BasicMethod($this->authorize, $user, $value); + if ( null !== $type ) { + list(, $value) = explode(' ', $request->getHeaderLine('Authorization'), 2) + [ null, null ]; + + switch($type) { + case HeaderAuthenticationTypeEnum::Basic: + $methodObj = new Header\BasicMethod($value); break; - case "digest": - if (! $user instanceof DigestAuthUserInterface) { - throw new \RuntimeException("Your user entity must provide a valid hash of `user:realm:password` "); - } + case HeaderAuthenticationTypeEnum::Digest: + #if (! $user instanceof DigestAuthUserInterface) { + # throw new \RuntimeException("Your user entity must provide a valid hash of `user:realm:password` "); + #} - $methodObj = new Header\DigestMethod($this->authorize, $user, $value); + $methodObj = new Header\DigestMethod($value); break; - case "bearer": - $methodObj = new Header\BearerMethod($this->authorize, $user, $value); + case HeaderAuthenticationTypeEnum::Bearer: + $methodObj = new Header\BearerMethod($value); break; - case "token": - + case HeaderAuthenticationTypeEnum::Token: + // @TODO ! break; - - default: - throw new \InvalidArgumentException("An authentication method must be provided"); } } - return isset($methodObj) && $methodObj->execute($request); - } + if (isset($methodObj)) { + $request = $methodObj->execute($request); + } + return $request; + } public function catchRequest(ServerRequestInterface $request) : bool { - foreach(array_merge($request->getHeader('Accept'), $request->getHeader('Content-Type')) as $accept) { + # Previously only catched from JSON content-type ; now accepts every connections + + /*foreach(array_merge($request->getHeader('Accept'), $request->getHeader('Content-Type')) as $accept) { foreach(explode(',', $accept) as $contentType) { if ( AuthorizeContentTypeEnum::tryFrom(strtolower($contentType)) ) { return true; } } - } - - return false; + }*/ + + return $request->hasHeader('authorization'); } } \ No newline at end of file diff --git a/src/Authorize/PostRequestAuthentication.php b/src/Authorize/PostRequestAuthentication.php index 4ef2747..44a063c 100644 --- a/src/Authorize/PostRequestAuthentication.php +++ b/src/Authorize/PostRequestAuthentication.php @@ -5,21 +5,23 @@ namespace Ulmus\User\Authorize; use Psr\Http\Message\ServerRequestInterface; use Ulmus\User\Entity\UserInterface; use Ulmus\User\Lib\Authenticate; +use Ulmus\User\Lib\AuthenticationMethodEnum; class PostRequestAuthentication implements AuthorizeMethodInterface { public function __construct( - public Authenticate $authenticate, protected string $fieldUser = "email", protected string $postFieldUser = "email", protected string $postFieldPassword = "password", ) {} - public function connect(ServerRequestInterface $request, UserInterface $user): bool + public function connect(ServerRequestInterface $request) : ServerRequestInterface { $post = $request->getParsedBody(); - return $this->authenticate->authenticate([ $this->fieldUser => $post[$this->postFieldUser] ], $post[$this->postFieldPassword]); + return $request->withAttribute('authentication_middleware:method', AuthenticationMethodEnum::UsernamePassword) + ->withAttribute('authentication_middleware:username', [ $this->fieldUser => $post[$this->postFieldUser] ]) + ->withAttribute('authentication_middleware:password', $post[$this->postFieldPassword]); } public function catchRequest(ServerRequestInterface $request): bool diff --git a/src/Entity/User.php b/src/Entity/User.php index defc934..d6f8253 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -48,12 +48,12 @@ abstract class User implements UserInterface { #[Field] public string $password; - #[Field\UpdatedAt(name: "updated_at", readonly: true)] - public ? Datetime $updatedAt; - #[Field\CreatedAt(name: "created_at", readonly: true)] public Datetime $createdAt; + #[Field\UpdatedAt(name: "updated_at", readonly: true)] + public ? Datetime $updatedAt; + public bool $logged = false; public function __toString() : string diff --git a/src/Exception/InvalidUserException.php b/src/Exception/InvalidUserException.php new file mode 100644 index 0000000..8472f59 --- /dev/null +++ b/src/Exception/InvalidUserException.php @@ -0,0 +1,5 @@ +session->destroy(); } - public function authenticate(array $userLogin, string $password) : bool + public function authenticate(string|array $userLogin, string $password) : bool { $repository = $this->user::repository(); + if (is_string($userLogin)) { + $userLogin = [ $this->user->usernameField() => $userLogin ]; + } + foreach($userLogin as $field => $value) { $repository->or($field, $value); } @@ -101,8 +105,8 @@ class Authenticate { $this->session->set("user.id", $this->user->id); } - if ( $this->cookie ) { - $this->cookie->set("user.id", $this->user->id); + if ( $this->cookie && ! $this->cookie->has('user.id')) { + $this->cookie->set("user.id", $this->user->id, samesite: "none"); } } @@ -121,6 +125,22 @@ class Authenticate { return $this; } + public function loadUser(?int $id) : ? UserInterface + { + try { + if ($id === null || null === ($entity = $this->user::repository()->loadFromPk($id))) { + return null; + } + } + catch(\Exception $ex) { + return null; + } + + $this->user->fromArray($entity); + + return $this->user; + } + public function logUser(null|int|object $id) : ? UserInterface { if (! is_object($id)) { diff --git a/src/Lib/AuthenticationMethodEnum.php b/src/Lib/AuthenticationMethodEnum.php new file mode 100644 index 0000000..afe3bfd --- /dev/null +++ b/src/Lib/AuthenticationMethodEnum.php @@ -0,0 +1,9 @@ +hasHeader('authorization')) { + list($method, ) = explode(' ', $request->getHeaderLine('authorization'), 2); + + return static::tryFrom(strtolower($method)); + } + + return null; + } +} \ No newline at end of file diff --git a/src/Middleware/AuthenticationMiddleware.php b/src/Middleware/AuthenticationMiddleware.php new file mode 100644 index 0000000..b5f146c --- /dev/null +++ b/src/Middleware/AuthenticationMiddleware.php @@ -0,0 +1,57 @@ +launchAuthentication($request); + } + catch(InvalidUserException $e) { + return call_user_func($this->loginFailedResponse, [ 'api.error_message' => $e->getMessage() ]); + } + + return $handler->handle($request); + } + + protected function launchAuthentication(ServerRequestInterface $request) : void + { + if (null !== $id = $request->getAttribute('authentication_middleware:user_id')) { + + $this->authenticator->loadUser($id); + + if ( ! $this->authenticator->user->isLoaded() ) { + throw new InvalidUserException("Given user id do not match with an existing/active user"); + } + } + + switch($request->getAttribute('authentication_middleware:method')) { + case AuthenticationMethodEnum::ForceLogin: + $this->authenticator->login(); + break; + + case AuthenticationMethodEnum::UsernamePassword: + $this->authenticator->authenticate($request->getAttribute('authentication_middleware:username'), $request->getAttribute('authentication_middleware:password')); + break; + } + } +} diff --git a/src/Middleware/CookieAuthenticationMiddleware.php b/src/Middleware/CookieAuthenticationMiddleware.php new file mode 100644 index 0000000..eeb974c --- /dev/null +++ b/src/Middleware/CookieAuthenticationMiddleware.php @@ -0,0 +1,30 @@ +authenticator->catchRequest($request) ) { + $request = $this->authenticator->connect($request); + } + + return $handler->handle($request); + } +} diff --git a/src/Middleware/HeaderAuthenticationMiddleware.php b/src/Middleware/HeaderAuthenticationMiddleware.php index 7c35d0f..b5d02d9 100644 --- a/src/Middleware/HeaderAuthenticationMiddleware.php +++ b/src/Middleware/HeaderAuthenticationMiddleware.php @@ -14,28 +14,14 @@ use Ulmus\User\Lib\Authenticate; class HeaderAuthenticationMiddleware implements MiddlewareInterface { - protected HeaderAuthentication $authenticator; - public function __construct( - protected Authenticate $authorize, - protected UserInterface $entity, - protected \Closure $loginFailedResponse, - ? HeaderAuthentication $authenticator = null, - ) { - $this->authenticator = $authenticator ?: new HeaderAuthentication($authorize); - } + protected HeaderAuthentication $authenticator, + ) { } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - try { - if ( $this->authenticator->catchRequest($request) ) { - if ( ! $this->authenticator->connect($request, $this->entity) ) { - return call_user_func($this->loginFailedResponse, [ 'api.process' => "Auth failed" ]); - } - } - } - catch(\Exception $e) { - return call_user_func($this->loginFailedResponse, [ 'api.error_message' => $e->getMessage() ]); + if ( $this->authenticator->catchRequest($request) ) { + $request = $this->authenticator->connect($request); } return $handler->handle($request); diff --git a/src/Middleware/PostRequestAuthenticationMiddleware.php b/src/Middleware/PostRequestAuthenticationMiddleware.php index 8168a24..3eae7d8 100644 --- a/src/Middleware/PostRequestAuthenticationMiddleware.php +++ b/src/Middleware/PostRequestAuthenticationMiddleware.php @@ -14,27 +14,15 @@ use Ulmus\User\Lib\Authenticate; class PostRequestAuthenticationMiddleware implements MiddlewareInterface { - protected PostRequestAuthentication $authenticator; - public function __construct( - protected UserInterface $entity, - protected \Closure $loginFailedResponse, - ? PostRequestAuthentication $authenticator = null, + protected PostRequestAuthentication $authenticator, ) { - $this->authenticator = $authenticator ?: new PostRequestAuthentication(new Authenticate($entity)); } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - $this->authenticator->authenticate->rememberMe(); - if ( $this->authenticator->catchRequest($request) ) { - if ( ! $this->authenticator->connect($request, $this->entity) ) { - # Adds random sleep after a bad login attempts - sleep(random_int(2,8)); - - return call_user_func($this->loginFailedResponse, "Login failed"); - } + $request = $this->authenticator->connect($request); } return $handler->handle($request);