From d9167fb5318d5370ba5445e94c0e0f9b64341df4 Mon Sep 17 00:00:00 2001 From: George Halkiadakis Date: Mon, 13 Mar 2023 02:22:07 +0200 Subject: authentication skeleton --- core/classes/authentication/Core/PasswordTrait.php | 32 ++++++++++ core/classes/authentication/Core/UserManager.php | 68 ++++++++++++++++++++++ .../authentication/Core/UserManagerInterface.php | 25 ++++++++ 3 files changed, 125 insertions(+) create mode 100644 core/classes/authentication/Core/PasswordTrait.php create mode 100644 core/classes/authentication/Core/UserManager.php create mode 100644 core/classes/authentication/Core/UserManagerInterface.php (limited to 'core/classes/authentication/Core') diff --git a/core/classes/authentication/Core/PasswordTrait.php b/core/classes/authentication/Core/PasswordTrait.php new file mode 100644 index 0000000..18d67b5 --- /dev/null +++ b/core/classes/authentication/Core/PasswordTrait.php @@ -0,0 +1,32 @@ + $this->cost]); + } + + public function isPasswordValid(UserInterface $user, string $plainPassword): bool + { + return password_verify($plainPassword, $user->getPassword()); + } + + public function setCost(int $cost): void + { + if ($cost < 4 || $cost > 12) { + throw new \InvalidArgumentException('Cost must be in the range of 4-31.'); + } + $this->cost = $cost; + } +} diff --git a/core/classes/authentication/Core/UserManager.php b/core/classes/authentication/Core/UserManager.php new file mode 100644 index 0000000..3b380b8 --- /dev/null +++ b/core/classes/authentication/Core/UserManager.php @@ -0,0 +1,68 @@ +hasUserToken()) { + $userToken = unserialize($_SESSION[UserTokenInterface::DEFAULT_PREFIX_KEY]); + } + + return $userToken; + } + + public function hasUserToken(): bool + { + $key = UserTokenInterface::DEFAULT_PREFIX_KEY; + return (array_key_exists($key, $_SESSION) && unserialize($_SESSION[$key]) !== false); + } + + public function isGranted(array $roles): bool + { + if (!is_null($userToken = $this->getUserToken())) { + return false; + } + + if ($userToken->getUser() instanceof UserInterface) { + return (!empty(array_intersect($roles, $userToken->getUser()->getRoles()))); + } + + return false; + } + + public function createUserToken(UserInterface $user): UserTokenInterface + { + $userToken = new UserToken($user); + $_SESSION[UserTokenInterface::DEFAULT_PREFIX_KEY] = $userToken->serialize(); + + return $userToken; + } + + public function logout(): void + { + if ($this->hasUserToken()) { + unset($_SESSION[UserTokenInterface::DEFAULT_PREFIX_KEY]); + } + } +} diff --git a/core/classes/authentication/Core/UserManagerInterface.php b/core/classes/authentication/Core/UserManagerInterface.php new file mode 100644 index 0000000..4702992 --- /dev/null +++ b/core/classes/authentication/Core/UserManagerInterface.php @@ -0,0 +1,25 @@ +