From 5e98f0992ef698f6522a34218b4ed7abc2b66dc9 Mon Sep 17 00:00:00 2001 From: Vincent Chalamon Date: Tue, 19 May 2020 15:24:00 +0200 Subject: [PATCH] Add reset password --- .env | 4 + .github/workflows/ci.yml | 7 + behat.yml.dist | 9 +- composer.json | 3 + composer.lock | 238 +++++++++++++++++- config/bundles.php | 1 + config/packages/mailer.yaml | 3 + config/packages/reset_password.yaml | 2 + config/packages/security.yaml | 1 + docker-compose.override.yml.dist | 7 +- docker-compose.yml | 3 + features/user/reset_password.feature | 64 +++++ fixtures/resetPasswordRequest.yaml | 3 + .../User/Security/ResetPasswordController.php | 189 ++++++++++++++ .../Faker/Provider/DateTimeProvider.php | 13 + src/Entity/ResetPasswordRequest.php | 40 +++ src/Form/Type/ChangePasswordFormType.php | 47 ++++ .../Type/ResetPasswordRequestFormType.php | 32 +++ src/Migrations/Version20200519114430.php | 36 +++ .../ResetPasswordRequestRepository.php | 46 ++++ symfony.lock | 30 +++ templates/base.html.twig | 2 + .../reset_password/check_email.html.twig | 9 + templates/reset_password/email.html.twig | 11 + templates/reset_password/request.html.twig | 21 ++ templates/reset_password/reset.html.twig | 12 + templates/user/login.html.twig | 5 + tests/Behat/ResetPasswordContext.php | 38 +++ 28 files changed, 866 insertions(+), 10 deletions(-) create mode 100644 config/packages/mailer.yaml create mode 100644 config/packages/reset_password.yaml create mode 100644 features/user/reset_password.feature create mode 100644 fixtures/resetPasswordRequest.yaml create mode 100644 src/Controller/User/Security/ResetPasswordController.php create mode 100644 src/DataFixtures/Faker/Provider/DateTimeProvider.php create mode 100644 src/Entity/ResetPasswordRequest.php create mode 100644 src/Form/Type/ChangePasswordFormType.php create mode 100644 src/Form/Type/ResetPasswordRequestFormType.php create mode 100644 src/Migrations/Version20200519114430.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 create mode 100644 tests/Behat/ResetPasswordContext.php diff --git a/.env b/.env index 907caec3..09a2fd56 100644 --- a/.env +++ b/.env @@ -35,3 +35,7 @@ APP_SECRET=782bb8b0aeb47de4ea870794e79d82cd # IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml DATABASE_URL=postgresql://resop:postgrespwd@postgres/resop?serverVersion=11&charset=utf8 ###< doctrine/doctrine-bundle ### + +###> symfony/mailer ### +MAILER_DSN=smtp://mailcatcher:25 +###< symfony/mailer ### diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8b6b1170..313f4710 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,7 @@ env: APP_DEBUG: 0 DATABASE_SERVER_VERSION: 11 # update service "postgresql" if this value change PANTHER_CHROME_DRIVER_BINARY: /usr/bin/chromedriver + MAILER_DSN: smtp://localhost:25 jobs: php: @@ -32,6 +33,11 @@ jobs: - 5432:5432 # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 + mailcatcher: + image: tophfr/mailcatcher:0.6.5 + ports: + - 1080:80 + - 1025:25 steps: - name: set DATABASE_URL environment variable @@ -131,6 +137,7 @@ jobs: - name: Run Behat tests run: | bin/post-install-test.sh + sed -i 's#http://mailcatcher#http://localhost:1080#' behat.yml.dist vendor/bin/behat --format=progress --out=std --format=junit --out=var/behat --tags '~@javascript' if: always() diff --git a/behat.yml.dist b/behat.yml.dist index 44791dda..51d23c3c 100644 --- a/behat.yml.dist +++ b/behat.yml.dist @@ -2,18 +2,22 @@ default: suites: default: contexts: + - Alex\MailCatcher\Behat\MailCatcherContext - App\Tests\Behat\CoverageContext - App\Tests\Behat\DatabaseContext - App\Tests\Behat\FixturesContext - App\Tests\Behat\OrganizationPlanningContext + - App\Tests\Behat\ResetPasswordContext - App\Tests\Behat\SecurityContext - App\Tests\Behat\TraversingContext - App\Tests\Behat\UserPlanningContext - Behat\MinkExtension\Context\MinkContext - PantherExtension\Context\PantherContext - - PantherExtension\Context\WaitContext: + - PantherExtension\Context\WaitContext extensions: - PantherExtension\Extension\PantherExtension: ~ + Alex\MailCatcher\Behat\MailCatcherExtension\Extension: + url: http://mailcatcher + purge_before_scenario: true Behat\MinkExtension: browser_name: chrome default_session: symfony @@ -28,3 +32,4 @@ default: kernel: environment: test debug: true + PantherExtension\Extension\PantherExtension: ~ diff --git a/composer.json b/composer.json index 9fd7ed57..d9bc71f9 100644 --- a/composer.json +++ b/composer.json @@ -22,6 +22,7 @@ "symfony/form": "5.*", "symfony/framework-bundle": "5.*", "symfony/intl": "5.*", + "symfony/mailer": "5.0.*", "symfony/monolog-bundle": "^3.5", "symfony/orm-pack": "^1.0", "symfony/security-bundle": "5.0.*", @@ -32,10 +33,12 @@ "symfony/validator": "5.*", "symfony/webpack-encore-bundle": "^1.7", "symfony/yaml": "5.*", + "symfonycasts/reset-password-bundle": "^1.1", "twig/cache-extension": "^1.4", "twig/intl-extra": "^3.0" }, "require-dev": { + "alexandresalome/mailcatcher": "dev-master", "behat/behat": "^3.6", "dama/doctrine-test-bundle": "^6.3", "escapestudios/symfony2-coding-standard": "^3.11", diff --git a/composer.lock b/composer.lock index 5dc57a6d..9c767fa3 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": "10236f253fb789a4d6ab379c547effaf", + "content-hash": "1484706dd252a5724a38741f81bafebd", "packages": [ { "name": "beberlei/assert", @@ -1370,6 +1370,64 @@ ], "time": "2020-03-27T11:06:43+00:00" }, + { + "name": "egulias/email-validator", + "version": "2.1.17", + "source": { + "type": "git", + "url": "https://github.com/egulias/EmailValidator.git", + "reference": "ade6887fd9bd74177769645ab5c474824f8a418a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/ade6887fd9bd74177769645ab5c474824f8a418a", + "reference": "ade6887fd9bd74177769645ab5c474824f8a418a", + "shasum": "" + }, + "require": { + "doctrine/lexer": "^1.0.1", + "php": ">=5.5", + "symfony/polyfill-intl-idn": "^1.10" + }, + "require-dev": { + "dominicsayers/isemail": "^3.0.7", + "phpunit/phpunit": "^4.8.36|^7.5.15", + "satooshi/php-coveralls": "^1.0.1" + }, + "suggest": { + "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Egulias\\EmailValidator\\": "EmailValidator" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Eduardo Gulias Davis" + } + ], + "description": "A library for validating emails against several RFCs", + "homepage": "https://github.com/egulias/EmailValidator", + "keywords": [ + "email", + "emailvalidation", + "emailvalidator", + "validation", + "validator" + ], + "time": "2020-02-13T22:36:52+00:00" + }, { "name": "friendsofsymfony/jsrouting-bundle", "version": "2.5.4", @@ -4230,6 +4288,87 @@ ], "time": "2020-03-27T16:56:45+00:00" }, + { + "name": "symfony/mailer", + "version": "v5.0.8", + "source": { + "type": "git", + "url": "https://github.com/symfony/mailer.git", + "reference": "b473af272a4375d832d060b2bc9aac185536443d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mailer/zipball/b473af272a4375d832d060b2bc9aac185536443d", + "reference": "b473af272a4375d832d060b2bc9aac185536443d", + "shasum": "" + }, + "require": { + "egulias/email-validator": "^2.1.10", + "php": "^7.2.5", + "psr/log": "~1.0", + "symfony/event-dispatcher": "^4.4|^5.0", + "symfony/mime": "^4.4|^5.0", + "symfony/service-contracts": "^1.1|^2" + }, + "conflict": { + "symfony/http-kernel": "<4.4" + }, + "require-dev": { + "symfony/amazon-mailer": "^4.4|^5.0", + "symfony/google-mailer": "^4.4|^5.0", + "symfony/http-client-contracts": "^1.1|^2", + "symfony/mailchimp-mailer": "^4.4|^5.0", + "symfony/mailgun-mailer": "^4.4|^5.0", + "symfony/messenger": "^4.4|^5.0", + "symfony/postmark-mailer": "^4.4|^5.0", + "symfony/sendgrid-mailer": "^4.4|^5.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Mailer\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Mailer Component", + "homepage": "https://symfony.com", + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-04-28T17:58:55+00:00" + }, { "name": "symfony/mime", "version": "v5.0.7", @@ -6770,6 +6909,52 @@ ], "time": "2020-03-30T11:42:42+00:00" }, + { + "name": "symfonycasts/reset-password-bundle", + "version": "v1.1.1", + "source": { + "type": "git", + "url": "https://github.com/SymfonyCasts/reset-password-bundle.git", + "reference": "ac39892a5de861209cb7491e056a77a0b872e87d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/SymfonyCasts/reset-password-bundle/zipball/ac39892a5de861209cb7491e056a77a0b872e87d", + "reference": "ac39892a5de861209cb7491e056a77a0b872e87d", + "shasum": "" + }, + "require": { + "php": "^7.2", + "symfony/config": "^4.4 | ^5.0", + "symfony/dependency-injection": "^4.4 | ^5.0", + "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.16", + "symfony/framework-bundle": "^4.4 | ^5.0", + "symfony/phpunit-bridge": "^5.0", + "vimeo/psalm": "^3.8" + }, + "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.", + "time": "2020-04-18T00:37:02+00:00" + }, { "name": "twig/cache-extension", "version": "1.4.0", @@ -7146,6 +7331,44 @@ } ], "packages-dev": [ + { + "name": "alexandresalome/mailcatcher", + "version": "dev-master", + "target-dir": "Alex/MailCatcher", + "source": { + "type": "git", + "url": "https://github.com/alexandresalome/mailcatcher.git", + "reference": "8caef3fabdf0a0a2dc674391c93a7a70d315150d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/alexandresalome/mailcatcher/zipball/8caef3fabdf0a0a2dc674391c93a7a70d315150d", + "reference": "8caef3fabdf0a0a2dc674391c93a7a70d315150d", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": ">=5.3.3", + "symfony/dom-crawler": "~2.3 || ~3.0 || ~4.0 || ~5.0" + }, + "require-dev": { + "behat/behat": "~3.0", + "phpunit/phpunit": "~4.6", + "swiftmailer/swiftmailer": "~5.0" + }, + "type": "library", + "autoload": { + "psr-0": { + "Alex\\MailCatcher": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A library to access MailCatcher", + "time": "2019-11-24T12:45:26+00:00" + }, { "name": "behat/behat", "version": "v3.6.1", @@ -10558,22 +10781,22 @@ }, { "name": "symfony/maker-bundle", - "version": "v1.14.6", + "version": "v1.18.0", "source": { "type": "git", "url": "https://github.com/symfony/maker-bundle.git", - "reference": "bc4df88792fbaaeb275167101dc714218475db5f" + "reference": "b38c75be880b152ab55cef6cd52bf882d2b6518e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/maker-bundle/zipball/bc4df88792fbaaeb275167101dc714218475db5f", - "reference": "bc4df88792fbaaeb275167101dc714218475db5f", + "url": "https://api.github.com/repos/symfony/maker-bundle/zipball/b38c75be880b152ab55cef6cd52bf882d2b6518e", + "reference": "b38c75be880b152ab55cef6cd52bf882d2b6518e", "shasum": "" }, "require": { "doctrine/inflector": "^1.2", "nikic/php-parser": "^4.0", - "php": "^7.0.8", + "php": "^7.1.3", "symfony/config": "^3.4|^4.0|^5.0", "symfony/console": "^3.4|^4.0|^5.0", "symfony/dependency-injection": "^3.4|^4.0|^5.0", @@ -10636,7 +10859,7 @@ "type": "tidelift" } ], - "time": "2020-03-04T13:57:29+00:00" + "time": "2020-05-15T18:51:23+00:00" }, { "name": "symfony/panther", @@ -11182,6 +11405,7 @@ "aliases": [], "minimum-stability": "stable", "stability-flags": { + "alexandresalome/mailcatcher": 20, "roave/security-advisories": 20 }, "prefer-stable": false, diff --git a/config/bundles.php b/config/bundles.php index 0bb13597..1eab456d 100644 --- a/config/bundles.php +++ b/config/bundles.php @@ -23,4 +23,5 @@ Misd\PhoneNumberBundle\MisdPhoneNumberBundle::class => ['all' => true], Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true], FOS\JsRoutingBundle\FOSJsRoutingBundle::class => ['all' => true], + SymfonyCasts\Bundle\ResetPassword\SymfonyCastsResetPasswordBundle::class => ['all' => true], ]; diff --git a/config/packages/mailer.yaml b/config/packages/mailer.yaml new file mode 100644 index 00000000..56a650d8 --- /dev/null +++ b/config/packages/mailer.yaml @@ -0,0 +1,3 @@ +framework: + mailer: + dsn: '%env(MAILER_DSN)%' diff --git a/config/packages/reset_password.yaml b/config/packages/reset_password.yaml new file mode 100644 index 00000000..796ff0cb --- /dev/null +++ b/config/packages/reset_password.yaml @@ -0,0 +1,2 @@ +symfonycasts_reset_password: + request_password_repository: App\Repository\ResetPasswordRequestRepository diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 1d712f10..f549aa33 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -37,5 +37,6 @@ security: access_control: - { path: ^/user/new$, roles: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY } + - { path: ^/reset-password, roles: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/, roles: ROLE_USER } - { path: ^/organizations/, roles: ROLE_ORGANIZATION } diff --git a/docker-compose.override.yml.dist b/docker-compose.override.yml.dist index ccb02ede..9998f3e7 100644 --- a/docker-compose.override.yml.dist +++ b/docker-compose.override.yml.dist @@ -36,4 +36,9 @@ services: volumes: - postgres-data:/var/lib/postgresql/data:rw # ports: -# - '5432:5432' # Uncomment if you need to access the DB from your host +# - '5432:5432' # Uncomment if you need to access the DB from your host + +# mailcatcher: +# ports: +# - '1080:80' # Uncomment if you need to access the mails interface from your host +# - '1025:25' # Uncomment if you need to send mails from your host diff --git a/docker-compose.yml b/docker-compose.yml index 23bac4f6..9f27b814 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -90,3 +90,6 @@ services: - NODE_ENV=dev volumes: - ./:/srv + + mailcatcher: + image: tophfr/mailcatcher:0.6.5 diff --git a/features/user/reset_password.feature b/features/user/reset_password.feature new file mode 100644 index 00000000..147e3625 --- /dev/null +++ b/features/user/reset_password.feature @@ -0,0 +1,64 @@ +Feature: + In order to reset my password, + As a user, + I must be able to request a token and reset my password. + + Scenario: As a user, I cannot request a token + Given I am authenticated as "admin201@resop.com" + When I go to "/reset-password" + Then I should be on "/" + And the response status code should be 200 + + Scenario: As anonymous, I can request a token + When I go to "/" + Then I should be on "/login" + And the response status code should be 200 + And I should see "Mot de passe oublié ?" + When I follow "Mot de passe oublié ?" + Then I should be on "/reset-password" + And the response status code should be 200 + When I fill in "reset_password_request_form[emailAddress]" with "admin201@resop.com" + And I press "Envoyer le lien" + Then I should be on "/reset-password/check-email" + And I should see "Un email vous a été envoyé contenant un lien vous permettant de réinitialiser mon mot de passe. Ce lien expirera dans 1 heure(s)." + And 1 mail should be sent + + Scenario: As anonymous, I cannot request a token if I already requested one in the configured time + Given I am on "/reset-password" + When I fill in "reset_password_request_form[emailAddress]" with "admin203@resop.com" + And I press "Envoyer le lien" + Then I should be on "/reset-password" + And I should see "Une erreur est survenue durant la réinitialisation de votre mot de passe - You have already requested a reset password email. Please check your email or try again soon." + And 0 mail should be sent + + Scenario: As a user, I cannot reset my password using a valid token + Given I am authenticated as "admin201@resop.com" + When I go to the reset password page of "admin201@resop.com" + Then I should be on "/" + And the response status code should be 200 + + Scenario: As anonymous, I can reset my password using a valid token + When I go to the reset password page of "admin201@resop.com" + Then I should be on "/reset-password/reset" + And the response status code should be 200 + And I should see "Mot de passe" + And I should see "Confirmation" + When I fill in the following: + | change_password_form[plainPassword][first] | test | + | change_password_form[plainPassword][second] | test | + And I press "Réinitialiser mon mot de passe" + Then I should be on "/login" + And the response status code should be 200 + And I should see "Votre mot de passe a été mis à jour avec succès." + When I fill in the following: + | user_login[identifier] | 990001A | + | user_login[password] | test | + And I press "Je me connecte" + Then I should be on "/" + And the response status code should be 200 + And I should see "NIVOL : 990001A" + + Scenario: As anonymous, I cannot reset my password using a invalid token + When I go to "/reset-password/reset/invalid" + Then I should be on "/reset-password" + And the response status code should be 200 diff --git a/fixtures/resetPasswordRequest.yaml b/fixtures/resetPasswordRequest.yaml new file mode 100644 index 00000000..de1696c7 --- /dev/null +++ b/fixtures/resetPasswordRequest.yaml @@ -0,0 +1,3 @@ +App\Entity\ResetPasswordRequest: + ResetPasswordRequest.jane_doe: + __construct: ['@User.jane_doe', '', '102', '01GgM0q3lRa6pM2V/S+mZrJpACowPjKnNBlw4ipasOs='] diff --git a/src/Controller/User/Security/ResetPasswordController.php b/src/Controller/User/Security/ResetPasswordController.php new file mode 100644 index 00000000..7ed22072 --- /dev/null +++ b/src/Controller/User/Security/ResetPasswordController.php @@ -0,0 +1,189 @@ +resetPasswordHelper = $resetPasswordHelper; + } + + /** + * Display & process form to request a password reset. + * + * @Route("", name="app_forgot_password_request") + */ + public function request(Request $request, MailerInterface $mailer): Response + { + if ($this->getUser() instanceof User) { + return $this->redirectToRoute('app_user_home'); + } + + $form = $this->createForm(ResetPasswordRequestFormType::class); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + return $this->processSendingPasswordResetEmail( + $form->get('emailAddress')->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 + { + if ($this->getUser() instanceof User) { + return $this->redirectToRoute('app_user_home'); + } + + // We prevent users from directly accessing this page + if (!$this->canCheckEmail()) { + return $this->redirectToRoute('app_forgot_password_request'); + } + + return $this->render('reset_password/check_email.html.twig', [ + 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(), + ]); + } + + /** + * 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 ($this->getUser() instanceof User) { + return $this->redirectToRoute('app_user_home'); + } + + 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('error', sprintf( + 'Une erreur est survenue durant la réinitialisation de votre mot de passe - %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(); + $this->addFlash('success', 'Votre mot de passe a été mis à jour avec succès.'); + + return $this->redirectToRoute('app_login'); + } + + 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([ + 'emailAddress' => $emailFormData, + ]); + + // Marks that you are allowed to see the app_check_email page. + $this->setCanCheckEmailInSession(); + + // 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) { + $this->addFlash('error', sprintf( + 'Une erreur est survenue durant la réinitialisation de votre mot de passe - %s', + $e->getReason() + )); + + return $this->redirectToRoute('app_forgot_password_request'); + } + + $email = (new TemplatedEmail()) + ->from(new Address('noreply@resop.com', 'Réserve opérationnelle - Croix-Rouge Française')) + ->to($user->getEmailAddress()) + ->subject('Mot de passe oublié') + ->htmlTemplate('reset_password/email.html.twig') + ->context([ + 'resetToken' => $resetToken, + 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(), + ]) + ; + + $mailer->send($email); + + return $this->redirectToRoute('app_check_email'); + } +} diff --git a/src/DataFixtures/Faker/Provider/DateTimeProvider.php b/src/DataFixtures/Faker/Provider/DateTimeProvider.php new file mode 100644 index 00000000..82c9cda4 --- /dev/null +++ b/src/DataFixtures/Faker/Provider/DateTimeProvider.php @@ -0,0 +1,13 @@ +user = $user; + $this->initialize($expiresAt, $selector, $hashedToken); + } + + public function getUser(): object + { + return $this->user; + } +} diff --git a/src/Form/Type/ChangePasswordFormType.php b/src/Form/Type/ChangePasswordFormType.php new file mode 100644 index 00000000..7eddd2b5 --- /dev/null +++ b/src/Form/Type/ChangePasswordFormType.php @@ -0,0 +1,47 @@ +add('plainPassword', RepeatedType::class, [ + 'type' => PasswordType::class, + 'first_options' => [ + 'constraints' => [ + new NotBlank(), + new Length([ + // max length allowed by Symfony for security reasons + 'max' => 4096, + ]), + ], + 'label' => 'Mot de passe', + ], + 'second_options' => [ + 'label' => 'Confirmation', + ], + 'invalid_message' => 'Les mots de passe ne correspondent pas.', + // 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/Type/ResetPasswordRequestFormType.php b/src/Form/Type/ResetPasswordRequestFormType.php new file mode 100644 index 00000000..dc88446b --- /dev/null +++ b/src/Form/Type/ResetPasswordRequestFormType.php @@ -0,0 +1,32 @@ +add('emailAddress', EmailType::class, [ + 'constraints' => [ + new NotBlank([ + 'message' => 'Please enter your email', + ]), + ], + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([]); + } +} diff --git a/src/Migrations/Version20200519114430.php b/src/Migrations/Version20200519114430.php new file mode 100644 index 00000000..aedde14c --- /dev/null +++ b/src/Migrations/Version20200519114430.php @@ -0,0 +1,36 @@ +abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.'); + + $this->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 DEFAULT 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 users (id) NOT DEFERRABLE INITIALLY IMMEDIATE'); + } + + public function down(Schema $schema): void + { + $this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.'); + + $this->addSql('DROP SEQUENCE reset_password_request_id_seq CASCADE'); + $this->addSql('DROP TABLE reset_password_request'); + } +} diff --git a/src/Repository/ResetPasswordRequestRepository.php b/src/Repository/ResetPasswordRequestRepository.php new file mode 100644 index 00000000..53e5de12 --- /dev/null +++ b/src/Repository/ResetPasswordRequestRepository.php @@ -0,0 +1,46 @@ + {% endif %} + {{ include('misc/flash-messages.html.twig') }} + {% block body '' %} diff --git a/templates/reset_password/check_email.html.twig b/templates/reset_password/check_email.html.twig new file mode 100644 index 00000000..83a9ae93 --- /dev/null +++ b/templates/reset_password/check_email.html.twig @@ -0,0 +1,9 @@ +{% extends 'base.html.twig' %} + +{% block title %}Réinitialiser mon mot de passe{% endblock %} + +{% block body %} +

