From 1f6a7b57bb1450f400f253b35b465ad56bd91198 Mon Sep 17 00:00:00 2001 From: jeroen Date: Wed, 7 Sep 2022 14:36:22 +0200 Subject: [PATCH] ENHANCEMENT: Saving locale in database --- config/packages/security.yaml | 11 ++++++-- config/services.yaml | 5 +++- migrations/Version1002.php | 32 +++++++++++++++++++++ src/Command/DemoInstallCommand.php | 2 +- src/Command/UserCommand.php | 17 ++++++++++-- src/Controller/SecurityController.php | 5 +++- src/Entity/User.php | 24 ++++++++++++++++ src/EventSubscriber/LoginSubscriber.php | 37 +++++++++++++++++++++++++ 8 files changed, 125 insertions(+), 8 deletions(-) create mode 100644 migrations/Version1002.php create mode 100644 src/EventSubscriber/LoginSubscriber.php diff --git a/config/packages/security.yaml b/config/packages/security.yaml index d482bea..d3564e8 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -14,7 +14,7 @@ security: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false login: - pattern: ^/?(%enabled_locales%)?/(health)$ + pattern: ^/?([a-zA-Z0-9-]+)?/(health)$ security: false main: pattern: ^/(.*) @@ -41,5 +41,12 @@ security: # Easy way to control access for large sections of your site # Note: Only the *first* access control that matches will be used access_control: - - { path: ^/?(%enabled_locales%)?/job, roles: ROLE_USER } + - { path: ^/?([a-zA-Z0-9-]+)?/job, roles: ROLE_USER } # - { path: ^/profile, roles: ROLE_USER } + +when@dev: + security: + firewalls: + main: + remember_me: + secure: false diff --git a/config/services.yaml b/config/services.yaml index 9d56fc9..bb5f3ce 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -4,7 +4,10 @@ # Put parameters here that don't need to change on each machine where the app is deployed # https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration parameters: - enabled_locales: 'en|nl' + enabled_locales: + en: 'English' + nl: 'Nederlands' + en-l33t: '3ngL1sh (L33t)' security: csp_policy: "default-src 'none'; font-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; img-src 'self' data:; form-action 'self'; require-trusted-types-for 'script'; frame-ancestors 'none'; base-uri 'none'" referer_policy: "same-origin" diff --git a/migrations/Version1002.php b/migrations/Version1002.php new file mode 100644 index 0000000..7ef3d75 --- /dev/null +++ b/migrations/Version1002.php @@ -0,0 +1,32 @@ +addSql('ALTER TABLE user ADD locale VARCHAR(15) NOT NULL'); + $this->addSql('UPDATE user SET locale = :locale', ['locale' => 'en']); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('ALTER TABLE user DROP locale'); + } +} diff --git a/src/Command/DemoInstallCommand.php b/src/Command/DemoInstallCommand.php index a148932..d0df284 100755 --- a/src/Command/DemoInstallCommand.php +++ b/src/Command/DemoInstallCommand.php @@ -55,7 +55,7 @@ class DemoInstallCommand extends Command $user ->setEmail($_ENV['DEMO_USER']) ->setPassword($hashedpassword) - ->setSendmail(true); + ->setLocale('en'); $em->persist($user); $em->flush(); diff --git a/src/Command/UserCommand.php b/src/Command/UserCommand.php index badfcc1..59d891d 100755 --- a/src/Command/UserCommand.php +++ b/src/Command/UserCommand.php @@ -17,6 +17,7 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\Question; use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; @@ -27,17 +28,20 @@ class UserCommand extends Command protected ManagerRegistry $doctrine; protected UserPasswordHasherInterface $passwordHasher; protected SymfonyStyle $io; + protected ParameterBagInterface $params; private $action; private $username; private $password; + private $locale; private $confirm; - public function __construct(KernelInterface $kernel, ManagerRegistry $doctrine, UserPasswordHasherInterface $passwordHasher) + public function __construct(KernelInterface $kernel, ManagerRegistry $doctrine, UserPasswordHasherInterface $passwordHasher, ParameterBagInterface $params) { $this->kernel = $kernel; $this->doctrine = $doctrine; $this->passwordHasher = $passwordHasher; + $this->params = $params; parent::__construct(); } @@ -100,6 +104,12 @@ class UserCommand extends Command $this->password = $password1; } } + + if(empty($this->locale)) { + $locales = $this->params->get('enabled_locales'); + + $this->locale = $this->io->choice('What locale should be used? ', $locales); + } } elseif ($this->action == 'delete') { $this->confirm = $this->io->confirm('Are you sure you want to delete ' . $this->username . '? ', false); } @@ -145,7 +155,7 @@ class UserCommand extends Command $user ->setEmail($this->username) ->setPassword($hashedpassword) - ->setSendmail($userSendMail === NULL); + ->setLocale($this->locale); $em->persist($user); $em->flush(); @@ -173,7 +183,8 @@ class UserCommand extends Command $hashedpassword = $this->passwordHasher->hashPassword($user, $this->password); $user ->setEmail($this->username) - ->setPassword($hashedpassword); + ->setPassword($hashedpassword) + ->setLocale($this->locale); $em->persist($user); $em->flush(); diff --git a/src/Controller/SecurityController.php b/src/Controller/SecurityController.php index 2883c4e..61e44d4 100644 --- a/src/Controller/SecurityController.php +++ b/src/Controller/SecurityController.php @@ -14,7 +14,10 @@ class SecurityController extends AbstractController public function loginAction(Request $request, AuthenticationUtils $authenticationUtils): Response { if($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) { - return new RedirectResponse($this->generateUrl('job_index')); + $session = $request->getSession(); + $user = $this->getUser(); + $session->set('_locale', $user->getLocale()); + return new RedirectResponse($this->generateUrl('job_index', ['_locale' => $user->getLocale()])); } // get the login error if there is one $error = $authenticationUtils->getLastAuthenticationError(); diff --git a/src/Entity/User.php b/src/Entity/User.php index 29720a3..6a25fde 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -30,6 +30,12 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface #[ORM\Column(type: "string", length: 60)] private string $password; + /** + * @var string + */ + #[ORM\Column(type: "string", length: 15)] + private string $locale; + /** * @return int|null */ @@ -84,6 +90,24 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface return $this; } + /** + * @return string + */ + public function getLocale(): string + { + return $this->locale; + } + + /** + * @param string $locale + * @return User + */ + public function setLocale(string $locale): User + { + $this->locale = $locale; + return $this; + } + public function getRoles(): array { return array_unique(['ROLE_USER']); diff --git a/src/EventSubscriber/LoginSubscriber.php b/src/EventSubscriber/LoginSubscriber.php new file mode 100644 index 0000000..146f6be --- /dev/null +++ b/src/EventSubscriber/LoginSubscriber.php @@ -0,0 +1,37 @@ +defaultLocale = $defaultLocale; + } + + public function onSuccessfulLogin(LoginSuccessEvent $event) + { + /** @var User $user */ + $user = $event->getAuthenticatedToken()->getUser(); + $request = $event->getRequest(); + + // try to see if the locale has been set as a _locale routing parameter + if ($locale = $user->getLocale()) { + $request->getSession()->set('_locale', $locale); + } else { + // if no explicit locale has been set on this request, use one from the session + $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale)); + } + } + + public static function getSubscribedEvents() + { + return [LoginSuccessEvent::class => ['onSuccessfulLogin', 20]]; + } +} \ No newline at end of file