0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【symfony4】ユーザー認証の実装

Last updated at Posted at 2020-09-10

UserEntityの作成

UserInterface,\Serializableを継承

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @UniqueEntity("email")
 */
class User implements UserInterface,\Serializable
{
     /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;
    
    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $password;

    /**
     * @ORM\Column(type="integer")
     */
    private $userRoll;
    
    /**
     * @ORM\Column(type="string", length=255,unique=true)
     */
    // ユニークキーの設定
    private $email;

    public function serialize()
    {
        return serialize([
            $this->id,
            $this->email,
            $this->password,
            $this->userRoll,
            ]);
    }

    public function unserialize($serialized)
    {
        list($this->id,
            $this->email,
            $this->password,
            $this->userRoll
            ) = unserialize($serialized,['allowed_classes'=>false]);
    }

    public function eraseCredentials()
    {}

    public function getSalt()
    {
      return null;
    }

    
    public function getRoles()
    {
        return [$this->getUserRoll()];
    }

    public function getUsername()
    {}
}

コントローラー

ユーザー作成

   /**
     * ユーザー登録
     * 
     * @param Request $req
     * @param UserPasswordEncoderInterface $passwordEncoder
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function create(Request $req,UserPasswordEncoderInterface $passwordEncoder)
    {
        $form = $this->createForm(UserType::class, $user);

        $form->handleRequest($req);

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

            $password = $passwordEncoder->encodePassword($user, $user->getPassword());
            $user->setPassword($password);

            $manager = $this->getDoctrine()->getManager();
            $manager->persist($user);
            $manager->flush();


            return $this->redirectToRoute(
                'admin_user_find' , [
                    'id' => $user->getId(),
                ]);
        }
        return $this->render($this->twig_base . 'create.html.twig', [
            'form' => $form->createView()
        ]);
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?