简体   繁体   中英

Symfony3: How to delete current user and redirect to home?

I'm working on Delete User functionality. An user loged can delete his account, and then he will be redirected to home page.

This is implemented using an AJAX call , with the following action in Controller:

/**
 * @Route("settings/delete-user/{userId}", name="delete-user")
 */
public function deleteUserAction(Request $request,
                                 $userId,
                                 EntityManagerInterface $em,
                                 TranslatorInterface $translator,
                                 FormErrorCollector $errorCollector,
                                 SessionInterface $session,
                                 TokenStorageInterface $tokenStorage)
{
    $user = $this->getUser();
    $deleteUserForm = $this->createForm(ConfirmPasswordType::class);

    $deleteUserForm->handleRequest($request);
    if($request->isXmlHttpRequest() && $user->getId() == $userId){

        if($deleteUserForm->isValid()){

            $em->remove($user);
            $em->flush();

            $session->invalidate(0);

            return new JsonResponse(array(
                'status' => 'success',
                'message' => $translator->trans('USER_DELETED_SUCCESS')
            ));
        }else{

            $errors = $errorCollector->getErrors($deleteUserForm);

            return new JsonResponse(array(
                'status' => 'failure',
                'errors' => $errors
            ));
        }

    }else{

        return new JsonResponse('FORBIDEN');

    }
}

Actually, user is deleted from Database, and then, appears a Modal with the confirmation and a link to return to homepage. The problem is that when the user click on the link, Symfony shows this error:

You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.

Obviously, Symfony is unable to find the user since I just deleted it. I tried to remove the Session and TokenStorage hoping that the problem would be fixed, but not at all.

So, how can I redirect the deleted user to the homepage?

UPDATE

If you're using Symfony 3.3 or above, you can use Autowire. An improvement of the answer will be:

1.- Add use for TokenStorageInterface:

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

2.- Pass TokenStorageInterface as parameter to your DeleteAction:

public function deleteUserAction(Request $request,$userId,TokenStorageInterface$tokenStorage)
{

3.- Clear token and session:

$tokenStorage->setToken(null);
$session->invalidate();

You can also use autowire with session service, using:

use Symfony\Component\HttpFoundation\Session\SessionInterface;

You can try to logout the user manually before deleting with $this->get('security.token_storage')->setToken(null); , eg

/**
 * @Route("settings/delete-user/{userId}", name="delete-user")
 */
public function deleteUserAction(Request $request,
                                 $userId,
                                 EntityManagerInterface $em,
                                 TranslatorInterface $translator,
                                 FormErrorCollector $errorCollector,
                                 SessionInterface $session,
                                 TokenStorageInterface $tokenStorage)
{
    $user = $this->getUser();
    $deleteUserForm = $this->createForm(ConfirmPasswordType::class);

    $deleteUserForm->handleRequest($request);
    if($request->isXmlHttpRequest() && $user->getId() == $userId){

        if($deleteUserForm->isValid()){

            // force manual logout of logged in user    
            $this->get('security.token_storage')->setToken(null);

            $em->remove($user);
            $em->flush();

            $session->invalidate(0);

            return new JsonResponse(array(
                'status' => 'success',
                'message' => $translator->trans('USER_DELETED_SUCCESS')
            ));
        }else{

            $errors = $errorCollector->getErrors($deleteUserForm);

            return new JsonResponse(array(
                'status' => 'failure',
                'errors' => $errors
            ));
        }

    }else{

        return new JsonResponse('FORBIDEN');

    }
}

If you are using the remember me feature, make sure to reat the answer to Log user out in Symfony 2 application when "remember me" is enabled as well, as things get a little bit more tricky.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM