|
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('change_password.current_password_invalid'), |
|
42
|
|
|
], |
|
43
|
|
|
Response::HTTP_BAD_REQUEST |
|
44
|
|
|
); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
// Hash the new password directly |
|
48
|
|
|
$hashedPassword = $this->passwordHasher->hashPassword( |
|
49
|
|
|
$user, |
|
50
|
|
|
$newPassword |
|
|
|
|
|
|
51
|
|
|
); |
|
52
|
|
|
$user->setPassword($hashedPassword); |
|
53
|
|
|
|
|
54
|
|
|
// Save changes |
|
55
|
|
|
$this->entityManager->flush(); |
|
56
|
|
|
|
|
57
|
|
|
// Dispatch password changed event manually |
|
58
|
|
|
$passwordChangedEvent = new PasswordChangedEvent($user); |
|
59
|
|
|
$this->eventDispatcher->dispatch($passwordChangedEvent); |
|
60
|
|
|
|
|
61
|
|
|
return new JsonResponse(['success' => true]); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|