From c33940f64a1e5b59afd700010247382f5b7b2df3 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Mon, 12 Nov 2018 14:41:23 +0100 Subject: Moved permission checks to Authenticator class --- src/Helpers/Authenticator.php | 60 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'src/Helpers') diff --git a/src/Helpers/Authenticator.php b/src/Helpers/Authenticator.php index 3061fbc1..edceaa44 100644 --- a/src/Helpers/Authenticator.php +++ b/src/Helpers/Authenticator.php @@ -2,6 +2,7 @@ namespace Engelsystem\Helpers; +use Carbon\Carbon; use Engelsystem\Models\User\User; use Engelsystem\Models\User\User as UserRepository; use Psr\Http\Message\ServerRequestInterface; @@ -21,6 +22,9 @@ class Authenticator /** @var UserRepository */ protected $userRepository; + /** @var string[] */ + protected $permissions; + /** * @param ServerRequestInterface $request * @param Session $session @@ -90,4 +94,60 @@ class Authenticator return $this->user; } + + /** + * @param string[]|string $abilities + * @return bool + */ + public function can($abilities): bool + { + $abilities = (array)$abilities; + + if (empty($this->permissions)) { + $userId = $this->session->get('uid'); + + if ($userId) { + if ($user = $this->user()) { + $this->permissions = $this->getPermissionsByUser($user); + + $user->last_login_at = new Carbon(); + $user->save(); + } else { + $this->session->remove('uid'); + } + } + + if (empty($this->permissions)) { + $this->permissions = $this->getPermissionsByGroup(-10); + } + } + + foreach ($abilities as $ability) { + if (!in_array($ability, $this->permissions)) { + return false; + } + } + + return true; + } + + /** + * @param User $user + * @return array + * @codeCoverageIgnore + */ + protected function getPermissionsByUser($user) + { + return privileges_for_user($user->id); + } + + /** + * @param int $groupId + * @return array + * @codeCoverageIgnore + */ + protected function getPermissionsByGroup(int $groupId) + { + return privileges_for_group($groupId); + } } -- cgit v1.2.3-54-g00ecf