From 5b6bfaf5ad97e19eabec0067763947e9ffd9136d Mon Sep 17 00:00:00 2001 From: Frank Date: Sat, 3 Jan 2026 22:12:51 +0100 Subject: [PATCH 1/3] Quite some work done here. --- .env | 2 +- .idea/escapepage.iml | 1 + .idea/php.xml | 13 +- assets/game1.js | 3 +- composer.json | 13 +- composer.lock | 49 ++++++- config/bundles.php | 1 + config/packages/security.yaml | 24 ++-- config/routes.yaml | 6 + migrations/Version20260103210448.php | 33 +++++ src/Game/Controller/GameApiController.php | 24 ++-- src/Game/Controller/GameController.php | 4 +- src/Game/Service/GameResponseService.php | 20 +++ src/Tech/.gitkeep | 0 src/Tech/Controller/ActivationController.php | 43 ++++++ .../Controller/RegistrationController.php | 55 ++++++++ src/Tech/Controller/SecurityController.php | 32 +++++ src/Tech/Entity/User.php | 124 ++++++++++++++++++ src/Tech/Form/RegistrationFormType.php | 48 +++++++ src/Tech/Repository/UserRepository.php | 35 +++++ src/Tech/Service/EmailVerifier.php | 53 ++++++++ src/Tech/Service/UserChecker.php | 26 ++++ symfony.lock | 3 + templates/base.html.twig | 15 ++- templates/game/index.html.twig | 1 + .../registration/confirmation_email.html.twig | 11 ++ .../tech/registration/register.html.twig | 16 +++ templates/tech/security/login.html.twig | 42 ++++++ templates/website/home/index.html.twig | 2 +- 29 files changed, 658 insertions(+), 41 deletions(-) create mode 100644 migrations/Version20260103210448.php create mode 100644 src/Game/Service/GameResponseService.php create mode 100644 src/Tech/.gitkeep create mode 100644 src/Tech/Controller/ActivationController.php create mode 100644 src/Tech/Controller/RegistrationController.php create mode 100644 src/Tech/Controller/SecurityController.php create mode 100644 src/Tech/Entity/User.php create mode 100644 src/Tech/Form/RegistrationFormType.php create mode 100644 src/Tech/Repository/UserRepository.php create mode 100644 src/Tech/Service/EmailVerifier.php create mode 100644 src/Tech/Service/UserChecker.php create mode 100644 templates/tech/registration/confirmation_email.html.twig create mode 100644 templates/tech/registration/register.html.twig create mode 100644 templates/tech/security/login.html.twig diff --git a/.env b/.env index 3a6f8fb..e39ec66 100644 --- a/.env +++ b/.env @@ -25,7 +25,7 @@ APP_SECRET= # # DATABASE_URL="sqlite:///%kernel.project_dir%/var/data_%kernel.environment%.db" # DATABASE_URL="mysql://app:!ChangeMe!@127.0.0.1:3306/app?serverVersion=8.0.32&charset=utf8mb4" -DATABASE_URL="mysql://app:!ChangeMe!@database:3306/app?serverVersion=8.0.32&charset=utf8mb4" +DATABASE_URL="mysql://escapepage:b.0nqrxJ%%2FD%%2ALuf9N@localhost:3306/escapepage?serverVersion=8.0.32&charset=utf8mb4" ###< doctrine/doctrine-bundle ### ###> symfony/messenger ### diff --git a/.idea/escapepage.iml b/.idea/escapepage.iml index beb36aa..c67296b 100644 --- a/.idea/escapepage.iml +++ b/.idea/escapepage.iml @@ -138,6 +138,7 @@ + diff --git a/.idea/php.xml b/.idea/php.xml index 6852c14..89d06de 100644 --- a/.idea/php.xml +++ b/.idea/php.xml @@ -12,7 +12,7 @@ - + @@ -151,14 +151,13 @@ + - - + - + @@ -171,10 +170,10 @@ - + - + \ No newline at end of file diff --git a/assets/game1.js b/assets/game1.js index e6d5ffe..0e9a995 100644 --- a/assets/game1.js +++ b/assets/game1.js @@ -69,6 +69,7 @@ document.addEventListener('DOMContentLoaded', async () => { const topic = cfgEl.dataset.topic; const apiPingUrl = cfgEl.dataset.apiPingUrl; const apiEchoUrl = cfgEl.dataset.apiEchoUrl; + const userId = cfgEl.dataset.userId; if (mercurePublicUrl && topic) { subscribeToMercure(mercurePublicUrl, topic); @@ -88,7 +89,7 @@ document.addEventListener('DOMContentLoaded', async () => { if (apiEchoUrl) { const echo = await fetchJson(apiEchoUrl, { method: 'POST', - body: { hello: 'from game1.js', ts: new Date().toISOString() }, + body: { message: 'from game1.js', ts: new Date().toISOString(), user: userId }, }); console.log('[API][game1] echo →', echo); } else { diff --git a/composer.json b/composer.json index 15f4edf..79b894f 100644 --- a/composer.json +++ b/composer.json @@ -4,7 +4,7 @@ "minimum-stability": "stable", "prefer-stable": true, "require": { - "php": ">=8.5.1", + "php": ">=8.2", "ext-ctype": "*", "ext-iconv": "*", "doctrine/dbal": "^3", @@ -25,8 +25,8 @@ "symfony/http-client": "7.3.*", "symfony/intl": "7.3.*", "symfony/mailer": "7.3.*", + "symfony/mercure-bundle": "^0.3", "symfony/mime": "7.3.*", - "symfony/sendgrid-mailer": "7.3.*", "symfony/monolog-bundle": "^3.0", "symfony/notifier": "7.3.*", "symfony/process": "7.3.*", @@ -34,6 +34,7 @@ "symfony/property-info": "7.3.*", "symfony/runtime": "7.3.*", "symfony/security-bundle": "7.3.*", + "symfony/sendgrid-mailer": "7.3.*", "symfony/serializer": "7.3.*", "symfony/stimulus-bundle": "^2.30", "symfony/string": "7.3.*", @@ -42,11 +43,11 @@ "symfony/ux-turbo": "^2.30", "symfony/validator": "7.3.*", "symfony/web-link": "7.3.*", - "symfony/yaml": "7.3.*", - "twig/extra-bundle": "^2.12|^3.0", - "twig/twig": "^2.12|^3.0", "symfony/webpack-encore-bundle": "^2.1", - "symfony/mercure-bundle": "^0.3" + "symfony/yaml": "7.3.*", + "symfonycasts/verify-email-bundle": "^1.18", + "twig/extra-bundle": "^2.12|^3.0", + "twig/twig": "^2.12|^3.0" }, "config": { "allow-plugins": { diff --git a/composer.lock b/composer.lock index b918f0b..03309f0 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "7b090cdc9768a74bdf1ef02cc14e5d8c", + "content-hash": "663544ea81c4031dcd096a2db68ba5f8", "packages": [ { "name": "composer/semver", @@ -7969,6 +7969,51 @@ ], "time": "2025-12-04T18:07:52+00:00" }, + { + "name": "symfonycasts/verify-email-bundle", + "version": "v1.18.0", + "source": { + "type": "git", + "url": "https://github.com/SymfonyCasts/verify-email-bundle.git", + "reference": "ae0e6228c240a3fa20f2df5528f2fed97b806cab" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/SymfonyCasts/verify-email-bundle/zipball/ae0e6228c240a3fa20f2df5528f2fed97b806cab", + "reference": "ae0e6228c240a3fa20f2df5528f2fed97b806cab", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/config": "^5.4 | ^6.0 | ^7.0 | ^8.0", + "symfony/dependency-injection": "^5.4 | ^6.0 | ^7.0 | ^8.0", + "symfony/deprecation-contracts": "^2.2 | ^3.0", + "symfony/http-kernel": "^5.4 | ^6.0 | ^7.0 | ^8.0", + "symfony/routing": "^5.4 | ^6.0 | ^7.0 | ^8.0" + }, + "require-dev": { + "doctrine/orm": "^2.7", + "doctrine/persistence": "^2.0", + "symfony/framework-bundle": "^5.4 | ^6.0 | ^7.0 | ^8.0", + "symfony/phpunit-bridge": "^5.4 | ^6.0 | ^7.0 | ^8.0" + }, + "type": "symfony-bundle", + "autoload": { + "psr-4": { + "SymfonyCasts\\Bundle\\VerifyEmail\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Simple, stylish Email Verification for Symfony", + "support": { + "issues": "https://github.com/SymfonyCasts/verify-email-bundle/issues", + "source": "https://github.com/SymfonyCasts/verify-email-bundle/tree/v1.18.0" + }, + "time": "2025-11-29T11:53:37+00:00" + }, { "name": "twig/extra-bundle", "version": "v3.22.2", @@ -10502,7 +10547,7 @@ "prefer-stable": true, "prefer-lowest": false, "platform": { - "php": ">=8.5.1", + "php": ">=8.2", "ext-ctype": "*", "ext-iconv": "*" }, diff --git a/config/bundles.php b/config/bundles.php index 003cd9c..be3ef62 100644 --- a/config/bundles.php +++ b/config/bundles.php @@ -15,4 +15,5 @@ return [ Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true], Symfony\WebpackEncoreBundle\WebpackEncoreBundle::class => ['all' => true], Symfony\Bundle\MercureBundle\MercureBundle::class => ['all' => true], + SymfonyCasts\Bundle\VerifyEmail\SymfonyCastsVerifyEmailBundle::class => ['all' => true], ]; diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 367af25..b1d4cb0 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -4,20 +4,28 @@ security: Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto' # https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider providers: - users_in_memory: { memory: null } + app_user_provider: + entity: + class: App\Tech\Entity\User + property: email firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false main: lazy: true - provider: users_in_memory - - # activate different ways to authenticate - # https://symfony.com/doc/current/security.html#the-firewall - - # https://symfony.com/doc/current/security/impersonating_user.html - # switch_user: true + provider: app_user_provider + user_checker: App\Tech\Service\UserChecker + form_login: + login_path: app_login + check_path: app_login + enable_csrf: true + username_parameter: email + password_parameter: password + logout: + path: app_logout + # where to redirect after logout + # target: app_any_route # Easy way to control access for large sections of your site # Note: Only the *first* access control that matches will be used diff --git a/config/routes.yaml b/config/routes.yaml index adbeb26..f0a300d 100644 --- a/config/routes.yaml +++ b/config/routes.yaml @@ -13,6 +13,12 @@ game_controllers: type: attribute prefix: /game +tech_controllers: + resource: + path: ../src/Tech/Controller/ + namespace: App\Tech\Controller + type: attribute + # Uncomment when you add base controllers # base_controllers: # resource: diff --git a/migrations/Version20260103210448.php b/migrations/Version20260103210448.php new file mode 100644 index 0000000..9640451 --- /dev/null +++ b/migrations/Version20260103210448.php @@ -0,0 +1,33 @@ +addSql('CREATE TABLE `user` (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, is_verified TINYINT(1) NOT NULL, UNIQUE INDEX UNIQ_IDENTIFIER_EMAIL (email), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); + $this->addSql('CREATE TABLE messenger_messages (id BIGINT AUTO_INCREMENT NOT NULL, body LONGTEXT NOT NULL, headers LONGTEXT NOT NULL, queue_name VARCHAR(190) NOT NULL, created_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', available_at DATETIME NOT NULL COMMENT \'(DC2Type:datetime_immutable)\', delivered_at DATETIME DEFAULT NULL COMMENT \'(DC2Type:datetime_immutable)\', INDEX IDX_75EA56E0FB7336F0E3BD61CE16BA31DBBF396750 (queue_name, available_at, delivered_at, id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('DROP TABLE `user`'); + $this->addSql('DROP TABLE messenger_messages'); + } +} diff --git a/src/Game/Controller/GameApiController.php b/src/Game/Controller/GameApiController.php index 04da718..57ba364 100644 --- a/src/Game/Controller/GameApiController.php +++ b/src/Game/Controller/GameApiController.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace App\Game\Controller; +use App\Game\Service\GameResponseService; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; @@ -12,6 +13,12 @@ use Symfony\Component\Routing\Annotation\Route; #[Route('/game/api', name: 'game_api_')] final class GameApiController extends AbstractController { + + public function __construct( + protected GameResponseService $gameResponseService) { + + } + #[Route('/ping', name: 'ping', methods: ['GET'])] public function ping(): JsonResponse { @@ -22,27 +29,18 @@ final class GameApiController extends AbstractController ]); } - #[Route('/echo', name: 'echo', methods: ['POST'])] - public function echo(Request $request): JsonResponse + #[Route('/message', name: 'message', methods: ['POST'])] + public function message(Request $request): JsonResponse { $raw = (string) $request->getContent(); $data = null; if ($raw !== '') { - try { - /** @var array|null $decoded */ - $decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR); - $data = $decoded; - } catch (\Throwable $e) { - return $this->json([ - 'ok' => false, - 'error' => 'Invalid JSON: ' . $e->getMessage(), - ], Response::HTTP_BAD_REQUEST); - } + $data = $this->gameResponseService->getGameResponse($raw); } return $this->json([ 'ok' => true, - 'received' => $data, + 'result' => $data, 'ts' => date('c'), ]); } diff --git a/src/Game/Controller/GameController.php b/src/Game/Controller/GameController.php index dbca841..2087205 100644 --- a/src/Game/Controller/GameController.php +++ b/src/Game/Controller/GameController.php @@ -12,6 +12,8 @@ final class GameController extends AbstractController #[Route(path: '', name: 'game')] public function index(): Response { - return $this->render('game/index.html.twig'); + return $this->render('game/index.html.twig', [ + 'user_id' => $this->getUser()?->getId(), + ]); } } diff --git a/src/Game/Service/GameResponseService.php b/src/Game/Service/GameResponseService.php new file mode 100644 index 0000000..d60bdf1 --- /dev/null +++ b/src/Game/Service/GameResponseService.php @@ -0,0 +1,20 @@ +query->get('id'); + + if (null === $id) { + return $this->redirectToRoute('app_register'); + } + + $user = $userRepository->find($id); + + if (null === $user) { + return $this->redirectToRoute('app_register'); + } + + // validate email confirmation link, sets User::isVerified=true and persists + try { + $emailVerifier->handleEmailConfirmation($request, $user); + } catch (VerifyEmailExceptionInterface $exception) { + $this->addFlash('error', $exception->getReason()); + + return $this->redirectToRoute('app_register'); + } + + $this->addFlash('success', 'Your email address has been verified. You can now log in.'); + + return $this->redirectToRoute('app_login'); + } +} diff --git a/src/Tech/Controller/RegistrationController.php b/src/Tech/Controller/RegistrationController.php new file mode 100644 index 0000000..04e84a7 --- /dev/null +++ b/src/Tech/Controller/RegistrationController.php @@ -0,0 +1,55 @@ +createForm(RegistrationFormType::class, $user); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + // encode the plain password + $user->setPassword( + $userPasswordHasher->hashPassword( + $user, + $form->get('plainPassword')->getData() + ) + ); + + $entityManager->persist($user); + $entityManager->flush(); + + // generate a signed url and email it to the user + $emailVerifier->sendEmailConfirmation('app_verify_email', $user, + (new TemplatedEmail()) + ->from('noreply@escapepage.dev') + ->to($user->getEmail()) + ->subject('Please Confirm your Email') + ->htmlTemplate('tech/registration/confirmation_email.html.twig') + ); + + $this->addFlash('success', 'A confirmation email has been sent to your email address.'); + + return $this->redirectToRoute('website_home'); + } + + return $this->render('tech/registration/register.html.twig', [ + 'registrationForm' => $form->createView(), + ]); + } +} diff --git a/src/Tech/Controller/SecurityController.php b/src/Tech/Controller/SecurityController.php new file mode 100644 index 0000000..a7bea2a --- /dev/null +++ b/src/Tech/Controller/SecurityController.php @@ -0,0 +1,32 @@ +getUser()) { + // return $this->redirectToRoute('target_path'); + // } + + // get the login error if there is one + $error = $authenticationUtils->getLastAuthenticationError(); + // last username entered by the user + $lastUsername = $authenticationUtils->getLastUsername(); + + return $this->render('tech/security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]); + } + + #[Route(path: '/logout', name: 'app_logout')] + public function logout(): void + { + throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.'); + } +} diff --git a/src/Tech/Entity/User.php b/src/Tech/Entity/User.php new file mode 100644 index 0000000..47150f0 --- /dev/null +++ b/src/Tech/Entity/User.php @@ -0,0 +1,124 @@ + The user roles + */ + #[ORM\Column] + private array $roles = []; + + /** + * @var string The hashed password + */ + #[ORM\Column] + private ?string $password = null; + + #[ORM\Column(type: 'boolean')] + private bool $isVerified = false; + + public function getId(): ?int + { + return $this->id; + } + + public function getEmail(): ?string + { + return $this->email; + } + + public function setEmail(string $email): static + { + $this->email = $email; + + return $this; + } + + /** + * A visual identifier that represents this user. + * + * @see UserInterface + */ + public function getUserIdentifier(): string + { + return (string) $this->email; + } + + /** + * @see UserInterface + * + * @return list + */ + public function getRoles(): array + { + $roles = $this->roles; + // guarantee every user at least has ROLE_USER + $roles[] = 'ROLE_USER'; + + return array_unique($roles); + } + + /** + * @param list $roles + */ + public function setRoles(array $roles): static + { + $this->roles = $roles; + + return $this; + } + + /** + * @see PasswordAuthenticatedUserInterface + */ + public function getPassword(): ?string + { + return $this->password; + } + + public function setPassword(string $password): static + { + $this->password = $password; + + return $this; + } + + /** + * @see UserInterface + */ + public function eraseCredentials(): void + { + // If you store any temporary, sensitive data on the user, clear it here + // $this->plainPassword = null; + } + + public function isVerified(): bool + { + return $this->isVerified; + } + + public function setIsVerified(bool $isVerified): static + { + $this->isVerified = $isVerified; + + return $this; + } +} diff --git a/src/Tech/Form/RegistrationFormType.php b/src/Tech/Form/RegistrationFormType.php new file mode 100644 index 0000000..9f77432 --- /dev/null +++ b/src/Tech/Form/RegistrationFormType.php @@ -0,0 +1,48 @@ +add('email', EmailType::class) + ->add('plainPassword', RepeatedType::class, [ + 'type' => PasswordType::class, + 'mapped' => false, + 'attr' => ['autocomplete' => 'new-password'], + 'first_options' => ['label' => 'Password'], + 'second_options' => ['label' => 'Repeat Password'], + 'constraints' => [ + new NotBlank([ + 'message' => 'Please enter a password', + ]), + new Length([ + 'min' => 6, + 'minMessage' => 'Your password should be at least {{ limit }} characters', + // max length allowed by Symfony for security reasons + 'max' => 4096, + ]), + ], + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'data_class' => User::class, + ]); + } +} diff --git a/src/Tech/Repository/UserRepository.php b/src/Tech/Repository/UserRepository.php new file mode 100644 index 0000000..3417362 --- /dev/null +++ b/src/Tech/Repository/UserRepository.php @@ -0,0 +1,35 @@ + + */ +class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface +{ + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, User::class); + } + + /** + * Used to upgrade (rehash) the user's password automatically over time. + */ + public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void + { + if (!$user instanceof User) { + throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class)); + } + + $user->setPassword($newHashedPassword); + $this->getEntityManager()->persist($user); + $this->getEntityManager()->flush(); + } +} diff --git a/src/Tech/Service/EmailVerifier.php b/src/Tech/Service/EmailVerifier.php new file mode 100644 index 0000000..a798efc --- /dev/null +++ b/src/Tech/Service/EmailVerifier.php @@ -0,0 +1,53 @@ +verifyEmailHelper->generateSignature( + $verifyEmailRouteName, + (string) $user->getId(), + $user->getEmail(), + ['id' => $user->getId()] + ); + + $context = $email->getContext(); + $context['signedUrl'] = $signatureComponents->getSignedUrl(); + $context['expiresAtMessageKey'] = $signatureComponents->getExpirationMessageKey(); + $context['expiresAtMessageData'] = $signatureComponents->getExpirationMessageData(); + + $email->context($context); + + $this->mailer->send($email); + } + + /** + * @throws VerifyEmailExceptionInterface + */ + public function handleEmailConfirmation(Request $request, User $user): void + { + $this->verifyEmailHelper->validateEmailConfirmation($request->getUri(), (string) $user->getId(), $user->getEmail()); + + $user->setIsVerified(true); + + $this->entityManager->persist($user); + $this->entityManager->flush(); + } +} diff --git a/src/Tech/Service/UserChecker.php b/src/Tech/Service/UserChecker.php new file mode 100644 index 0000000..11a621e --- /dev/null +++ b/src/Tech/Service/UserChecker.php @@ -0,0 +1,26 @@ +isVerified()) { + throw new CustomUserMessageAuthenticationException('Your email address is not verified.'); + } + } + + public function checkPostAuth(UserInterface $user): void + { + } +} diff --git a/symfony.lock b/symfony.lock index cdf33ac..c8acec2 100644 --- a/symfony.lock +++ b/symfony.lock @@ -356,6 +356,9 @@ "./webpack.config.js" ] }, + "symfonycasts/verify-email-bundle": { + "version": "v1.18.0" + }, "twig/extra-bundle": { "version": "v3.21.0" } diff --git a/templates/base.html.twig b/templates/base.html.twig index 242e28f..f80dc10 100644 --- a/templates/base.html.twig +++ b/templates/base.html.twig @@ -14,10 +14,23 @@
+ {% for label, messages in app.flashes %} + {% for message in messages %} +
+ {{ message }} +
+ {% endfor %} + {% endfor %} {% block body %}{% endblock %}