Skip to content

Commit 8f1996c

Browse files
update security system according to symfony 5.3
1 parent c9c0e0c commit 8f1996c

File tree

9 files changed

+75
-132
lines changed

9 files changed

+75
-132
lines changed

config/packages/security.yaml

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
security:
2-
encoders:
2+
# https://symfony.com/doc/current/security/authenticator_manager.html
3+
enable_authenticator_manager: true
4+
password_hashers:
5+
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
36
App\Entity\User:
47
algorithm: auto
58

@@ -15,12 +18,9 @@ security:
1518
pattern: ^/(_(profiler|wdt)|css|images|js)/
1619
security: false
1720
main:
18-
anonymous: true
1921
lazy: true
2022
provider: app_user_provider
21-
guard:
22-
authenticators:
23-
- App\Security\LoginFormAuthenticator
23+
custom_authenticator: App\Security\LoginFormAuthenticator
2424
logout:
2525
path: app_logout
2626
# where to redirect after logout

src/Controller/ResetPasswordController.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@
3737
use Symfony\Component\HttpFoundation\Response;
3838
use Symfony\Component\Mailer\MailerInterface;
3939
use Symfony\Component\Mime\Address;
40+
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
4041
use Symfony\Component\Routing\Annotation\Route;
41-
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
4242
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
4343
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
4444
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
@@ -107,7 +107,7 @@ public function checkEmail(): Response
107107
*/
108108
public function reset(
109109
Request $request,
110-
UserPasswordEncoderInterface $passwordEncoder,
110+
UserPasswordHasherInterface $passwordHasher,
111111
string $token = null
112112
): Response {
113113
if ($token) {
@@ -143,7 +143,7 @@ public function reset(
143143
$this->resetPasswordHelper->removeResetRequest($token);
144144

145145
// Encode the plain password, and set it.
146-
$encodedPassword = $passwordEncoder->encodePassword(
146+
$encodedPassword = $passwordHasher->hashPassword(
147147
$user,
148148
$form->get('plainPassword')->getData()
149149
);

src/Controller/SecurityController.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public function login(AuthenticationUtils $authenticationUtils): Response
5353
/**
5454
* @Route("/logout", name="app_logout")
5555
*/
56-
public function logout()
56+
public function logout(): void
5757
{
5858
throw new \LogicException();
5959
}

src/Controller/SignUpController.php

+22-27
Original file line numberDiff line numberDiff line change
@@ -28,37 +28,39 @@
2828

2929
use App\Entity\User;
3030
use App\Event\InvitationEvent;
31+
use App\Form\RegistrationFormType;
3132
use App\Form\SignUpType;
3233
use App\Repository\InvitationRepository;
3334
use App\Repository\UserClassRepository;
3435
use App\Repository\UserRepository;
3536
use App\Security\EmailVerifier;
36-
use App\Security\LoginFormAuthenticator;
37+
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
3738
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
38-
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
39+
use Symfony\Component\EventDispatcher\EventDispatcherInterface as EventDispatcherEventDispatcherInterface;
3940
use Symfony\Component\HttpFoundation\Request;
4041
use Symfony\Component\HttpFoundation\Response;
42+
use Symfony\Component\Mime\Address;
43+
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
4144
use Symfony\Component\Routing\Annotation\Route;
42-
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
43-
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
45+
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
4446

4547
class SignUpController extends AbstractController
4648
{
47-
private $userLimitReached = false;
49+
private bool $userLimitReached = false;
50+
private bool $needCode = false;
51+
4852

4953
/**
5054
* @Route("/signup", name="sign_up")
5155
*/
52-
public function index(
56+
public function register(
5357
Request $request,
54-
UserClassRepository $userClassRepository,
58+
EmailVerifier $emailVerifier,
59+
UserPasswordHasherInterface $userPasswordHasherInterface,
5560
UserRepository $userRepository,
56-
GuardAuthenticatorHandler $guardHandler,
57-
LoginFormAuthenticator $authenticator,
58-
UserPasswordEncoderInterface $passwordEncoder,
61+
UserClassRepository $userClassRepository,
5962
InvitationRepository $invitationRepository,
60-
EventDispatcherInterface $dispatcher,
61-
EmailVerifier $emailVerifier
63+
EventDispatcherEventDispatcherInterface $dispatcher
6264
): Response {
6365

6466
// Check user limit
@@ -69,24 +71,22 @@ public function index(
6971
$this->userLimitReached = true;
7072
}
7173
}
74+
// Check if app is registrations are open
75+
$this->needCode = !$this->getParameter('app.open_registration');
7276

7377

7478
$user = new User();
75-
76-
$needCode = !$this->getParameter('app.open_registration');
7779
$form = $this->createForm(
7880
SignUpType::class,
7981
$user,
80-
['needCode' => $needCode, 'userLimitReached' => $this->userLimitReached]
82+
['needCode' => $this->needCode, 'userLimitReached' => $this->userLimitReached]
8183
);
82-
8384
$form->handleRequest($request);
85+
8486
if ($form->isSubmitted() && $form->isValid()) {
85-
/** @var User $user */
8687
$user = $form->getData();
87-
8888
$user->setPassword(
89-
$passwordEncoder->encodePassword(
89+
$userPasswordHasherInterface->hashPassword(
9090
$user,
9191
$form->get('plainPassword')->getData()
9292
)
@@ -103,7 +103,7 @@ public function index(
103103
$entityManager = $this->getDoctrine()->getManager();
104104
$entityManager->persist($user);
105105

106-
if ($needCode) {
106+
if ($this->needCode) {
107107
$code = $form->get('code')->getData();
108108
$invitation = $invitationRepository->findOneBy(['code' => $code]);
109109
$invitation->setChild($user);
@@ -114,6 +114,7 @@ public function index(
114114
$entityManager->flush();
115115
}
116116

117+
117118
// Send validation email
118119
$emailVerifier->sendEmailConfirmation(
119120
'email_verify',
@@ -122,15 +123,9 @@ public function index(
122123
$email = $user->getEmail();
123124
$this->addFlash('primary', "An email have been send to $email for validation");
124125

125-
return $guardHandler->authenticateUserAndHandleSuccess(
126-
$user,
127-
$request,
128-
$authenticator,
129-
'main' // firewall name in security.yaml
130-
);
126+
return $this->redirectToRoute('app_login');
131127
}
132128

133-
134129
return $this->render('sign_up/index.html.twig', [
135130
'form' => $form->createView(),
136131
'userLimitReached' => $this->userLimitReached,

src/DataFixtures/UserFixture.php

+13-13
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,15 @@
3232
use Doctrine\Bundle\FixturesBundle\Fixture;
3333
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
3434
use Doctrine\Persistence\ObjectManager;
35-
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
35+
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
3636

3737
class UserFixture extends Fixture implements DependentFixtureInterface
3838
{
39-
private $passwordEncoder;
39+
private $passwordHasher;
4040

41-
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
41+
public function __construct(UserPasswordHasherInterface $passwordHasher)
4242
{
43-
$this->passwordEncoder = $passwordEncoder;
43+
$this->passwordHasher = $passwordHasher;
4444
}
4545

4646

@@ -63,7 +63,7 @@ public function load(ObjectManager $manager)
6363
$userBolos
6464
->setUsername('bolos')
6565
->setEmail('[email protected]')
66-
->setPassword($this->passwordEncoder->encodePassword($userBolos, 'bolos'))
66+
->setPassword($this->passwordHasher->hashPassword($userBolos, 'bolos'))
6767
->setUserClass($basicUser)
6868
->setCreatedAt(new DateTime('2020-02-02'))
6969
->setParanoia(0)
@@ -74,7 +74,7 @@ public function load(ObjectManager $manager)
7474
$userVincent
7575
->setUsername('vincent')
7676
->setEmail('[email protected]')
77-
->setPassword($this->passwordEncoder->encodePassword($userVincent, 'vincent'))
77+
->setPassword($this->passwordHasher->hashPassword($userVincent, 'vincent'))
7878
->setUserClass($member)
7979
->setCreatedAt(new DateTime('2020-06-02'))
8080
->setParanoia(0)
@@ -87,7 +87,7 @@ public function load(ObjectManager $manager)
8787
$userGuillaume
8888
->setUsername('guillaume')
8989
->setEmail('[email protected]')
90-
->setPassword($this->passwordEncoder->encodePassword($userGuillaume, 'gp231299'))
90+
->setPassword($this->passwordHasher->hashPassword($userGuillaume, 'gp231299'))
9191
->setUserClass($basicUser)
9292
->setCreatedAt(new DateTime('2020-04-04'))
9393
->setParanoia(0)
@@ -99,7 +99,7 @@ public function load(ObjectManager $manager)
9999
$userLea
100100
->setUsername('leatine')
101101
->setEmail('[email protected]')
102-
->setPassword($this->passwordEncoder->encodePassword($userLea, 'leatine'))
102+
->setPassword($this->passwordHasher->hashPassword($userLea, 'leatine'))
103103
->setUserClass($member)
104104
->setCreatedAt(new DateTime('2019-06-06'))
105105
->setParanoia(0)
@@ -111,7 +111,7 @@ public function load(ObjectManager $manager)
111111
$userNicolas
112112
->setUsername('nicolas')
113113
->setEmail('[email protected]')
114-
->setPassword($this->passwordEncoder->encodePassword($userNicolas, 'espace'))
114+
->setPassword($this->passwordHasher->hashPassword($userNicolas, 'espace'))
115115
->setUserClass($member)
116116
->setCreatedAt(new DateTime('2018-01-01'))
117117
->setParanoia(1)
@@ -123,7 +123,7 @@ public function load(ObjectManager $manager)
123123
$userAudrey
124124
->setUsername('audrey')
125125
->setEmail('[email protected]')
126-
->setPassword($this->passwordEncoder->encodePassword($userAudrey, 'missmogwai'))
126+
->setPassword($this->passwordHasher->hashPassword($userAudrey, 'missmogwai'))
127127
->setRole(User::ROLE_MODERATOR)
128128
->setUserClass($powerUser)
129129
->setCreatedAt(new DateTime('2018-03-03'))
@@ -136,7 +136,7 @@ public function load(ObjectManager $manager)
136136
$userGuilhem
137137
->setUsername('guilhem')
138138
->setEmail('[email protected]')
139-
->setPassword($this->passwordEncoder->encodePassword($userGuilhem, 'guilhem'))
139+
->setPassword($this->passwordHasher->hashPassword($userGuilhem, 'guilhem'))
140140
->setUserClass($elite)
141141
->setCreatedAt(new DateTime('2017-09-09'))
142142
->setParanoia(2)
@@ -148,7 +148,7 @@ public function load(ObjectManager $manager)
148148
$userRelou
149149
->setUsername('relou')
150150
->setEmail('[email protected]')
151-
->setPassword($this->passwordEncoder->encodePassword($userRelou, 'relou'))
151+
->setPassword($this->passwordHasher->hashPassword($userRelou, 'relou'))
152152
->setUserClass($member)
153153
->setCreatedAt(new DateTime('2019-09-09'))
154154
->setParanoia(0)
@@ -161,7 +161,7 @@ public function load(ObjectManager $manager)
161161
$userEscargot
162162
->setUsername('escargot')
163163
->setEmail('[email protected]')
164-
->setPassword($this->passwordEncoder->encodePassword($userEscargot, 'escargot'))
164+
->setPassword($this->passwordHasher->hashPassword($userEscargot, 'escargot'))
165165
->setUserClass($basicUser)
166166
->setCreatedAt(new DateTime('2013-03-03'))
167167
->setLastActivity(new DateTime('2013-04-04'))

src/Entity/User.php

+7-1
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,15 @@
3535
use Symfony\Component\Validator\Constraints as Assert;
3636
use Doctrine\ORM\Mapping as ORM;
3737
use InvalidArgumentException;
38+
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
3839
use Symfony\Component\Security\Core\User\UserInterface;
3940

4041
/**
4142
* @ORM\Entity(repositoryClass=UserRepository::class)
4243
* @UniqueEntity(fields={"username"}, message="There is already an account with this username")
4344
* @UniqueEntity(fields={"email"}, message="There is already an account with this email adress")
4445
*/
45-
class User implements UserInterface
46+
class User implements UserInterface, PasswordAuthenticatedUserInterface
4647
{
4748
public const ROLE_USER = 0;
4849
public const ROLE_MODERATOR = 50;
@@ -240,6 +241,11 @@ public function setUsername(string $username): self
240241
return $this;
241242
}
242243

244+
public function getUserIdentifier(): string
245+
{
246+
return (string) $this->username;
247+
}
248+
243249
public function getRole(): int
244250
{
245251
return $this->role;

src/EventSubscriber/ActivitySubscriber.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public static function getSubscribedEvents()
7272

7373
public function onKernelTerminate(TerminateEvent $event): void
7474
{
75-
if ($event->isMasterRequest()) {
75+
if ($event->isMainRequest()) {
7676
$user = $this->security->getUser();
7777
$delay = $this->parameterBag->get('app.last_activity_delay');
7878
if (($user instanceof User) && $user->getLastActivity() < new DateTime("$delay minute ago")) {

src/Form/SignUpType.php

-8
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,6 @@
4646

4747
class SignUpType extends AbstractType
4848
{
49-
/** @var UserpasswordEncoderInterface */
50-
private $passwordEncoder;
51-
52-
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
53-
{
54-
$this->passwordEncoder = $passwordEncoder;
55-
}
56-
5749
public function buildForm(FormBuilderInterface $builder, array $options): void
5850
{
5951
/** @var bool */

0 commit comments

Comments
 (0)