From caeec305094094a818827e538fbfc8e55aa19374 Mon Sep 17 00:00:00 2001
From: thisfro
Date: Sun, 2 May 2021 14:45:17 +0200
Subject: [PATCH] add reset password functionality
---
composer.json | 1 +
composer.lock | 53 +++++-
config/bundles.php | 1 +
config/packages/reset_password.yaml | 2 +
migrations/Version20210502123444.php | 42 +++++
src/Controller/ResetPasswordController.php | 171 ++++++++++++++++++
src/Entity/ResetPasswordRequest.php | 45 +++++
src/Form/ChangePasswordFormType.php | 49 +++++
src/Form/ResetPasswordRequestFormType.php | 30 +++
.../ResetPasswordRequestRepository.php | 31 ++++
symfony.lock | 12 ++
.../reset_password/check_email.html.twig | 11 ++
templates/reset_password/email.html.twig | 9 +
templates/reset_password/request.html.twig | 22 +++
templates/reset_password/reset.html.twig | 12 ++
templates/security/login.html.twig | 3 +
16 files changed, 493 insertions(+), 1 deletion(-)
create mode 100644 config/packages/reset_password.yaml
create mode 100644 migrations/Version20210502123444.php
create mode 100644 src/Controller/ResetPasswordController.php
create mode 100644 src/Entity/ResetPasswordRequest.php
create mode 100644 src/Form/ChangePasswordFormType.php
create mode 100644 src/Form/ResetPasswordRequestFormType.php
create mode 100644 src/Repository/ResetPasswordRequestRepository.php
create mode 100644 templates/reset_password/check_email.html.twig
create mode 100644 templates/reset_password/email.html.twig
create mode 100644 templates/reset_password/request.html.twig
create mode 100644 templates/reset_password/reset.html.twig
diff --git a/composer.json b/composer.json
index b3aef36..b3b84a7 100644
--- a/composer.json
+++ b/composer.json
@@ -27,6 +27,7 @@
"symfony/validator": "5.2.*",
"symfony/webpack-encore-bundle": "^1.11",
"symfony/yaml": "5.2.*",
+ "symfonycasts/reset-password-bundle": "^1.7",
"symfonycasts/verify-email-bundle": "^1.4",
"twig/extra-bundle": "^2.12|^3.0",
"twig/intl-extra": "^3.3",
diff --git a/composer.lock b/composer.lock
index 07b7beb..6d67edd 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": "4e8e54f0634c09e272233b3cc1fcf27c",
+ "content-hash": "17c34311a2696b4e9d060e5d8855bf05",
"packages": [
{
"name": "composer/package-versions-deprecated",
@@ -6959,6 +6959,57 @@
],
"time": "2021-03-06T07:59:01+00:00"
},
+ {
+ "name": "symfonycasts/reset-password-bundle",
+ "version": "v1.7.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/SymfonyCasts/reset-password-bundle.git",
+ "reference": "368a4f64fc4f8174234fc91f9b22d5016257211b"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/SymfonyCasts/reset-password-bundle/zipball/368a4f64fc4f8174234fc91f9b22d5016257211b",
+ "reference": "368a4f64fc4f8174234fc91f9b22d5016257211b",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.2.5",
+ "symfony/config": "^4.4 | ^5.0",
+ "symfony/dependency-injection": "^4.4 | ^5.0",
+ "symfony/deprecation-contracts": "^2.2",
+ "symfony/http-kernel": "^4.4 | ^5.0"
+ },
+ "conflict": {
+ "doctrine/orm": "<2.7",
+ "symfony/framework-bundle": "<4.4",
+ "symfony/http-foundation": "<4.4"
+ },
+ "require-dev": {
+ "doctrine/doctrine-bundle": "^2.0.3",
+ "doctrine/orm": "^2.7",
+ "friendsofphp/php-cs-fixer": "^2.17",
+ "symfony/framework-bundle": "^4.4 | ^5.0",
+ "symfony/phpunit-bridge": "^5.0",
+ "vimeo/psalm": "^4.3"
+ },
+ "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.7.0"
+ },
+ "time": "2021-04-12T17:29:47+00:00"
+ },
{
"name": "symfonycasts/verify-email-bundle",
"version": "v1.4.0",
diff --git a/config/bundles.php b/config/bundles.php
index abe9596..4ddfac0 100644
--- a/config/bundles.php
+++ b/config/bundles.php
@@ -15,4 +15,5 @@ return [
EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle::class => ['all' => true],
Symfony\WebpackEncoreBundle\WebpackEncoreBundle::class => ['all' => true],
Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
+ SymfonyCasts\Bundle\ResetPassword\SymfonyCastsResetPasswordBundle::class => ['all' => true],
];
diff --git a/config/packages/reset_password.yaml b/config/packages/reset_password.yaml
new file mode 100644
index 0000000..796ff0c
--- /dev/null
+++ b/config/packages/reset_password.yaml
@@ -0,0 +1,2 @@
+symfonycasts_reset_password:
+ request_password_repository: App\Repository\ResetPasswordRequestRepository
diff --git a/migrations/Version20210502123444.php b/migrations/Version20210502123444.php
new file mode 100644
index 0000000..a7261ed
--- /dev/null
+++ b/migrations/Version20210502123444.php
@@ -0,0 +1,42 @@
+addSql('CREATE SEQUENCE reset_password_request_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
+ $this->addSql('CREATE TABLE reset_password_request (id INT NOT NULL, user_id INT NOT NULL, selector VARCHAR(20) NOT NULL, hashed_token VARCHAR(100) NOT NULL, requested_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, expires_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id))');
+ $this->addSql('CREATE INDEX IDX_7CE748AA76ED395 ON reset_password_request (user_id)');
+ $this->addSql('COMMENT ON COLUMN reset_password_request.requested_at IS \'(DC2Type:datetime_immutable)\'');
+ $this->addSql('COMMENT ON COLUMN reset_password_request.expires_at IS \'(DC2Type:datetime_immutable)\'');
+ $this->addSql('ALTER TABLE reset_password_request ADD CONSTRAINT FK_7CE748AA76ED395 FOREIGN KEY (user_id) REFERENCES "user" (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
+ $this->addSql('ALTER TABLE offering ALTER zip_code DROP DEFAULT');
+ $this->addSql('ALTER TABLE offering ALTER description DROP DEFAULT');
+ }
+
+ public function down(Schema $schema) : void
+ {
+ // this down() migration is auto-generated, please modify it to your needs
+ $this->addSql('CREATE SCHEMA public');
+ $this->addSql('DROP SEQUENCE reset_password_request_id_seq CASCADE');
+ $this->addSql('DROP TABLE reset_password_request');
+ $this->addSql('ALTER TABLE offering ALTER zip_code SET DEFAULT 0');
+ $this->addSql('ALTER TABLE offering ALTER description SET DEFAULT \'Lorem ipsum dolor\'');
+ }
+}
diff --git a/src/Controller/ResetPasswordController.php b/src/Controller/ResetPasswordController.php
new file mode 100644
index 0000000..556d95f
--- /dev/null
+++ b/src/Controller/ResetPasswordController.php
@@ -0,0 +1,171 @@
+resetPasswordHelper = $resetPasswordHelper;
+ }
+
+ /**
+ * Display & process form to request a password reset.
+ */
+ #[Route('', name: 'app_forgot_password_request')]
+ public function request(Request $request, MailerInterface $mailer): Response
+ {
+ $form = $this->createForm(ResetPasswordRequestFormType::class);
+ $form->handleRequest($request);
+
+ if ($form->isSubmitted() && $form->isValid()) {
+ return $this->processSendingPasswordResetEmail(
+ $form->get('email')->getData(),
+ $mailer
+ );
+ }
+
+ return $this->render('reset_password/request.html.twig', [
+ 'requestForm' => $form->createView(),
+ ]);
+ }
+
+ /**
+ * Confirmation page after a user has requested a password reset.
+ */
+ #[Route('/check-email', name: 'app_check_email')]
+ public function checkEmail(): Response
+ {
+ // We prevent users from directly accessing this page
+ if (null === ($resetToken = $this->getTokenObjectFromSession())) {
+ return $this->redirectToRoute('app_forgot_password_request');
+ }
+
+ return $this->render('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, UserPasswordEncoderInterface $passwordEncoder, 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 {
+ $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
+ } catch (ResetPasswordExceptionInterface $e) {
+ $this->addFlash('reset_password_error', sprintf(
+ 'There was a problem validating your reset request - %s',
+ $e->getReason()
+ ));
+
+ return $this->redirectToRoute('app_forgot_password_request');
+ }
+
+ // The token is valid; allow the user to change their password.
+ $form = $this->createForm(ChangePasswordFormType::class);
+ $form->handleRequest($request);
+
+ if ($form->isSubmitted() && $form->isValid()) {
+ // A password reset token should be used only once, remove it.
+ $this->resetPasswordHelper->removeResetRequest($token);
+
+ // Encode the plain password, and set it.
+ $encodedPassword = $passwordEncoder->encodePassword(
+ $user,
+ $form->get('plainPassword')->getData()
+ );
+
+ $user->setPassword($encodedPassword);
+ $this->getDoctrine()->getManager()->flush();
+
+ // The session is cleaned up after the password has been changed.
+ $this->cleanSessionAfterReset();
+
+ return $this->redirectToRoute('user_page');
+ }
+
+ return $this->render('reset_password/reset.html.twig', [
+ 'resetForm' => $form->createView(),
+ ]);
+ }
+
+ private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer): RedirectResponse
+ {
+ $user = $this->getDoctrine()->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(
+ // 'There was a problem handling your password reset request - %s',
+ // $e->getReason()
+ // ));
+
+ return $this->redirectToRoute('app_check_email');
+ }
+
+ $email = (new TemplatedEmail())
+ ->from(new Address('no-reply@example.com', 'plantex no-reply'))
+ ->to($user->getEmail())
+ ->subject('Your password reset request')
+ ->htmlTemplate('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/Entity/ResetPasswordRequest.php b/src/Entity/ResetPasswordRequest.php
new file mode 100644
index 0000000..6f7faed
--- /dev/null
+++ b/src/Entity/ResetPasswordRequest.php
@@ -0,0 +1,45 @@
+user = $user;
+ $this->initialize($expiresAt, $selector, $hashedToken);
+ }
+
+ public function getId(): ?int
+ {
+ return $this->id;
+ }
+
+ public function getUser(): object
+ {
+ return $this->user;
+ }
+}
diff --git a/src/Form/ChangePasswordFormType.php b/src/Form/ChangePasswordFormType.php
new file mode 100644
index 0000000..9603af3
--- /dev/null
+++ b/src/Form/ChangePasswordFormType.php
@@ -0,0 +1,49 @@
+add('plainPassword', RepeatedType::class, [
+ 'type' => PasswordType::class,
+ 'first_options' => [
+ '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,
+ ]),
+ ],
+ '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/Form/ResetPasswordRequestFormType.php b/src/Form/ResetPasswordRequestFormType.php
new file mode 100644
index 0000000..15eea22
--- /dev/null
+++ b/src/Form/ResetPasswordRequestFormType.php
@@ -0,0 +1,30 @@
+add('email', EmailType::class, [
+ 'constraints' => [
+ new NotBlank([
+ 'message' => 'Please enter your email',
+ ]),
+ ],
+ ])
+ ;
+ }
+
+ public function configureOptions(OptionsResolver $resolver): void
+ {
+ $resolver->setDefaults([]);
+ }
+}
diff --git a/src/Repository/ResetPasswordRequestRepository.php b/src/Repository/ResetPasswordRequestRepository.php
new file mode 100644
index 0000000..5a428b7
--- /dev/null
+++ b/src/Repository/ResetPasswordRequestRepository.php
@@ -0,0 +1,31 @@
+
+ An email has been sent that contains a link that you can click 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/reset_password/email.html.twig b/templates/reset_password/email.html.twig
new file mode 100644
index 0000000..824a218
--- /dev/null
+++ b/templates/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/reset_password/request.html.twig b/templates/reset_password/request.html.twig
new file mode 100644
index 0000000..6905b79
--- /dev/null
+++ b/templates/reset_password/request.html.twig
@@ -0,0 +1,22 @@
+{% extends 'base.html.twig' %}
+
+{% block title %}Reset your password{% endblock %}
+
+{% block body %}
+ {% for flashError in app.flashes('reset_password_error') %}
+ {{ flashError }}
+ {% endfor %}
+ Reset your password
+
+ {{ form_start(requestForm) }}
+ {{ form_row(requestForm.email) }}
+
+
+ Enter your email address and we we will send you a
+ link to reset your password.
+
+
+
+
+ {{ form_end(requestForm) }}
+{% endblock %}
\ No newline at end of file
diff --git a/templates/reset_password/reset.html.twig b/templates/reset_password/reset.html.twig
new file mode 100644
index 0000000..799aa10
--- /dev/null
+++ b/templates/reset_password/reset.html.twig
@@ -0,0 +1,12 @@
+{% extends 'base.html.twig' %}
+
+{% block title %}Reset your password{% endblock %}
+
+{% block body %}
+ Reset your password
+
+ {{ form_start(resetForm) }}
+ {{ form_row(resetForm.plainPassword) }}
+
+ {{ form_end(resetForm) }}
+{% endblock %}
diff --git a/templates/security/login.html.twig b/templates/security/login.html.twig
index 8d6ff2e..eb6fa42 100644
--- a/templates/security/login.html.twig
+++ b/templates/security/login.html.twig
@@ -22,6 +22,9 @@