Symfony4.4 로그인중인 계정의 암호 재확인 양식 구현

12637 단어 심포니PHP심포니4

도전



패스워드의 변경이나 신용카드의 삭제 등, 시스템상, 중요한 변경을 하는 경우는, 로그인을 하고 있는 상태에서도, 본인 확인을 위해서, 재차, 패스워드를 확인하고 싶다.

밸리데이션을 바라보고 있으면, 목적에 맞는 기능이 있었으므로, 사용해 보았습니다.

TL;DR



이쪽도, 즈바리, 밸리데이션으로서, UserPassword 가 준비되어 있다.

여기를 사용하면 현재 로그인된 계정의 비밀번호와 체크를 해준다는 것.

폼 클래스로서, 다음과 같이 정의해 사용합니다.
컨트롤러와 Twig 템플리도 게재합니다.

App/Form/PasswordChangeType.php
<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;

class PasswordChangeType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('oldPassword', PasswordType::class, [
                'constraints' => [
                    new UserPassword([
                        'message' => '正しいパスワードを設定してください。'
                    ])
                ]
            ])
            ->add('newPassword', RepeatedType::class, [
                'type' => PasswordType::class,
                'required' => true,
                'invalid_message' => '再入力されたパスワードと一致しません。',
                'constraints' => [
                    new NotBlank([
                        'message' => 'パスワードを設定指定ください。',
                    ]),
                    new Length([
                        'min' => 6,
                        'minMessage' => 'パスワードは、{{ limit }}文字以上で設定してください。',
                        // max length allowed by Symfony for security reasons
                        'max' => 100,
                        'maxMessage' => 'パスワードは、{{limit}}文字以内で設定してください。'
                    ]),
                ],
            ])
        ;
    }
}


App/Controller/changePasswordController.php
   /**
     * @Route("/password/change", name="password_change")
     * @param Request $request
     * @param UserPasswordEncoderInterface $passwordEncoder
     * @param Security $security
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function changePassword(int $id, Request $request, UserPasswordEncoderInterface $passwordEncoder, Security $security)
    {
        $email = $security->getUser()->getUsername();
        /** @var User $user */
        $user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email' => $email]);
        $form = $this->createForm(UserPasswordType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user->setPassword(
                $passwordEncoder->encodePassword(
                    $user,
                    $form->get('newPassword')->getData()
                )
            );

            $this->getDoctrine()->getManager()->flush();

            $this->addFlash('success', 'パスワードを変更しました。');
        }

        return $this->render('changePassword/password.html.twig', [
           'passwordForm' => $form->createView()
        ]);
    }

templates/changePassword/password.html.twig
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-4">
                {{ form_start(passwordForm) }}
                {{ form_row(passwordForm.oldPassword, {label:'現在のパスワード'}) }}
                {{ form_row(passwordForm.newPassword.first, {label:'新しいパスワード'}) }}
                {{ form_row(passwordForm.newPassword.second, {label:'新しいパスワード再入力'}) }}
                <button class="btn btn-primary" name="confirm" type="submit"><i class="fas fa-check fa-fw mr-2"></i>変更する</button>
                {{ form_end(passwordForm) }}
            </div>
        </div>
    </div>

다음이 실제 동작

좋은 웹페이지 즐겨찾기