Symfony 4 - 在连接时删除自己的用户帐户的良好做法

时间:2018-03-21 08:21:20

标签: symfony session logout symfony4

我希望我的用户能够删除自己的用户帐户。我创建了SecurityController,其中有3个函数loginlogoutdeleteUser。当我删除数据库中的当前用户时,会出现此错误:

  

您无法从不包含标识符的EntityUserProvider刷新用户。必须使用Doctrine映射的自己的标识符序列化用户对象。

当我删除其他用户时,它可以正常工作,因为他没有连接。 我是否必须序列化用户并通过服务传递,注销用户然后在服务中删除它?或者我可以在控制器中清除PHP会话,但我不知道如何使用我知道它从版本4开始就改变了。

<?php

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;

use App\Entity\User;
use App\Form\UserType;

class SecurityController extends Controller
{
  /**
   * @Route("/createAdmin", name="create_admin")
   */
    public function createAdminUser(Request $request, UserPasswordEncoderInterface $passwordEncoder)
    {
      $usersRepo = $this->getDoctrine()->getRepository(User::class);
      $uCount = $usersRepo->countAllUsers();

      if ($uCount == 0)
      {
        $user = new User();
        $form = $this->createForm(UserType::class, $user, array(
          'is_fresh_install' => true,
        ));

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            // Encode the password
            $password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);

            // save the User
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            // Do what you want here before redirecting the user

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

        return $this->render('security/register_admin_user.html.twig', array(
          'form' => $form->createView(),
        ));
      } else {
        if ($this->getUser())
        {
          return $this->redirectToRoute('user_account');
        } else {
          return $this->redirectToRoute('login');
        }
      }
    }

    /**
     * @Route("/login", name="login")
     */
    public function login(Request $request, AuthenticationUtils $authUtils)
    {
      $usersRepo = $this->getDoctrine()->getRepository(User::class);
      $uCount = $usersRepo->countAllUsers();

      if ($uCount == 0)
      {
        return $this->redirectToRoute('create_admin');
      } else {
        $error = $authUtils->getLastAuthenticationError();
        $lastUsername = $authUtils->getLastUsername();

        return $this->render('security/login.html.twig', array(
         'last_username' => $lastUsername,
         'error'         => $error,
        ));
      }
    }

    /**
     * @Route("/logout", name="logout")
     */
    public function logout()
    {

    }

    /**
     * @Route("/delete_user/{id}", name="delete_user")
     */
    public function deleteUser($id)
    {
      $em = $this->getDoctrine()->getManager();
      $usrRepo = $em->getRepository(User::class);

      $user = $usrRepo->find($id);
      $em->remove($user);
      $em->flush();

      return $this->redirectToRoute('user_registration');

    }

}

3 个答案:

答案 0 :(得分:1)

我发现这样做也是一个很好的解决方案,这是一个可以接受的答案,但是您也可以简单地将用户重定向到注销路径。 在Symfony 4.4中,这对我没有任何问题

答案 1 :(得分:0)

我认为你必须序列化用户并通过服务传递它。只需检查以前的版本,你就会发现问题。

答案 2 :(得分:0)

解决方案:

在使用此方法删除DB中的用户条目之前,您必须清除会话:

<?php

use Symfony\Component\HttpFoundation\Session\Session;

// In your deleteUser function...

      $currentUserId = $this->getUser()->getId();
      if ($currentUserId == $id)
      {
        $session = $this->get('session');
        $session = new Session();
        $session->invalidate();
      }

我不知道为什么$this->get('session')->invalidate();不能直接起作用...如果有人知道:)

相关问题