-->

Ignore Password when user updates profile with FOS

2020-07-18 09:03发布

问题:

I am using FOSUserBundle and I am trying to create a page that allows a user to update their user profile. The problem I am facing is that my form does not require that the user reenter their password if they don't want to change/update their password. So when a user submits the form with an empty password the database will be updated with an empty string, and the user will not be able to log in.

How can I get my form to ignore updating the password field if it is not set? Below is the code I am using.

$user = $this->get('security.context')->getToken()->getUser();

//user form has email and repeating password fields    
$userForm = $this->createForm(new UserFormType(), $user);

if ($request->getMethod() == 'POST') {
   $userForm->bindRequest($request);

   if($userForm->isValid()){
      //this will be be empty string in the database if the user does not enter a password
      $user->setPlainPassword($userForm->getData()->getPassword());
      $em->flush();
   }
}

I have tried a few things such as the following, but this is still empty because the bindRequest sets the empty password to the user

if($userForm->getData()->getPassword())
   $user->setPlainPassword($userForm->getData()->getPassword());

I have also tried, but this results in a similar situation and causes an unneeded query

if($userForm->getData()->getPassword())
   $user->setPlainPassword($userForm->getData()->getPassword());
else
   $user->setPlainPassword($user->getPlainPassword());

Are there any elegant ways to handle this use case?

回答1:

I think you should reconsider if this is in fact a good use case. Should users be able to edit other users passwords? At our institution we do not allow even the highest level admin to perform this task.

If a user needs their password changed we let them handle that themselves. If they have forgotten their password we allow them to retrieve it via email. If they need assistance with adjusting their email we allow our admins to assist users then. But all password updating and creation is done soley by the user.

I think it is great that FOSUserBundle makes it so difficult to do otherwise but if you must DonCallisto seems to have a good solution.



回答2:

The problem is that you bind a form to a User Object before controls upon password. Let's analyze your snippet of code.

Do the following

$user = $this->get('security.context')->getToken()->getUser();

will load an existing user into a User Object.
Now you "build" a form with that data and if receive a post, you'll take the posted data into the previous object

$userForm = $this->createForm(new UserFormType(), $user);

if ($request->getMethod() == 'POST') {
   $userForm->bindRequest($request);

So, onto bindRequest you have alredy lost previous password into the object (obviously not into database yet) if that was leave empty. Every control from now on is useless.

A solution in that case is to manually verify value of form's field directly into $request object before binding it to the underlying object.
You can do this with this simple snippet of code

$postedValues = $request->request->get('formName');

Now you have to verify that password value is filled

if($postedValues['plainPassword']) { ... }

where plainPassword I suppose to be the name of the field we're interesting in.

If you find that this field contain a value (else branch) you haven't to do anything.
Otherwise you have to retrieve original password from User Object and set it into $request corrisponding value.
(update) Otherwise you may retrieve password from User Object but since that password is stored with an hased valued, you can't put it into the $request object because it will suffer from hashing again.
What you could do - i suppose - is an array_pop directly into $request object and put away the field that messes all the things up (plainPassword) Now that you had done those things, you can bind posted data to underlying object.

Another solution (maybe better because you move some business logic away from controller) is to use prePersist hook, but is more conceptually advanced. If you want to explore that solution, you can read this about form events



回答3:

<?php

class User
{
    public function setPassword($password)
    {
        if (false == empty($password)) {
            $this->password = $password;
        }
    }
}

This will only update the password on the user if it isn't empty.



回答4:

I have found a simple hack to get rid of the "Enter a password" form error. Manualy set a dummy plainPassword in the user entity. After form validation just reset it before you flush the entity.

<?php

    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AppBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Customer entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        
        $postedValues = $request->request->get('appbundle_user');
        
/* HERE */ $entity->setPlainPassword('dummy'); // hack to avoid the "enter password" error
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
/* AND HERE */ $entity->setPlainPassword(''); // hack to avoid the "enter password" error
            $em->flush();

            return $this->redirect($this->generateUrl('customer_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }