szurubooru/src/Services/PrivilegeService.php

78 lines
2 KiB
PHP
Raw Normal View History

2014-09-06 10:00:26 +02:00
<?php
namespace Szurubooru\Services;
class PrivilegeService
{
private $authService;
private $privilegeMap;
public function __construct(
\Szurubooru\Config $config,
\Szurubooru\Services\AuthService $authService)
{
$this->authService = $authService;
if (isset($config->security->privileges))
{
foreach ($config->security->privileges as $privilegeName => $allowedAccessRanks)
{
$allowedAccessRanks = array_filter(preg_split('/[;,\s]+/', $allowedAccessRanks));
foreach ($allowedAccessRanks as $allowedAccessRank)
{
if (!isset($this->privilegeMap[$allowedAccessRank]))
$this->privilegeMap[$allowedAccessRank] = [];
2014-09-09 12:34:57 +02:00
$this->privilegeMap[$allowedAccessRank][] = $privilegeName;
2014-09-06 10:00:26 +02:00
}
}
}
}
public function getCurrentPrivileges()
{
$currentAccessRank = $this->authService->getLoggedInUser()->accessRank;
$currentAccessRankName = \Szurubooru\Helpers\EnumHelper::accessRankToString($currentAccessRank);
if (!isset($this->privilegeMap[$currentAccessRankName]))
return [];
return $this->privilegeMap[$currentAccessRankName];
}
public function hasPrivilege($privilege)
{
return in_array($privilege, $this->getCurrentPrivileges());
}
public function assertPrivilege($privilege)
{
if (!$this->hasPrivilege($privilege))
throw new \DomainException('Unprivileged operation');
}
2014-09-07 14:50:16 +02:00
public function assertLoggedIn($userIdentifier)
{
if (!$this->isLoggedIn($userIdentifier))
throw new \DomainException('Unprivileged operation');
}
2014-09-06 10:00:26 +02:00
public function isLoggedIn($userIdentifier)
{
$loggedInUser = $this->authService->getLoggedInUser();
if ($userIdentifier instanceof \Szurubooru\Entities\User)
{
2014-09-09 12:34:57 +02:00
return $loggedInUser->name === $userIdentifier->name;
}
2014-09-06 10:00:26 +02:00
elseif (is_string($userIdentifier))
{
if ($loggedInUser->email)
{
2014-09-09 12:34:57 +02:00
if ($loggedInUser->email === $userIdentifier)
return true;
}
2014-09-09 12:34:57 +02:00
return $loggedInUser->name === $userIdentifier;
}
2014-09-06 10:00:26 +02:00
else
{
2014-09-06 10:00:26 +02:00
throw new \InvalidArgumentException('Invalid user identifier.');
}
2014-09-06 10:00:26 +02:00
}
}