10 Commits
Author SHA1 Message Date
mcndave 1e1d6e1ce3 Merge branch 'v2.x'
# Conflicts:
#	src/Lib/Authenticate.php
#	src/Middleware/HeaderAuthenticationMiddleware.php
#	src/Middleware/PostRequestAuthenticationMiddleware.php
2026-10-20 08:21:12 -04:00
Dave Mc Nicoll 6a24bcad76 - Added a new CookieAuthentication middleware 2026-10-20 11:57:30 +00:00
mcndave 8d648e88c8 - WIP on package manager 2026-07-16 14:13:22 -04:00
mcndave 61db8fcc95 Merge branch 'master' of https://git.mcnd.ca/mcndave/ulmus-user 2026-07-16 13:28:36 -04:00
mcndave 6ddf358f41 - Added Ulmus version dependencies 2026-07-16 13:28:17 -04:00
mcndave 33ff1b5b8c - User now has a reverse fullname parameter
- forgetMe() defined as void
2026-07-14 16:49:44 -04:00
mcndave 142509e9f6 Merge branch 'master' of https://git.mcnd.ca/mcndave/ulmus-user 2026-07-01 14:29:54 -04:00
mcndave 45546fbcc0 - WIP on securing PostRequestAuth and began adding some LAN auth also 2026-07-01 14:29:45 -04:00
Dave Mc Nicoll 2e7b46eae6 - Fixed some mistyped variables 2026-06-17 20:59:55 +00:00
Dave Mc Nicoll 0eaaf79ad8 - WIP on v2.x authentication 2026-02-25 20:10:09 +00:00
13 changed files with 243 additions and 50 deletions

No files matched your search

