-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathUserController.php
82 lines (70 loc) · 2.74 KB
/
UserController.php
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Controller;
use App\Entity\User;
use App\Form\ChangePasswordType;
use App\Form\UserType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Controller used to manage current user. The #[CurrentUser] attribute
* tells Symfony to inject the currently logged user into the given argument.
* It can only be used in controllers and it's an alternative to the
* $this->getUser() method, which still works inside controllers.
*
* @author Romain Monteil <[email protected]>
*/
#[Route('/profile'), IsGranted(User::ROLE_USER)]
final class UserController extends AbstractController
{
#[Route('/edit', name: 'user_edit', methods: ['GET', 'POST'])]
public function edit(
#[CurrentUser] User $user,
Request $request,
EntityManagerInterface $entityManager,
): Response {
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
$this->addFlash('success', 'user.updated_successfully');
return $this->redirectToRoute('user_edit', [], Response::HTTP_SEE_OTHER);
}
return $this->render('user/edit.html.twig', [
'user' => $user,
'form' => $form,
]);
}
#[Route('/change-password', name: 'user_change_password', methods: ['GET', 'POST'])]
public function changePassword(
#[CurrentUser] User $user,
Request $request,
EntityManagerInterface $entityManager,
Security $security,
): Response {
$form = $this->createForm(ChangePasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
// The logout method applies an automatic protection against CSRF attacks;
// it's explicitly disabled here because the form already has a CSRF token validated.
return $security->logout(validateCsrfToken: false) ?? $this->redirectToRoute('homepage');
}
return $this->render('user/change_password.html.twig', [
'form' => $form,
]);
}
}