Search code examples
facebook-graph-apiauthenticationzend-framework2zfcuser

Automatically authenticate a user who logged in using Facebook (ZF2)


I'm using ZfcUser in a ZF2 application. What I'm trying to do is to allow a person to authenticate using Facebook. The Facebook authentication part works fine: I request a login URL from the Graph API, redirect the user to login and request permissions, Facebook redirects back to my redirect URL and then I can fetch a Facebook session object and retrieve the user's info.

I would like it to work like this: - If e-mail address doesn't exist as a user in my database I will create the user and I want to automatically login with that local user profile. - If there's already a user in the database with that e-mail address I want to login as that user without having to authenticate.

\Zend\Authentication\AuthenticationService (which is used by ZfcUser) has a getIdentity() method to retrieve the current identity. It also has an authenticate method with an adapter parameter to perform authentication. There is no setIdentity() method, so I'm guessing I will have to create a custom authentication adapter and use that to login a user who logged in using Facebook. Is that true or is there an easier or better way?

Edit: This does work:

$authService = $this->getServiceLocator()->get('zfcuser_auth_service');
$user = ...
$authService->getStorage()->write($user);

It seems a bit dirty though, but I'm not sure if there's a cleaner way?


Solution

  • Don't reinvent the wheel ;)

    https://github.com/SocalNick/ScnSocialAuth

    Before doing something, it's always a good idea to check http://modules.zendframework.com/