From cff0d5234e40200d6f2fa4f578bc61ad8a8a1621 Mon Sep 17 00:00:00 2001 From: Brock H Caldwell Date: Wed, 9 Jul 2025 23:14:46 -0500 Subject: [PATCH] feat: password reset --- assets/styles/app.css | 8 + composer.json | 1 + composer.lock | 50 ++++- config/bundles.php | 1 + config/packages/doctrine.yaml | 6 + config/packages/reset_password.yaml | 2 + config/packages/security.yaml | 1 + config/security.yaml | 2 +- migrations/Version20250709200956.php | 47 +++++ .../Web/ResetPasswordController.php | 177 ++++++++++++++++++ .../Framework/Entity/ResetPasswordRequest.php | 39 ++++ .../Framework/Form/ChangePasswordForm.php | 62 ++++++ .../Form/ResetPasswordRequestForm.php | 31 +++ .../ResetPasswordRequestRepository.php | 32 ++++ symfony.lock | 12 ++ templates/bare.html.twig | 4 + templates/user/login.html.twig | 16 +- .../user/reset_password/check_email.html.twig | 21 +++ templates/user/reset_password/email.html.twig | 9 + .../user/reset_password/request.html.twig | 32 ++++ templates/user/reset_password/reset.html.twig | 18 ++ 21 files changed, 565 insertions(+), 6 deletions(-) create mode 100644 config/packages/reset_password.yaml create mode 100644 migrations/Version20250709200956.php create mode 100644 src/User/Framework/Controller/Web/ResetPasswordController.php create mode 100644 src/User/Framework/Entity/ResetPasswordRequest.php create mode 100644 src/User/Framework/Form/ChangePasswordForm.php create mode 100644 src/User/Framework/Form/ResetPasswordRequestForm.php create mode 100644 src/User/Framework/Repository/ResetPasswordRequestRepository.php create mode 100644 templates/user/reset_password/check_email.html.twig create mode 100644 templates/user/reset_password/email.html.twig create mode 100644 templates/user/reset_password/request.html.twig create mode 100644 templates/user/reset_password/reset.html.twig diff --git a/assets/styles/app.css b/assets/styles/app.css index 97e096b..cdeaa64 100644 --- a/assets/styles/app.css +++ b/assets/styles/app.css @@ -64,6 +64,14 @@ dialog[data-dialog-target="dialog"][closing] { animation: fade-out 200ms forwards; } +.text-input { + @apply bg-gray-50 text-gray-50 p-1 bg-transparent border-b-2 border-orange-400 +} + +.submit-button { + @apply bg-green-600/40 px-1.5 py-1 w-full rounded-md text-gray-50 backdrop-filter backdrop-blur-sm border-2 border-green-500 hover:bg-green-700/40 +} + .r-tablecell { display: none; } diff --git a/composer.json b/composer.json index ebc69a3..e7a4200 100644 --- a/composer.json +++ b/composer.json @@ -51,6 +51,7 @@ "symfony/ux-turbo": "^2.24", "symfony/ux-twig-component": "^2.24", "symfony/yaml": "7.3.*", + "symfonycasts/reset-password-bundle": "^1.23", "symfonycasts/tailwind-bundle": "^0.10.0", "twig/extra-bundle": "^2.12|^3.0", "twig/twig": "^2.12|^3.0" diff --git a/composer.lock b/composer.lock index cb27ab3..8bcaf23 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": "a659d112da02d5ff1bde5081db62de31", + "content-hash": "f368fdd2e0f36d53131785b857200062", "packages": [ { "name": "1tomany/rich-bundle", @@ -10257,6 +10257,54 @@ ], "time": "2025-04-04T10:10:33+00:00" }, + { + "name": "symfonycasts/reset-password-bundle", + "version": "v1.23.1", + "source": { + "type": "git", + "url": "https://github.com/SymfonyCasts/reset-password-bundle.git", + "reference": "bde42fe5956e0cd523931da886ee41ab660c45b2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/SymfonyCasts/reset-password-bundle/zipball/bde42fe5956e0cd523931da886ee41ab660c45b2", + "reference": "bde42fe5956e0cd523931da886ee41ab660c45b2", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": ">=8.1.10", + "symfony/config": "^5.4 | ^6.0 | ^7.0", + "symfony/dependency-injection": "^5.4 | ^6.0 | ^7.0", + "symfony/deprecation-contracts": "^2.2 | ^3.0", + "symfony/http-kernel": "^5.4 | ^6.0 | ^7.0" + }, + "require-dev": { + "doctrine/annotations": "^1.0", + "doctrine/doctrine-bundle": "^2.8", + "doctrine/orm": "^2.13", + "symfony/framework-bundle": "^5.4 | ^6.0 | ^7.0", + "symfony/phpunit-bridge": "^5.4 | ^6.0 | ^7.0", + "symfony/process": "^6.4 | ^7.0 | ^7.1", + "symfonycasts/internal-test-helpers": "dev-main" + }, + "type": "symfony-bundle", + "autoload": { + "psr-4": { + "SymfonyCasts\\Bundle\\ResetPassword\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Symfony bundle that adds password reset functionality.", + "support": { + "issues": "https://github.com/SymfonyCasts/reset-password-bundle/issues", + "source": "https://github.com/SymfonyCasts/reset-password-bundle/tree/v1.23.1" + }, + "time": "2024-12-09T19:04:36+00:00" + }, { "name": "symfonycasts/tailwind-bundle", "version": "v0.10.0", diff --git a/config/bundles.php b/config/bundles.php index a0d6c65..92ba5e0 100644 --- a/config/bundles.php +++ b/config/bundles.php @@ -20,4 +20,5 @@ return [ Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true], Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle::class => ['all' => true], Symfony\UX\Autocomplete\AutocompleteBundle::class => ['all' => true], + SymfonyCasts\Bundle\ResetPassword\SymfonyCastsResetPasswordBundle::class => ['all' => true], ]; diff --git a/config/packages/doctrine.yaml b/config/packages/doctrine.yaml index 117a846..d199bf9 100644 --- a/config/packages/doctrine.yaml +++ b/config/packages/doctrine.yaml @@ -18,6 +18,12 @@ doctrine: Doctrine\DBAL\Platforms\PostgreSQLPlatform: identity auto_mapping: true mappings: +# App: +# type: attribute +# is_bundle: false +# dir: '%kernel.project_dir%/src/Entity' +# prefix: 'App\Entity' +# alias: App Download: type: attribute is_bundle: false diff --git a/config/packages/reset_password.yaml b/config/packages/reset_password.yaml new file mode 100644 index 0000000..b803694 --- /dev/null +++ b/config/packages/reset_password.yaml @@ -0,0 +1,2 @@ +symfonycasts_reset_password: + request_password_repository: App\User\Framework\Repository\ResetPasswordRequestRepository diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 7a31233..1382856 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -36,6 +36,7 @@ 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: ^/reset-password, roles: PUBLIC_ACCESS } - { path: ^/getting-started, roles: PUBLIC_ACCESS } - { path: ^/register, roles: PUBLIC_ACCESS } - { path: ^/login, roles: PUBLIC_ACCESS } diff --git a/config/security.yaml b/config/security.yaml index d1efd18..fa73fda 100644 --- a/config/security.yaml +++ b/config/security.yaml @@ -43,7 +43,7 @@ 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: ^/register, roles: PUBLIC_ACCESS } + - { path: ^/reset-password, roles: PUBLIC_ACCESS } - { path: ^/login, roles: PUBLIC_ACCESS } - { path: ^/, roles: ROLE_USER } # Or ROLE_ADMIN, ROLE_SUPER_ADMIN, diff --git a/migrations/Version20250709200956.php b/migrations/Version20250709200956.php new file mode 100644 index 0000000..c1c0286 --- /dev/null +++ b/migrations/Version20250709200956.php @@ -0,0 +1,47 @@ +addSql(<<<'SQL' + CREATE TABLE reset_password_request (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, selector VARCHAR(20) NOT NULL, hashed_token VARCHAR(100) NOT NULL, requested_at DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', expires_at DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', INDEX IDX_7CE748AA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB + SQL); + $this->addSql(<<<'SQL' + ALTER TABLE reset_password_request ADD CONSTRAINT FK_7CE748AA76ED395 FOREIGN KEY (user_id) REFERENCES user (id) + SQL); + $this->addSql(<<<'SQL' + ALTER TABLE monitor CHANGE only_future only_future TINYINT(1) NOT NULL + SQL); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql(<<<'SQL' + ALTER TABLE reset_password_request DROP FOREIGN KEY FK_7CE748AA76ED395 + SQL); + $this->addSql(<<<'SQL' + DROP TABLE reset_password_request + SQL); + $this->addSql(<<<'SQL' + ALTER TABLE monitor CHANGE only_future only_future TINYINT(1) DEFAULT 1 NOT NULL + SQL); + } +} diff --git a/src/User/Framework/Controller/Web/ResetPasswordController.php b/src/User/Framework/Controller/Web/ResetPasswordController.php new file mode 100644 index 0000000..9ecee5a --- /dev/null +++ b/src/User/Framework/Controller/Web/ResetPasswordController.php @@ -0,0 +1,177 @@ +createForm(ResetPasswordRequestForm::class); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + /** @var string $email */ + $email = $form->get('email')->getData(); + + return $this->processSendingPasswordResetEmail($email, $mailer, $translator + ); + } + + return $this->render('user/reset_password/request.html.twig', [ + 'requestForm' => $form, + ]); + } + + /** + * Confirmation page after a user has requested a password reset. + */ + #[Route('/check-email', name: 'app_check_email')] + public function checkEmail(): Response + { + // Generate a fake token if the user does not exist or someone hit this page directly. + // This prevents exposing whether or not a user was found with the given email address or not + if (null === ($resetToken = $this->getTokenObjectFromSession())) { + $resetToken = $this->resetPasswordHelper->generateFakeResetToken(); + } + + return $this->render('user/reset_password/check_email.html.twig', [ + 'resetToken' => $resetToken, + ]); + } + + /** + * Validates and process the reset URL that the user clicked in their email. + */ + #[Route('/reset/{token}', name: 'app_reset_password')] + public function reset(Request $request, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator, ?string $token = null): Response + { + if ($token) { + // We store the token in session and remove it from the URL, to avoid the URL being + // loaded in a browser and potentially leaking the token to 3rd party JavaScript. + $this->storeTokenInSession($token); + + return $this->redirectToRoute('app_reset_password'); + } + + $token = $this->getTokenFromSession(); + + if (null === $token) { + throw $this->createNotFoundException('No reset password token found in the URL or in the session.'); + } + + try { + /** @var User $user */ + $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token); + } catch (ResetPasswordExceptionInterface $e) { + $this->addFlash('reset_password_error', sprintf( + '%s - %s', + $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'), + $translator->trans($e->getReason(), [], 'ResetPasswordBundle') + )); + + return $this->redirectToRoute('app_forgot_password_request'); + } + + // The token is valid; allow the user to change their password. + $form = $this->createForm(ChangePasswordForm::class); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + // A password reset token should be used only once, remove it. + $this->resetPasswordHelper->removeResetRequest($token); + + /** @var string $plainPassword */ + $plainPassword = $form->get('plainPassword')->getData(); + + // Encode(hash) the plain password, and set it. + $user->setPassword($passwordHasher->hashPassword($user, $plainPassword)); + $this->entityManager->flush(); + + // The session is cleaned up after the password has been changed. + $this->cleanSessionAfterReset(); + + return $this->redirectToRoute('app_index'); + } + + return $this->render('user/reset_password/reset.html.twig', [ + 'resetForm' => $form, + ]); + } + + private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse + { + $user = $this->entityManager->getRepository(User::class)->findOneBy([ + 'email' => $emailFormData, + ]); + + // Do not reveal whether a user account was found or not. + if (!$user) { + return $this->redirectToRoute('app_check_email'); + } + + try { + $resetToken = $this->resetPasswordHelper->generateResetToken($user); + } catch (ResetPasswordExceptionInterface $e) { + // If you want to tell the user why a reset email was not sent, uncomment + // the lines below and change the redirect to 'app_forgot_password_request'. + // Caution: This may reveal if a user is registered or not. + // + // $this->addFlash('reset_password_error', sprintf( + // '%s - %s', + // $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'), + // $translator->trans($e->getReason(), [], 'ResetPasswordBundle') + // )); + + return $this->redirectToRoute('app_check_email'); + } + + $email = (new TemplatedEmail()) + ->from(new Address('notify@caldwell.digital', 'Torsearch')) + ->to((string) $user->getEmail()) + ->subject('Your password reset request') + ->htmlTemplate('user/reset_password/email.html.twig') + ->context([ + 'resetToken' => $resetToken, + ]) + ; + + $mailer->send($email); + + // Store the token object in session for retrieval in check-email route. + $this->setTokenObjectInSession($resetToken); + + return $this->redirectToRoute('app_check_email'); + } +} diff --git a/src/User/Framework/Entity/ResetPasswordRequest.php b/src/User/Framework/Entity/ResetPasswordRequest.php new file mode 100644 index 0000000..c0d6ca6 --- /dev/null +++ b/src/User/Framework/Entity/ResetPasswordRequest.php @@ -0,0 +1,39 @@ +user = $user; + $this->initialize($expiresAt, $selector, $hashedToken); + } + + public function getId(): ?int + { + return $this->id; + } + + public function getUser(): User + { + return $this->user; + } +} diff --git a/src/User/Framework/Form/ChangePasswordForm.php b/src/User/Framework/Form/ChangePasswordForm.php new file mode 100644 index 0000000..89ad7a5 --- /dev/null +++ b/src/User/Framework/Form/ChangePasswordForm.php @@ -0,0 +1,62 @@ +add('plainPassword', RepeatedType::class, [ + 'type' => PasswordType::class, + 'options' => [ + 'attr' => [ + 'autocomplete' => 'new-password', + 'class' => 'text-input w-full mb-4' + ], + 'label_attr' => [ + 'class' => 'block' + ] + ], + 'first_options' => [ + 'constraints' => [ + new NotBlank([ + 'message' => 'Please enter a password', + ]), + new Length([ + 'min' => 12, + 'minMessage' => 'Your password should be at least {{ limit }} characters', + // max length allowed by Symfony for security reasons + 'max' => 4096, + ]), + new PasswordStrength(), + new NotCompromisedPassword(), + ], + 'label' => 'New password', + ], + 'second_options' => [ + 'label' => 'Repeat Password', + ], + 'invalid_message' => 'The password fields must match.', + // Instead of being set onto the object directly, + // this is read and encoded in the controller + 'mapped' => false, + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([]); + } +} diff --git a/src/User/Framework/Form/ResetPasswordRequestForm.php b/src/User/Framework/Form/ResetPasswordRequestForm.php new file mode 100644 index 0000000..87062ef --- /dev/null +++ b/src/User/Framework/Form/ResetPasswordRequestForm.php @@ -0,0 +1,31 @@ +add('email', EmailType::class, [ + 'attr' => ['autocomplete' => 'email'], + 'constraints' => [ + new NotBlank([ + 'message' => 'Please enter your email', + ]), + ], + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([]); + } +} diff --git a/src/User/Framework/Repository/ResetPasswordRequestRepository.php b/src/User/Framework/Repository/ResetPasswordRequestRepository.php new file mode 100644 index 0000000..0578f55 --- /dev/null +++ b/src/User/Framework/Repository/ResetPasswordRequestRepository.php @@ -0,0 +1,32 @@ + + */ +class ResetPasswordRequestRepository extends ServiceEntityRepository implements ResetPasswordRequestRepositoryInterface +{ + use ResetPasswordRequestRepositoryTrait; + + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, ResetPasswordRequest::class); + } + + /** + * @param User $user + */ + public function createResetPasswordRequest(object $user, \DateTimeInterface $expiresAt, string $selector, string $hashedToken): ResetPasswordRequestInterface + { + return new ResetPasswordRequest($user, $expiresAt, $selector, $hashedToken); + } +} diff --git a/symfony.lock b/symfony.lock index 36f3d40..f116441 100644 --- a/symfony.lock +++ b/symfony.lock @@ -375,6 +375,18 @@ "config/routes/web_profiler.yaml" ] }, + "symfonycasts/reset-password-bundle": { + "version": "1.23", + "recipe": { + "repo": "github.com/symfony/recipes", + "branch": "main", + "version": "1.0", + "ref": "97c1627c0384534997ae1047b93be517ca16de43" + }, + "files": [ + "config/packages/reset_password.yaml" + ] + }, "symfonycasts/tailwind-bundle": { "version": "0.10", "recipe": { diff --git a/templates/bare.html.twig b/templates/bare.html.twig index 9496032..24bf2b1 100644 --- a/templates/bare.html.twig +++ b/templates/bare.html.twig @@ -17,6 +17,10 @@