Un email vous a été envoyé contenant un lien vous permettant de réinitialiser mon mot de passe. + Ce lien expirera dans {{ tokenLifetime|date('g') }} heure(s).

+

Si vous ne recevez pas cet email, veuillez vérifier vos spams ou réessayez.

+{% endblock %} diff --git a/templates/reset_password/email.html.twig b/templates/reset_password/email.html.twig new file mode 100644 index 00000000..7330234f --- /dev/null +++ b/templates/reset_password/email.html.twig @@ -0,0 +1,11 @@ +

Bonjour !

+ +

+ Pour réinitialiser votre mot de passe, veuillez aller sur + + {{ url('app_reset_password', {token: resetToken.token}) }} + + Ce lien expirera dans {{ tokenLifetime|date('g') }} heure(s).. +

+ +

Cordialement

diff --git a/templates/reset_password/request.html.twig b/templates/reset_password/request.html.twig new file mode 100644 index 00000000..95ede9cc --- /dev/null +++ b/templates/reset_password/request.html.twig @@ -0,0 +1,21 @@ +{% extends 'base.html.twig' %} + +{% block title %}Réinitialiser mon mot de passe{% endblock %} + +{% block body %} + {% for flashError in app.flashes('reset_password_error') %} + + {% endfor %} +

Réinitialiser mon mot de passe

+ + {{ form_start(requestForm) }} + {{ form_row(requestForm.emailAddress) }} +
+ + Veuillez saisir votre adresse email afin d'obtenir un lien de réinitialisation de votre mot de passe. + +
+ + + {{ form_end(requestForm) }} +{% endblock %} diff --git a/templates/reset_password/reset.html.twig b/templates/reset_password/reset.html.twig new file mode 100644 index 00000000..5bcade89 --- /dev/null +++ b/templates/reset_password/reset.html.twig @@ -0,0 +1,12 @@ +{% extends 'base.html.twig' %} + +{% block title %}Réinitialiser mon mot de passe{% endblock %} + +{% block body %} +

Réinitialiser mon mot de passe

+ + {{ form_start(resetForm) }} + {{ form_row(resetForm.plainPassword) }} + + {{ form_end(resetForm) }} +{% endblock %} diff --git a/templates/user/login.html.twig b/templates/user/login.html.twig index d15719b0..ecc0e045 100644 --- a/templates/user/login.html.twig +++ b/templates/user/login.html.twig @@ -10,6 +10,8 @@ {% include '_navbar.html.twig' with {navbarClass: 'navbar-dark'} %}
+ {{ include('misc/flash-messages.html.twig') }} +