2012-06-24 25 views
23

Tôi cần thực hiện một tập hợp các hành động sau khi người dùng đăng nhập thành công. Điều này bao gồm tải dữ liệu từ cơ sở dữ liệu và lưu trữ trong phiên.Symfony2: Sau sự kiện đăng nhập thành công, hãy thực hiện bộ hành động

Cách tiếp cận tốt nhất để thực hiện điều này là gì?

+1

Làm thế nào để làm điều đó bằng cách sử dụng dịch vụ: http://stackoverflow.com/questions/8308050/how-to-disable-redirection-after-login-check-in-symfony-2/8312188#8312188 – unairoldan

Trả lời

50

Bạn có thể thêm người nghe vào sự kiện security.interactive_login.

đính kèm người nghe của bạn như vậy. Trong ví dụ này, tôi cũng chuyển ngữ cảnh bảo mật và phiên làm phụ thuộc.

Lưu ý: SecurityContext bị phản đối như của Symfony 2.6. Vui lòng tham khảo http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

parameters: 
    # ... 

    account.security_listener.class: Company\AccountBundle\Listener\SecurityListener 

services: 
    # ... 

    account.security_listener: 
     class: %account.security_listener.class% 
     arguments: ['@security.context', '@session'] 
     tags: 
      - { name: kernel.event_listener, event: security.interactive_login, method: onSecurityInteractiveLogin } 

và người nghe của bạn, bạn có thể lưu trữ bất cứ điều gì bạn muốn trên phiên. Trong trường hợp này, tôi đặt múi giờ của người dùng.

<?php 

namespace Company\AccountBundle\Listener; 

use Symfony\Component\Security\Core\SecurityContextInterface; 
use Symfony\Component\HttpFoundation\Session\Session; 
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; 

class SecurityListener 
{ 

    public function __construct(SecurityContextInterface $security, Session $session) 
    { 
     $this->security = $security; 
     $this->session = $session; 
    } 

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) 
    { 
     $timezone = $this->security->getToken()->getUser()->getTimezone(); 
     if (empty($timezone)) { 
      $timezone = 'UTC'; 
     } 
     $this->session->set('timezone', $timezone); 
    } 

} 
+0

Điều này có vẻ như nó sẽ làm các trick. Có bất kỳ phụ thuộc nào tôi cần khai báo trong lớp không? – jbsound

+0

Không, chỉ phụ thuộc của riêng bạn (người quản lý thực thể có thể). – MDrollette

+0

Sau khi đào nhiều hơn một chút, có vẻ như có những phụ thuộc cần được chỉ định. Tìm thấy bài viết này cho thấy việc triển khai mã hoàn chỉnh hơn: http://www.metod.si/login-event-listener-in-symfony2/ – jbsound

6

Bạn thậm chí có thể tìm nạp cá thể người dùng từ chính sự kiện, không cần phải tiêm bộ nhớ mã thông báo!

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) 
{ 
    $event->getAuthenticationToken()->getUser() 
} 
Các vấn đề liên quan