forked from SymfonyCasts/symfony-ux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpre-turbo-use-new-security.diff
295 lines (271 loc) · 12.1 KB
/
pre-turbo-use-new-security.diff
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
diff --git a/config/packages/security.yaml b/config/packages/security.yaml
index 9d199ba..ac75763 100644
--- a/config/packages/security.yaml
+++ b/config/packages/security.yaml
@@ -1,5 +1,7 @@
security:
- encoders:
+ enable_authenticator_manager: true
+
+ password_hashers:
App\Entity\User:
algorithm: auto
@@ -15,11 +17,9 @@ security:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
- anonymous: true
lazy: true
- guard:
- authenticators:
- - App\Security\LoginFormAuthenticator
+ custom_authenticators:
+ - App\Security\LoginFormAuthenticator
logout:
path: app_logout
# where to redirect after logout
diff --git a/src/Controller/RegistrationController.php b/src/Controller/RegistrationController.php
index 7be2280..e84524a 100644
--- a/src/Controller/RegistrationController.php
+++ b/src/Controller/RegistrationController.php
@@ -9,16 +9,16 @@ use App\Security\LoginFormAuthenticator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
-use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
-use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
+use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
class RegistrationController extends AbstractController
{
/**
* @Route("/register", name="app_register")
*/
- public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder, GuardAuthenticatorHandler $guardHandler, LoginFormAuthenticator $authenticator, ProductRepository $productRepository): Response
+ public function register(Request $request, UserPasswordHasherInterface $passwordHasher, UserAuthenticatorInterface $userAuthenticator, LoginFormAuthenticator $authenticator, ProductRepository $productRepository): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
@@ -27,7 +27,7 @@ class RegistrationController extends AbstractController
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
- $passwordEncoder->encodePassword(
+ $passwordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
@@ -39,11 +39,10 @@ class RegistrationController extends AbstractController
// do anything else you need here, like send an email
- return $guardHandler->authenticateUserAndHandleSuccess(
+ return $userAuthenticator->authenticateUser(
$user,
- $request,
$authenticator,
- 'main' // firewall name in security.yaml
+ $request,
);
}
diff --git a/src/DataFixtures/AppFixtures.php b/src/DataFixtures/AppFixtures.php
index 5600637..abc1be9 100644
--- a/src/DataFixtures/AppFixtures.php
+++ b/src/DataFixtures/AppFixtures.php
@@ -9,15 +9,16 @@ use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Filesystem\Filesystem;
+use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class AppFixtures extends Fixture
{
- private $passwordEncoder;
+ private UserPasswordHasherInterface $passwordHasher;
- public function __construct(UserPasswordEncoderInterface $passwordEncoder)
+ public function __construct(UserPasswordHasherInterface $passwordHasher)
{
- $this->passwordEncoder = $passwordEncoder;
+ $this->passwordHasher = $passwordHasher;
}
public function load(ObjectManager $manager)
@@ -83,14 +84,14 @@ class AppFixtures extends Fixture
$user = new User();
$user->setEmail('[email protected]');
- $user->setPassword($this->passwordEncoder->encodePassword($user, 'buy'));
+ $user->setPassword($this->passwordHasher->hashPassword($user, 'buy'));
$manager->persist($user);
$manager->flush();
}
- private static function getProductsData()
+ private static function getProductsData(): iterable
{
/* OFFICE SUPPLIES */
yield [
diff --git a/src/Entity/User.php b/src/Entity/User.php
index abdb02d..23f03ea 100644
--- a/src/Entity/User.php
+++ b/src/Entity/User.php
@@ -4,6 +4,7 @@ namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
+use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
@@ -11,7 +12,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
-class User implements UserInterface
+class User implements UserInterface, PasswordAuthenticatedUserInterface
{
/**
* @ORM\Id()
@@ -60,7 +61,7 @@ class User implements UserInterface
*
* @see UserInterface
*/
- public function getUsername(): string
+ public function getUserIdentifier(): string
{
return (string) $this->email;
}
diff --git a/src/Security/LoginFormAuthenticator.php b/src/Security/LoginFormAuthenticator.php
index 297f815..48a71a4 100644
--- a/src/Security/LoginFormAuthenticator.php
+++ b/src/Security/LoginFormAuthenticator.php
@@ -6,98 +6,69 @@ use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
-use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
-use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
-use Symfony\Component\Security\Core\User\UserInterface;
-use Symfony\Component\Security\Core\User\UserProviderInterface;
-use Symfony\Component\Security\Csrf\CsrfToken;
-use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
-use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
-use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
+use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
+use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
+use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
+use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
+use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
+use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
+use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
-class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
+class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
- private $entityManager;
- private $urlGenerator;
- private $csrfTokenManager;
- private $passwordEncoder;
+ private EntityManagerInterface $entityManager;
+ private UrlGeneratorInterface $urlGenerator;
- public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
+ public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
- $this->csrfTokenManager = $csrfTokenManager;
- $this->passwordEncoder = $passwordEncoder;
}
- public function supports(Request $request)
+ public function authenticate(Request $request): PassportInterface
{
- return 'app_login' === $request->attributes->get('_route')
- && $request->isMethod('POST');
- }
-
- public function getCredentials(Request $request)
- {
- $credentials = [
- 'email' => $request->request->get('email'),
- 'password' => $request->request->get('password'),
- 'csrf_token' => $request->request->get('_csrf_token'),
- ];
+ $email = $request->request->get('email');
$request->getSession()->set(
Security::LAST_USERNAME,
- $credentials['email']
+ $email
);
- return $credentials;
- }
-
- public function getUser($credentials, UserProviderInterface $userProvider)
- {
- $token = new CsrfToken('authenticate', $credentials['csrf_token']);
- if (!$this->csrfTokenManager->isTokenValid($token)) {
- throw new InvalidCsrfTokenException();
- }
-
- $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
-
- if (!$user) {
- // fail authentication with a custom error
- throw new CustomUserMessageAuthenticationException('Email could not be found.');
- }
-
- return $user;
- }
-
- public function checkCredentials($credentials, UserInterface $user)
- {
- return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
- }
-
- /**
- * Used to upgrade (rehash) the user's password automatically over time.
- */
- public function getPassword($credentials): ?string
- {
- return $credentials['password'];
+ return new Passport(
+ new UserBadge($email, function() use ($email) {
+ $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
+
+ if (!$user) {
+ throw new CustomUserMessageAuthenticationException('Email not found!');
+ }
+
+ return $user;
+ }),
+ new PasswordCredentials($request->request->get('password')),
+ [
+ new CsrfTokenBadge('authenticate', $request->request->get('_csrf_token')),
+ new RememberMeBadge(),
+ ]
+ );
}
- public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
+ public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
- if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
+ if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
return new RedirectResponse($this->urlGenerator->generate('app_homepage'));
}
- protected function getLoginUrl()
+ protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate('app_login');
}
diff --git a/templates/security/login.html.twig b/templates/security/login.html.twig
index b71ecc6..9133359 100644
--- a/templates/security/login.html.twig
+++ b/templates/security/login.html.twig
@@ -13,7 +13,7 @@
{% if app.user %}
<div class="mb-3">
- You are logged in as {{ app.user.username }}, <a href="{{ path('app_logout') }}">Logout</a>
+ You are logged in as {{ app.user.userIdentifier }}, <a href="{{ path('app_logout') }}">Logout</a>
</div>
{% endif %}