Featured image of post Symfony2でユーザー登録と同時にログインさせる方法

Symfony2でユーザー登録と同時にログインさせる方法

Twitter ツイート Hatena Bookmark ブックマーク

この記事はSymfony2.7を想定して書いています。(おそらく)

最近のブログはSymfony2の話ばかりで、あれなんですが、まあそれだけSymfony2を愛しているということで許してください。
で、よくあるユーザー登録完了後にログインしている状態にしてほしいなんて話はよくあると思います。

Symfony2で実現する場合はこんな感じで対応できます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use HogeBundle\Entity\User;


class SignupController extends SimpleSessionController
{
    public function registerAction(Request $requeset)
    {
        $form = $this->createForm(new UserType());
        $form->handleRequest($request);

        if ($form->isValid()) {
            /** @var User */
            $user = $form->getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();
            $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
            $this->get('security.token_storage')->setToken($token);
            return $this->redirectToRoute("webpage");
        }
}

UsernamePasswordTokenクラスを使ってtokenを作成して、それをsecurity.token_storageの中に入れれば、ログインした状態と同じになります。

非常に簡単ですね。めでたしめでたし。

comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。