1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ProjetNormandie\UserBundle\Controller\User; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
6
|
|
|
use ProjetNormandie\UserBundle\Entity\User; |
7
|
|
|
use ProjetNormandie\UserBundle\Event\PasswordChangedEvent; |
8
|
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
9
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
10
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
11
|
|
|
use Symfony\Component\HttpFoundation\Request; |
12
|
|
|
use Symfony\Component\HttpFoundation\Response; |
13
|
|
|
use Symfony\Component\HttpKernel\Attribute\AsController; |
14
|
|
|
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; |
15
|
|
|
use Symfony\Contracts\Translation\TranslatorInterface; |
16
|
|
|
|
17
|
|
|
#[AsController] |
18
|
|
|
class ChangePassword extends AbstractController |
19
|
|
|
{ |
20
|
|
|
public function __construct( |
21
|
|
|
private readonly UserPasswordHasherInterface $passwordHasher, |
22
|
|
|
private readonly TranslatorInterface $translator, |
23
|
|
|
private readonly EntityManagerInterface $entityManager, |
24
|
|
|
private readonly EventDispatcherInterface $eventDispatcher |
25
|
|
|
) { |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function __invoke(Request $request): Response |
29
|
|
|
{ |
30
|
|
|
$data = json_decode($request->getContent(), true); |
31
|
|
|
$currentPassword = $data['currentPassword'] ?? null; |
32
|
|
|
$newPassword = $data['newPassword'] ?? null; |
33
|
|
|
|
34
|
|
|
/** @var User $user */ |
35
|
|
|
$user = $this->getUser(); |
36
|
|
|
|
37
|
|
|
// Verify current password |
38
|
|
|
if (!$this->passwordHasher->isPasswordValid($user, $currentPassword)) { |
|
|
|
|
39
|
|
|
return new JsonResponse( |
40
|
|
|
[ |
41
|
|
|
'message' => $this->translator->trans( |
42
|
|
|
'change_password.current_password_invalid', |
43
|
|
|
[], |
44
|
|
|
'PnUser', |
45
|
|
|
$user->getLanguage() |
46
|
|
|
), |
47
|
|
|
], |
48
|
|
|
Response::HTTP_BAD_REQUEST |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
// Hash the new password directly |
53
|
|
|
$hashedPassword = $this->passwordHasher->hashPassword( |
54
|
|
|
$user, |
55
|
|
|
$newPassword |
|
|
|
|
56
|
|
|
); |
57
|
|
|
$user->setPassword($hashedPassword); |
58
|
|
|
|
59
|
|
|
// Save changes |
60
|
|
|
$this->entityManager->flush(); |
61
|
|
|
|
62
|
|
|
// Dispatch password changed event manually |
63
|
|
|
$passwordChangedEvent = new PasswordChangedEvent($user); |
64
|
|
|
$this->eventDispatcher->dispatch($passwordChangedEvent); |
65
|
|
|
|
66
|
|
|
return new JsonResponse(['success' => true]); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|