3

すでにログインしているユーザーをメイン ページにリダイレクトする方法はありますか? たとえば、Cookie を使用しているユーザーや「リメンバーミー」を使用しているユーザーなどは?

「loginController」でこれを試しましたが、機能しません

public function loginAction()
{
    $request = $this->getRequest();
    $session = $request->getSession();
   // $user = new Usuario();

    // get the login error if there is one
    if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
        $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    } else {
        $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
    }
    $securityContext = $this->container->get('security.context');
    if( $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') ){
       $this->redirect($this->generateUrl('MonsePanelBundle_homepage'));
    }
    return $this->render('UsuariosBundle:Security:login.html.twig', array(
        // last username entered by the user
        'last_username' => $session->get(SecurityContext::LAST_USERNAME),
        'error'         => $error,
    ));
}

他の同様の質問をすべて読みましたが、これまでのところ運がありません...

念のため、これは私のsecurity.ymlです...

security:
encoders:
   Monse\UsuariosBundle\Entity\Usuario:
        algorithm: sha512
        encode-as-base64: true
        iterations: 10

role_hierarchy:
    ROLE_ADMIN: [ROLE_USER]
    ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

providers:
    user_db:
        entity: { class: Monse\UsuariosBundle\Entity\Usuario, property: usuario }

firewalls:
    main:
        pattern: /.*
        provider: user_db
        form_login:
            login_path: /login
            check_path: /login_check
            remember_me: true
            default_target_path: /panel
        logout:
            path: /logout
            target: /login
        remember_me:
            key: MiClaveSegura
            lifetime: 1800
            path: /.*
            domain: ~
        security: true
        anonymous: true
access_control:
    - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/panel, roles: [ROLE_SUPER_ADMIN, ROLE_ADMIN, ROLE_USER] }
4

3 に答える 3

3

すべてのアクションの前にコントローラーでメソッドを実行する必要がある場合があり、場合によっては複数のコントローラーでメソッドを実行する必要があります。つまり、ユーザーがログインしているかどうかを確認する場合です。

私のコードはhttps://matt.drollette.com/2012/06/calling-a-method-before-every-controller-action-in-symfony2/のカスタマイズです

コントローラに適用すると、ユーザーがログインしているかどうかがチェックされます。ログインしている場合は、ランディングページは表示されません。ただし、ユーザーをプロジェクトの任意のページにリダイレクトできます


UsuariosBundleの横に新しいバンドルを作成し、CoreBundleという名前を付けます。このバンドルで、EventListenerとModelの2つのフォルダーを作成します。モデルで作成:

interface InitializableControllerInterface
{
    public function initialize(Request $request, 
                               SecurityContextInterface $security_context, 
                               FilterControllerEvent $event);
}

EventListenerで次を作成します。

class BeforeControllerListener
{
    private $security_context;

    public function __construct(SecurityContextInterface $security_context)
    {
        $this->security_context = $security_context;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();

        if (!is_array($controller)) {
            // not a object but a different kind of callable. Do nothing
            return;
        }

        $controllerObject = $controller[0];

        // skip initializing for exceptions
        if ($controllerObject instanceof ExceptionController) {
            return;
        }

        if ($controllerObject instanceof InitializableControllerInterface) {
            // this method is the one that is part of the interface.
            $controllerObject->initialize($event->getRequest(),
                                          $this->security_context, $event);
        }
    }
}

クラスでは、カスタマイズを行う必要はありません。それらをコピーして貼り付けるだけです。インデックスアクションがデフォルトでランディングページを指すDefaultControllerがあるとします。ログインしたユーザーにはプロモーションコンテンツしかないため、ランディングページが表示されないようにすることができます。

class DefaultController extends Controller 
                        implements InitializableControllerInterface {

    /* Do not show landing page if user is logged in */

    public function initialize(Request $request, 
                               SecurityContextInterface $security_context, 
                               FilterControllerEvent $event) {

        $parent = $this;

        $securityContext = $this->container->get('security.context');

        if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY') ||
            $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {

            if ($parent->container->get('request')->get('_route') != 
                                                   'my_homepage') {
                //nothing
            } else {
                $event->setController(function() use ($parent) {
                return new RedirectResponse(
                           $parent->generateUrl('my_user'));
                        });
            }
        }
    }

   //your code
}

お役に立てば幸いです。

于 2013-01-27T09:31:41.440 に答える
0

このようにセキュリティリスナーを実装する必要があると思います

 public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
    }
 public function onKernelResponse(FilterResponseEvent $event)
    {
        if ($this->security->isGranted('ROLE_SUPER')) {
            $response = new RedirectResponse($this->router->generate('route1'));
        } 

        elseif ($this->security->isGranted('ROLE_USER')) {
            $response = new RedirectResponse($this->router->generate('route2'));
        } 


        $event->setResponse($response);
    }

詳細については、こちらをご覧くださいhttp://symfony.com/doc/2.0/components/event_dispatcher/introduction.html

于 2013-01-27T09:01:00.910 に答える