简体   繁体   English

Symfony3:如何删除当前用户并重定向到首页?

[英]Symfony3: How to delete current user and redirect to home?

I'm working on Delete User functionality. 我正在使用“ Delete User功能。 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: 这是通过AJAX call实现的,在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: 问题是,当用户单击链接时,Symfony显示此错误:

You cannot refresh a user from the EntityUserProvider that does not contain an identifier. 您无法从不包含标识符的EntityUserProvider刷新用户。 The user object has to be serialized with its own identifier mapped by Doctrine. 用户对象必须使用Doctrine映射的自己的标识符进行序列化。

Obviously, Symfony is unable to find the user since I just deleted it. 显然,Symfony无法删除用户,因为我刚刚删除了该用户。 I tried to remove the Session and TokenStorage hoping that the problem would be fixed, but not at all. 我试图删除SessionTokenStorage希望问题可以解决,但根本不能解决。

So, how can I redirect the deleted user to the homepage? 那么,如何将已删除的用户重定向到首页?

UPDATE UPDATE

If you're using Symfony 3.3 or above, you can use Autowire. 如果您使用的是Symfony 3.3或更高版本,则可以使用自动装配。 An improvement of the answer will be: 答案的改进将是:

1.- Add use for TokenStorageInterface: 1.-为TokenStorageInterface添加用途:

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

2.- Pass TokenStorageInterface as parameter to your DeleteAction: 2.-将TokenStorageInterface作为参数传递给DeleteAction:

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

3.- Clear token and session: 3.-清除令牌和会话:

$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); 您可以尝试手动注销用户,然后再通过$this->get('security.token_storage')->setToken(null);进行删除$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. 如果您使用的是“记住我”功能,请确保在启用“记住我”的情况下也能在Symfony 2应用程序中退出“注销用户”的答案,因为事情变得有些棘手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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