logo

$5
What's the best way to get the current session|user object?

I have just written a simple
Doctrine_Listener
(read about it here) and in it I need to check whether the currently logged in user is the one that just logged in.

I currently get the session user with this:

$eventUser = sfContext::getInstance()->getUser()->getGuardUser()


Now we all know that
sfContext::getInstance()
is risky and usually a thing to avoid.

As I am just about to write a small unit test for this I will see the consequences soon.

NiKo suggested that I could use an event listener listening to
context.load_factories
and then fetch the user object and inject it in the listener. However this feels a bit intransparent for me.

Do you see a better approach?

Christian Schaefer | 06/11/10 at 6:11am | Edit


(1) Possible Answers Submitted...

  • avatar
    Last edited:
    06/14/10
    12:02am
    Pascal says:

    What about listening user.change_authentication event ?

    you will have a myUser object as subject, a "authenticated" boolean as parameter and you will be able to access easily the sfGuardUser object.

    • 06/11/10 7:08am

      Christian Schaefer says:

      Now that's not a bad idea!

      But I tried the following callback and somehow when using link() the id of the loged in sfGuardUser is auto incremented which leads to all kinds of problems..

      class UserLoginHistoryTable extends Doctrine_Table
      {
      public static function getInstance()
      {
      return Doctrine_Core::getTable('UserLoginHistory');
      }

      static public function writeLoginHistory(sfEvent $event)
      {
      $params = $event->getParameters();
      if(true === $params['authenticated'])
      {
      $history = new UserLoginHistory();
      $history->ip = getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR');
      $history->save();
      $history->link('User', array($event->getSubject()->getGuardUser()->id));
      }
      }
      }


      I guess this happens because the event is fired before the sfGuardObject is saved. Though I haven't had a thorough look yet..

      Any ideas?

    • 06/11/10 7:17am

      Pascal says:

      You should try


      $history->User = $event->getSubject()->getGuardUser();
      $history->save();


      Or


      $history->user_id = $event->getSubject()->getAttribute('user_id','','sfGuardSecurityUser');
      $history->save();

    • 06/11/10 9:28am

      Christian Schaefer says:

      That actually works fine. Thanks a lot!

      And because it's so neat I put my stuff online for everybody:
      http://www.symfony-project.org/plugins/sfDoctrineGuardLoginHistoryPlugin

      and on GitHub as well:
      http://github.com/caefer/sfDoctrineGuardLoginHistoryPlugin

This question has expired.





Current status of this question: Completed