+3 -3
View File
@@ -10,12 +10,12 @@
}
],
"require": {
"mcnd/ulmus": "dev-master"
"mcnd/ulmus": "^1.0 || ^2.0"
},
"repositories": [
{
"type": "vcs",
"url": "https://git.mcnd.ca/mcNdave/ulmus.git"
"type": "composer",
"url": "https://git.mcnd.ca/api/packages/mcndave/composer"
}
],
"autoload": {
+4 -4
View File
@@ -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
@@ -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)
);
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Ulmus\User\Authorize;
use DI\Attribute\Inject;
use Psr\Http\Message\ServerRequestInterface;
use Storage\Cookie;
use Ulmus\User\Lib\Authenticate;
use Ulmus\User\Lib\HeaderAuthenticationTypeEnum;
class CookieAuthentication implements AuthorizeMethodInterface
{
public function __construct(
protected Authenticate $authorize,
protected Cookie $cookie,
) { }
public function connect(ServerRequestInterface $request): ServerRequestInterface
{
$methodObj = new Header\BearerMethod($this->cookie->get('jwt'));
if (isset($methodObj)) {
$request = $methodObj->execute($request);
}
return $request;
}
public function catchRequest(ServerRequestInterface $request) : bool
{
return $this->cookie->has('jwt');
}
}
+16 -9
View File
@@ -6,30 +6,32 @@ 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 Authenticate $authorize,
# protected UserInterface $user,
protected string $token
) {}
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) {
$request = $request->withAttribute('authentication_middleware:user_id', $payload['sub']);
$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;
@@ -37,6 +39,8 @@ class BearerMethod implements MethodInterface
case BearerTokenTypeEnum::UniqueKey:
# @TODO
break;
default:
}
return $request;
@@ -44,11 +48,14 @@ class BearerMethod implements MethodInterface
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;
}
+1 -1
View File
@@ -62,7 +62,7 @@ class HeaderAuthentication implements AuthorizeMethodInterface
}
}
}*/
return $request->hasHeader('authorization');
}
}
@@ -0,0 +1,55 @@
<?php
namespace Ulmus\User\Authorize;
use Psr\Http\Message\ServerRequestInterface;
use Ulmus\User\Entity\UserInterface;
use Ulmus\User\Lib\Authenticate;
class MacAddressAuthentication implements AuthorizeMethodInterface
{
public function __construct(
public Authenticate $authenticate,
protected string $fieldUser = "mac",
) {}
public function connect(ServerRequestInterface $request, UserInterface $user): bool
{
$server = $request->getServerParams();
# var_dump($server, $this->getArpMacAddress($server['REMOTE_ADDR']));die();
return false;
return $this->authenticate->authenticate([ $this->fieldUser => $post[$this->postFieldUser] ], $post[$this->postFieldPassword]);
}
public function catchRequest(ServerRequestInterface $request): bool
{
return true;
$post = $request->getParsedBody();
return strtoupper( $request->getMethod() ) === "POST" && isset($post[$this->postFieldUser], $post[$this->postFieldPassword]);
}
protected function getArpMacAddress(string $ip) : ?string
{
#run the external command, break output into lines
$arp = shell_exec(sprintf("arp -a %s", escapeshellarg($ip)));
$lines = explode("\n", $arp);
#look for the output line describing our IP address
foreach($lines as $line)
{
$cols = preg_split('/\s+/', trim($line));
if ($cols[0] === $ip)
{
return $cols[0];
}
}
return false;
}
}
+9 -5
View File
@@ -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
@@ -80,9 +80,13 @@ abstract class User implements UserInterface {
return password_verify($password, $this->password ?? null);
}
public function fullName() : string
public function fullname(bool $reverse = false) : string
{
return trim( ( $this->firstName ?? "" ) . " " . ( $this->lastName ?? "" ) );
if (! $this->isLoaded() ) {
return "???";
}
return trim($reverse ? "{$this->lastName}, {$this->firstName}" : "{$this->firstName} {$this->lastName}");
}
public function loggedIn(?bool $set = null): bool
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Ulmus\User\Exception;
class InvalidUserException extends \Exception {}
+21 -9
View File
@@ -37,7 +37,8 @@ class Authenticate {
return null;
}
public function forgetMe() {
public function forgetMe() : void
{
$this->cookie->delete("user.id");
$this->session->destroy();
}
@@ -104,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");
}
}
@@ -140,14 +141,25 @@ class Authenticate {
return $this->user;
}
public function logUser(?int $id) : ? UserInterface
public function logUser(null|int|object $id) : ? UserInterface
{
if ( null !== $this->loadUser($id) ) {
$this->user->loggedIn(true);
return $this->user;
if (! is_object($id)) {
try {
if ($id === null || null === ($entity = $this->user::repository()->loadFromPk($id))) {
return null;
}
} catch (\Exception $ex) {
return null;
}
}
else {
$entity = $id;
}
return null;
$this->user->fromArray($entity);
$this->user->loggedIn(true);
return $this->user;
}
}
+25 -18
View File
@@ -10,6 +10,7 @@ use Psr\Http\{
};
use Ulmus\User\Entity\UserInterface;
use Ulmus\User\Authorize\PostRequestAuthentication;
use Ulmus\User\Exception\InvalidUserException;
use Ulmus\User\Lib\Authenticate;
use Ulmus\User\Lib\AuthenticationMethodEnum;
@@ -23,28 +24,34 @@ class AuthenticationMiddleware implements MiddlewareInterface
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
try {
if (null !== $id = $request->getAttribute('authentication_middleware:user_id')) {
$this->authenticator->loadUser($id);
if ( ! $this->authenticator->user->isLoaded() ) {
throw new \Exception("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;
}
$this->launchAuthentication($request);
}
catch(\Exception $e) {
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;
}
}
}
@@ -0,0 +1,30 @@
<?php
namespace Ulmus\User\Middleware;
use DI\Attribute\Inject;
use Psr\Http\{
Message\ResponseInterface,
Message\ServerRequestInterface,
Server\MiddlewareInterface,
Server\RequestHandlerInterface
};
use Ulmus\User\Authorize\CookieAuthentication;
class CookieAuthenticationMiddleware implements MiddlewareInterface
{
public function __construct(
#[Inject]
protected CookieAuthentication $authenticator,
) { }
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ( $this->authenticator->catchRequest($request) ) {
$request = $this->authenticator->connect($request);
}
return $handler->handle($request);
}
}
@@ -0,0 +1,40 @@
<?php
namespace Ulmus\User\Middleware;
use Psr\Http\{
Message\ResponseInterface,
Message\ServerRequestInterface,
Server\MiddlewareInterface,
Server\RequestHandlerInterface
};
use Ulmus\User\Authorize\MacAddressAuthentication;
use Ulmus\User\Entity\UserInterface;
use Ulmus\User\Authorize\PostRequestAuthentication;
use Ulmus\User\Lib\Authenticate;
class LocalMacAddressMiddleware implements MiddlewareInterface
{
protected MacAddressAuthentication $authenticator;
public function __construct(
protected UserInterface $entity,
protected \Closure $loginFailedResponse,
? MacAddressAuthentication $authenticator = null,
) {
$this->authenticator = $authenticator ?: new MacAddressAuthentication(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) ) {
return call_user_func($this->loginFailedResponse, "Login failed");
}
}
return $handler->handle($request);
}
}