簡體   English   中英

Symfony 4按用戶名更改密碼 - 電子郵件不能為空

[英]Symfony 4 change password by username - email can not be null

介紹

我一直試圖弄清楚如何創建一個由用戶名值控制的重置密碼表單。

錯誤

Path        Message                           Invalid value     Violation
data.email  This value should not be blank.   null 



ConstraintViolation {#945 ▼
  -message: "This value should not be blank."
  -messageTemplate: "This value should not be blank."
  -parameters: [▶]
  -plural: null
  -root: Form {#620 ▶}
  -propertyPath: "data.email"
  -invalidValue: null
  -constraint: NotBlank {#477 …}
  -code: "c1051bb4-d103-4f74-8988-acbcafc7fdc3"
  -cause: null
}

期待什么

使用新密碼更新我的用戶對象。

我的守則

ForgotController.php

我知道這可能不是獲取密碼的正確方法,但是搜索Symfony 4忘記密碼表單會顯示與我的版本無關的symfony2.4帖子

    <?php
        namespace App\Controller\User;

        use App\Entity\User;
        use App\Form\User\ChangePasswordType;
        use App\Repository\UserRepository;
        use Symfony\Bundle\FrameworkBundle\Controller\Controller;
        use Symfony\Component\HttpFoundation\Request;
        use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

        class ForgotController extends Controller
        {
            public function forgot(Request $request, UserPasswordEncoderInterface $encoder)
            {
                $entityManager = $this->getDoctrine()->getManager();

                $changePassword = $request->request->get('change_password');

                $username = $changePassword['username'];
                $password = $changePassword['plainPassword']['first'];

                $user       = $entityManager->getRepository(User::class)->findBy(['username' => $username]);
                $userEntity = new User();

                if (!$user) {
                    $this->addFlash('danger', 'User not found for '. $username);
                }

                $form = $this->createForm(ChangePasswordType::class, $userEntity);
                $form->handleRequest($request);

                if ($form->isSubmitted() && $form->isValid()) {
                    try {
                        $pass = $encoder->encodePassword($userEntity, $password);

                        $userEntity->setPassword($pass);
                        $entityManager->flush();

                        $this->addFlash('success', 'Password Changed!');
                    } catch (Exception $e) {
                        $this->addFlash('danger', 'Something went skew-if. Please try again.');
                    }

                    return $this->redirectToRoute('login');
                }

                return $this->render('user/forgot.html.twig', array('form' => $form->createView()));
            }
        }

ChangePasswordType.php

<?php
    namespace App\Form\User;

    use App\Entity\User;
    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\Extension\Core\Type\TextType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;

    class ChangePasswordType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('username', TextType::class)
                ->add('plainPassword', RepeatedType::class, array(
                'type' => PasswordType::class,
                'first_options' => array('label' => 'New Password'),
                'second_options' => array('label' => 'Repeat New Password')
            ));
        }

        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => User::class
            ));
        }
    }

forgot.html.twig

{% include 'builder/header.html.twig' %}

<div class="user-container" id="user-content">
    {% block body %}
        {% include 'builder/notices.html.twig' %}

        <div class="user-container">
            <i class="fas fa-user-edit fa-5x"></i>
        </div>

        <hr />

        {{ form_start(form) }}
            {{ form_row(form.username, { 'attr': {'class': 'form-control'} }) }}
            {{ form_row(form.plainPassword.first, { 'attr': {'class': 'form-control'} }) }}
            {{ form_row(form.plainPassword.second, { 'attr': {'class': 'form-control'} }) }}

            <div class="register-btn-container">
                <button class="btn btn-danger" id="return-to-dash-btn" type="button">Cancel!</button>
                <button class="btn btn-primary" type="submit">Update!</button>
            </div>
        {{ form_end(form) }}
    {% endblock %}
</div>

{% include 'builder/footer.html.twig' %}

我不確定為什么甚至會提到電子郵件,除非它試圖將新用戶插入數據庫但它不應該嘗試基於我的控制器執行此操作? 如何添加用戶名標識的忘記密碼表單?

由於您的更改密碼表單只需要兩個字段,我們將使用數組而不是用戶實體。 需要稍微調整一下ChangePasswordType:

    // ChangePasswordType
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            //'data_class' => User::class
        ));
    }

這是一個有效的忘記行動:

    public function forgot(
        Request $request, 
        UserPasswordEncoderInterface $encoder, 
        UserRepository $userRepository)
    {

        $userInfo = ['username' => null, 'plainPassword' => null];

        $form = $this->createForm(ChangePasswordType::class, $userInfo);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $userInfo = $form->getData();
            $username = $userInfo['username'];
            $plainPassword = $userInfo['plainPassword'];

            $user = $userRepository->findOneBy(['username' => $username]);
            if ($user === null) {
                $this->addFlash('danger', 'Invalid username');
                return $this->redirectToRoute('forgot');
            }
            $password = $encoder->encodePassword($user, $plainPassword);

            $user->setPassword($password);
            $userRepository->flush();

            return $this->redirectToRoute('login');
        }

        return $this->render('user/forgot.html.twig', array('form' => $form->createView()));
    }

