-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityService.php
More file actions
41 lines (33 loc) · 1.22 KB
/
SecurityService.php
File metadata and controls
41 lines (33 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
namespace App\Utils\Security;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class SecurityService
{
public function __construct(
private TokenStorageInterface $tokenStorage,
private AuthorizationCheckerInterface $authorizationChecker,
)
{
}
public function getCurrentUser(): mixed
{
$user = $this->tokenStorage->getToken()?->getUser();
return $user instanceof User ? $user : null;
}
public function isGranted(mixed $attribute, mixed $subject = null): bool
{
return $this->authorizationChecker->isGranted($attribute, $subject);
}
public function denyAccessUnlessGranted(mixed $attribute, mixed $subject = null, ?string $message = null): void
{
if (!$this->isGranted($attribute, $subject)) {
$message = $message ?? 'Access Denied.';
$exception = new AccessDeniedException($message);
$exception->setAttributes([$attribute]);
$exception->setSubject($subject);
throw $exception;
}
}
}