Torsearch

{% block body %}{% endblock %} +
+ Sign In + v{{ version }} +
diff --git a/templates/user/login.html.twig b/templates/user/login.html.twig index 05d852a..b234959 100644 --- a/templates/user/login.html.twig +++ b/templates/user/login.html.twig @@ -40,14 +40,22 @@ -
- - -
+ +
+
+ + +
+
+ + +
+ Forgot password? +
{% endblock %} diff --git a/templates/user/reset_password/check_email.html.twig b/templates/user/reset_password/check_email.html.twig new file mode 100644 index 0000000..edc112a --- /dev/null +++ b/templates/user/reset_password/check_email.html.twig @@ -0,0 +1,21 @@ +{% extends 'bare.html.twig' %} + +{% block title %}Password Reset Email Sent{% endblock %} + +{% block body %} +
+

Head over to your email

+ +
+

+ If an account matching your email exists, then an email was just sent that contains a + link that you can use to reset your password. This link will expire in + {{ resetToken.expirationMessageKey|trans(resetToken.expirationMessageData, 'ResetPasswordBundle') }}. +

+

+ If you don't receive an email please check your spam folder or + try again. +

+
+
+{% endblock %} diff --git a/templates/user/reset_password/email.html.twig b/templates/user/reset_password/email.html.twig new file mode 100644 index 0000000..824a218 --- /dev/null +++ b/templates/user/reset_password/email.html.twig @@ -0,0 +1,9 @@ +

