Search code examples
symfonyfosuserbundlefosfacebookbundle

Detect first FOSFacebookBundle login


I implemented successfully the FOSFacebookBundle with the FOSUserBundle. Everything works great.

Now, I'd like to be able to detect the first connection of an user with the FOSFacebookBundle.

I have a FacebookAuthenticationSuccessHandler which is called every time a Facebook authentication successes, but I'd like to declare a kind of "FirstFacebookAuthenticationSuccessHandler", called only if the user didn't exist yet. The goal of this handler is to be able to send a welcome email to each new user.

For the classic registration, I simply use a RegistrationSuccessListener.

Do you have any idea on how I could do this?


Solution

  • Answering my own question as I found the solution.

    1/ I created (and registered) a new event listener called NewFacebookUserListener:

    ...
    
    /**
     * {@inheritDoc}
     */
     public static function getSubscribedEvents()
     {
          return array(
              MyCustomEvents::NEW_FACEBOOK_USER => 'onNewFacebookUser'
          );
     }
    
     public function onNewFacebookUser(UserEvent $event)
     {
          // we get the user
          $user = $event->getUser();
    
          // and now you can do what you wish
     }
    

    2/ In my FacebookProvider (located under Security/User/Provider), I added a few lines to dispatch this new event:

    $user->setFBData($fbdata);
    
    // we send a "FB user created" event
    $dispatcher = $this->container->get('event_dispatcher');
    $dispatcher->dispatch(MyCustomEvents::NEW_FACEBOOK_USER, new UserEvent($user, $this->container->get('request')));
    

    And as expected, the event is dispatched only when a new Facebook user is created.