|
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->isTryingToDeleteLoggedInUser($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 isTryingToDeleteLoggedInUser(UserInterface $user): bool |
|
59
|
|
|
{ |
|
60
|
|
|
$token = $this->tokenStorage->getToken(); |
|
61
|
|
|
if (!$token) { |
|
62
|
|
|
return false; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
$loggedUser = $token->getUser(); |
|
66
|
|
|
if (!$loggedUser) { |
|
67
|
|
|
return false; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return $loggedUser->getId() === $user->getId() && $loggedUser->getRoles() === $user->getRoles(); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|