Hi!

+ +

To reset your password, please visit the following link

+ +{{ url('app_reset_password', {token: resetToken.token}) }} + +

This link will expire in {{ resetToken.expirationMessageKey|trans(resetToken.expirationMessageData, 'ResetPasswordBundle') }}.

+ +

Cheers!

diff --git a/templates/user/reset_password/request.html.twig b/templates/user/reset_password/request.html.twig new file mode 100644 index 0000000..b78ff63 --- /dev/null +++ b/templates/user/reset_password/request.html.twig @@ -0,0 +1,32 @@ +{% extends 'bare.html.twig' %} + +{% block title %}Reset your password — Torsearch{% endblock %} + +{% block body %} +
+

Reset your password

+ +
+ Enter your email address, and we'll send you a link to reset your password. +
+ +
+ {% for flash_error in app.flashes('reset_password_error') %} + + {% endfor %} + + + + + + +
+
+{% endblock %} diff --git a/templates/user/reset_password/reset.html.twig b/templates/user/reset_password/reset.html.twig new file mode 100644 index 0000000..37bc967 --- /dev/null +++ b/templates/user/reset_password/reset.html.twig @@ -0,0 +1,18 @@ +{% extends 'bare.html.twig' %} + +{% block title %}Reset your password — Torsearch{% endblock %} + +{% block body %} +
+

Reset your password

+ +
+ Enter a new password for your account. +
+ + {{ form_start(resetForm) }} + {{ form_row(resetForm.plainPassword) }} + + {{ form_end(resetForm) }} +
+{% endblock %}