注入UserRepository可以擺脫所有的學說廢話。 這里有一點需要注意,我會回來的。

我們構建userInfo數組,讓表單處理做到這一點。 如果我們不需要,我們真的不想直接從請求對象獲取屬性。

然后我們得到我們的實際用戶實體進行更新。 注意使用findOneBy而不是findBy。 我們檢查以確保用戶名有效。 如果你真的想得到想象,那么你可以在表單中添加一個驗證約束來自動進行檢查。

我擺脫了所有的try / catch東西。 它只是弄亂你的代碼。 到目前為止,如果拋出異常,那么它確實是異常的,並且可以由默認的異常處理程序處理。

你得到了密碼編碼器的東西。

然后我使用$ userRepository-> flush();而不是$ entityManager-> flush(); 開箱即用的存儲庫上沒有flush方法,所以你需要添加一個:

// UserRepository
public function flush()
{
    $this->_em->flush();
}

我個人喜歡只處理存儲庫而不是實體管理器。 但是如果需要,你可以回去注入經理而不是存儲庫。 你的來電。

並且如評論中所述,您確實希望添加一些安全性以防止用戶更改其他用戶密碼。

按照下面的方式實現一些東西 - 我已經像模板和路由一樣留下了一些東西。 這只是為了幫助你。

表單1:ForgottenUserType - 使用僅輸入用戶名/電子郵件並提交

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add("username", null, array(
        "label" => "Email",
        "attr" => array(
            "class" => "form-control",
            "id" => "basic-url",
            "placeholder" => "Email address for your account"
        ),
        "constraints" => array(
            new Email(array("message" => "Invalid Email"))
        )
    ));
}

表格2:ChangePasswordFormType - 用戶輸入並重復新密碼。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    parent::buildForm($builder, $options);
    $builder
        ->add('plainPassword', RepeatedType::class, array(
            'type'              => PasswordType::class,
            'required'          => false,
            'first_options'     => array('label' => 'New password'),
            'second_options'    => array('label' => 'Confirm new password'),
            'invalid_message' => 'The password fields must match.',
        ))
        ;
}

Controller:ResetPasswordController - 處理表單1的用戶查找請求和表單2的密碼重置請求:

<?php
namespace App\Controller\User;

use App\Entity\User;
use App\Form\User\ChangePasswordType;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class ResetPasswordController extends Controller
{
    /**
     * Action for when a user has forgotten their password, to request ForgottenUser form
     *
     * @param Request $request
     */
    public function requestAction(Request $request)
    {
        $tmpUser = new User();
        $entityManager = $this->getDoctrine()->getManager();

        $form = $this->createForm(ForgottenUserType::class, $tmpUser);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $user = $entityManager->getRepository(User::class)->findBy(['username' => $tmpUser->getUsername()]);

            if ($user) {

                //check and set token
                if (null === $user->getConfirmationToken()) {
                    /** @var $tokenGenerator TokenGeneratorInterface */
                    $token = md5(uniqid($user->getUsername(), true)); //some unique token (you can create a nicer token generator in standalone class with a service)
                    $user->setConfirmationToken($token);
                    $user->setPasswordRequestedAt(new \DateTime());
                    $em->persist($user);
                    $em->flush();)

                    $this->addFlash('Info', 'If user is found, you will receive an email with further instructions.');

                    //send email using swiftmailer & include url with token
                }


            } else {
                //return to requestAction.
            }
        }

        //request template contains the ForgottenUserType form
        return $this->render(":path/to/template:request.html.twig", array(
            "forgotten_form" => $form->createView()
        ));

    }

    /**
     * Reset user password.
     *
     * @param Request $request
     * @param $token
     */
    public function resetAction(Request $request, $token)
    {
        $entityManager = $this->getDoctrine()->getManager();
        $user = $entityManager->getRepository(User::class)->findBy(['confirmationToken' => $token]); 

        if (null === $user) {                        
            return new RedirectResponse($this->generateUrl('resetting_request')); //to requestAction above. / create route
        }        

        $form = $this->createForm(ChangePasswordFormType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user->SetConfirmationToken(null);
            $user->setPasswordRequestedAt(null);
            $entityManager->persist($user);
            $entityManager->flush()

            $this->addFlash("success", "Your password has been reset, log in now.");
            $url = $this->generateUrl('app.login'); //route to login page
            $response = new RedirectResponse($url);
            return $response;            
        }

        //reset template contains the ChangePasswordFormType form
        return $this->render(':path/to/forgottenpasswordtemplate:reset.html.twig', array(
            'token' => $token,
            'form' => $form->createView(),
        ));

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM