- WIP on user auth

This commit is contained in:
mcndave committed 2023-11-08 06:53:13 -05:00
1 parent 7769b1a1ca
commit 9ae3e2d6f9
6 files changed
+38 -37

No files matched your search

+20 -14
View File
@@ -5,35 +5,37 @@ namespace Ulmus\User\Lib;
use Storage\{Session, Cookie};
use \Closure;
use Ulmus\User\Entity\User;
use Ulmus\Exception;
use Ulmus\User\Entity\UserInterface;
class Authenticate {
protected bool $logged = false;
protected Closure $authenticationEvent;
public ? User $user = null;
public UserInterface $user;
public function __construct(
UserInterface $user,
protected ? Session $session = null,
protected ? Cookie $cookie = null,
? Closure $authenticationEvent = null
? Closure $authenticationEvent = null,
) {
$this->authenticationEvent = $authenticationEvent ?: fn(bool $authenticated, string $message, ? User $user, array $data = []) : ? bool => null;
$this->authenticationEvent = $authenticationEvent ?: fn(bool $authenticated, string $message, ? UserInterface $user, array $data = []) : ? bool => null;
$this->user = $user;
}
public function rememberMe(\Ulmus\Repository $repository) : ? User
public function rememberMe() : ? UserInterface
{
$logUser = function(? int $id) use ($repository) {
if ( $id === null || null === ( $user = $repository->loadFromPk($id) ) ) {
$logUser = function(? int $id) {
if ( $id === null || null === ( $user = $this->user::repository()->loadFromPk($id) ) ) {
throw new \InvalidArgumentException(sprintf("User having id '%s' was not found.", $id));
}
$user->logged = true;
$this->user->fromArray($user);
return $user;
$this->user->logged = true;
return $this->user;
};
if ( $this->session && $this->session->has("user.id") ) {
@@ -52,14 +54,18 @@ class Authenticate {
$this->session->destroy();
}
public function authenticate(\Ulmus\Repository $repository, array $userLogin, string $password) : User
public function authenticate(array $userLogin, string $password) : bool
{
$repository = $this->user::repository();
foreach($userLogin as $field => $value) {
$repository->or($field, $value);
}
try {
$this->user = $repository->loadOne() ?: $repository->instanciateEntity();
if (null !== $entity = $repository->loadOne()) {
$this->user->fromArray($entity->toArray());
}
}
catch(Exception\EmptyDatasetException $e) {
if ( ! call_user_func_array($this->authenticationEvent, [ false, 'userNotFound', $this->user ]) ) {
@@ -98,7 +104,7 @@ class Authenticate {
call_user_func_array($this->authenticationEvent, [ false, 'authenticationFailed', $this->user, [ 'user_login' => $userLogin, 'password' => $password ] ]);
}
return $this->user;
return $this->user->logged;
}
public function logout() : self