1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Sylius package. |
5
|
|
|
* |
6
|
|
|
* (c) Paweł Jędrzejewski |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Sylius\Bundle\UserBundle\EventListener; |
15
|
|
|
|
16
|
|
|
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent; |
17
|
|
|
use Sylius\Component\User\Model\UserInterface; |
18
|
|
|
use Symfony\Component\HttpFoundation\Response; |
19
|
|
|
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface; |
20
|
|
|
use Symfony\Component\HttpFoundation\Session\SessionInterface; |
21
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
22
|
|
|
use Webmozart\Assert\Assert; |
23
|
|
|
|
24
|
|
|
final class UserDeleteListener |
25
|
|
|
{ |
26
|
|
|
/** @var TokenStorageInterface */ |
27
|
|
|
private $tokenStorage; |
28
|
|
|
|
29
|
|
|
/** @var SessionInterface */ |
30
|
|
|
private $session; |
31
|
|
|
|
32
|
|
|
public function __construct(TokenStorageInterface $tokenStorage, SessionInterface $session) |
33
|
|
|
{ |
34
|
|
|
$this->tokenStorage = $tokenStorage; |
35
|
|
|
$this->session = $session; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @throws \InvalidArgumentException |
40
|
|
|
*/ |
41
|
|
|
public function deleteUser(ResourceControllerEvent $event): void |
42
|
|
|
{ |
43
|
|
|
$user = $event->getSubject(); |
44
|
|
|
|
45
|
|
|
Assert::isInstanceOf($user, UserInterface::class); |
46
|
|
|
|
47
|
|
|
if ($this->isTryingToDeleteLoggedInAdminUser($user)) { |
48
|
|
|
$event->stopPropagation(); |
49
|
|
|
$event->setErrorCode(Response::HTTP_UNPROCESSABLE_ENTITY); |
50
|
|
|
$event->setMessage('Cannot remove currently logged in user.'); |
51
|
|
|
|
52
|
|
|
/** @var FlashBagInterface $flashBag */ |
53
|
|
|
$flashBag = $this->session->getBag('flashes'); |
54
|
|
|
$flashBag->add('error', 'Cannot remove currently logged in user.'); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function isTryingToDeleteLoggedInAdminUser(UserInterface $user): bool |
59
|
|
|
{ |
60
|
|
|
if (!$user->hasRole('ROLE_ADMINISTRATION_ACCESS') && !$user->hasRole('ROLE_API_ACCESS')){ |
61
|
|
|
return false; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$token = $this->tokenStorage->getToken(); |
65
|
|
|
if (!$token) { |
66
|
|
|
return false; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$loggedUser = $token->getUser(); |
70
|
|
|
if (!$loggedUser) { |
71
|
|
|
return false; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $loggedUser->getId() === $user->getId(); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|