We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Social Login

How can I build social login functionality on phalcon



1.7k

Well, I am going to implement that functionality in my pilot project. Here is my approach.

1) Url Organization for handling post back from identity providers

  1. Facebook: www.example.com/auth/facebook
  2. Twitter: www.example.com/auth/twitter
  3. Google +: www.example.com/auth/gplus

    $router->add('/auth/facebook', array(
        'controller' => 'auth',
        'action' => 'facebook'
    ));
    $router->add('/auth/twitter', array(
        'controller' => 'auth',
        'action' => 'twitter'
    ));
    $router->add('/auth/gplus', array(
        'controller' => 'auth',
        'action' => 'gplus'
    ));

2) Facebook integration

Just download Facebook SDK for PHP at https://developers.facebook.com/docs/php/gettingstarted/4.0.0 and locate it at plugin folder of your Phalcon app

|app
|  pluggins
|     facebook
|         FacebookAuthorizationException.php
|         .....
|         .....
|         etc...
|         GraphUserPage.php

Then set your facebook DI component.

$di->set('fbLoginHelper', function(){
    require APP_PATH . 'app/plugins/facebook/FacebookSession.php';
    FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET');
    return new FacebookRedirectLoginHelper("/auth/facebook");
});

Then in your controller just pass the fbLoginHeper to the view

class AuthController{
    public loginAction(){
        //some code here...
        $this->view->setVar('facbookLoginHelper',$this->fbLoginHelper);
    }
}

In the view

<a href="<?= $facbookLoginHelper->getLoginUrl()?">Login with facebook</a>

After user login at facebook side, we will need to handle the login process

class AuthController{
    ....
    public facebookAction(){
        try {
            $session = $this->fbLoginHelper->getSessionFromRedirect();
        } catch(FacebookRequestException $ex) {
            // When Facebook returns an error
        } catch(\Exception $ex) {
            // When validation fails or other local issues
        }
        if($session){
            //now we know that user has loged in at facebook and we can get his information like email, user id an we can authenticate him like that
            $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());

            $userId = $session->getUserId();
            $userName = $user_profile->getName();
            //log this user in
            $this->session->set('auth',['id'=>$userId , 'name'=>$userName]);

        }
    }
}

For twitter and google plus integration I think we can follow the same approach.



58.4k

@dzungcao

I see example look good , you can share tip on https://phalcontip.com, please ?



1.7k

@duythien I will do that once I finish my implmentation

edited Feb '15

Sounds very good. Please let me know if it has worked for you. Definitely am going to test this out. thanks alot.

Am running the Action auth/facebook and I get this error.

Fatal error: Class 'FacebookSDKException' not found in ..\app\plugins\facebook\FacebookRedirectLoginHelper.php on line 247.

What do you think could be the cause?



5.2k
edited Jun '15

you should add namespace before the class name like:

\Facebook\FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET');

and also you should require the class or use autoload.

Sounds very good. Please let me know if it has worked for you. Definitely am going to test this out. thanks alot.

Am running the Action auth/facebook and I get this error.

Fatal error: Class 'FacebookSDKException' not found in ..\app\plugins\facebook\FacebookRedirectLoginHelper.php on line 247.

What do you think could be the cause?

edited Jun '15

Actually I'm using the league oauth client

$provider = \App\Auth\Component\OauthFactory::create($providerName);
// ... almost the same code from oauth library here

with \App\Auth\Component\OauthFactory like


<?php
namespace App\Auth\Component;

use Phalcon\Exception;

class OauthFactory
{
    public static function create($providerName = null)
    {
        $providerName = ucfirst($providerName);
        $namespace = '\League\OAuth2\Client\Provider\\'.$providerName;

        $configName = strtolower($providerName);
        $configuration = \Phalcon\Di::getDefault()->getSocialConfig();

        if(!isset($configuration->$configName)) {
            throw new Exception('No configuration for this provider', 500, null);
        }
        elseif(!class_exists($namespace)) {
            throw new Exception('Provider does not exists.', 500, null);
        }

        return new $namespace($configuration->$configName->toArray());
    }
}

this way I'm relying on a well tested component wich does its job transparently.

Hi, I'm trying to follow your approach but I get stuck in the 2) guideline. I get Fatal error: Class 'FacebookSession' not found in services.php

I just added this:

$di->set('fbLoginHelper', function(){

require '/../../app/plugins/Facebook/FacebookSession.php';

FacebookSession::setDefaultApplication('xxxxxx', 'xxxxxx');

return new FacebookRedirectLoginHelper("/login/facebook");

});

Im close to a deadline and I can't manage to solve this, please help.

Well, I am going to implement that functionality in my pilot project. Here is my approach.

1) Url Organization for handling post back from identity providers

  1. Facebook: www.example.com/auth/facebook
  2. Twitter: www.example.com/auth/twitter
  3. Google +: www.example.com/auth/gplus

    $router->add('/auth/facebook', array( 'controller' => 'auth', 'action' => 'facebook' )); $router->add('/auth/twitter', array( 'controller' => 'auth', 'action' => 'twitter' )); $router->add('/auth/gplus', array( 'controller' => 'auth', 'action' => 'gplus' ));

2) Facebook integration

Just download Facebook SDK for PHP at https://developers.facebook.com/docs/php/gettingstarted/4.0.0 and locate it at plugin folder of your Phalcon app

|app | pluggins | facebook | FacebookAuthorizationException.php | ..... | ..... | etc... | GraphUserPage.php

Then set your facebook DI component.

$di->set('fbLoginHelper', function(){ require APP_PATH . 'app/plugins/facebook/FacebookSession.php'; FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET'); return new FacebookRedirectLoginHelper("/auth/facebook"); });

Then in your controller just pass the fbLoginHeper to the view

class AuthController{ public loginAction(){ //some code here... $this->view->setVar('facbookLoginHelper',$this->fbLoginHelper); } }

In the view

<a href="<?= $facbookLoginHelper->getLoginUrl()?">Login with facebook</a>

After user login at facebook side, we will need to handle the login process

class AuthController{ .... public facebookAction(){ try { $session = $this->fbLoginHelper->getSessionFromRedirect(); } catch(FacebookRequestException $ex) { // When Facebook returns an error } catch(\Exception $ex) { // When validation fails or other local issues } if($session){ //now we know that user has loged in at facebook and we can get his information like email, user id an we can authenticate him like that $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());

          $userId = $session->getUserId();
          $userName = $user_profile->getName();
          //log this user in
          $this->session->set('auth',['id'=>$userId , 'name'=>$userName]);

      }
  }

}

For twitter and google plus integration I think we can follow the same approach.

It seems you know about this, i think i have that class problem as u suggest. What am i missing?

you should add namespace before the class name like:

\Facebook\FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET');

and also you should require the class or use autoload.

Sounds very good. Please let me know if it has worked for you. Definitely am going to test this out. thanks alot.

Am running the Action auth/facebook and I get this error.

Fatal error: Class 'FacebookSDKException' not found in ..\app\plugins\facebook\FacebookRedirectLoginHelper.php on line 247.

What do you think could be the cause?



5.2k
edited Jun '15

Yes, I implement a social login systerm recently.

I think It's better add your facebook sdk to your Phalcon loader:

$loader = new \Phalcon\Loader();

/**
 * Registering a set of directories taken from the configuration file
 */
$loader->registerNamespaces([
  ...
    'Facebook'      =>  $config->application->pluginsDir . 'Facebook/',
    'Twitter'           =>  $config->application->pluginsDir . 'Twitter/',

]);

$loader->register();

It seems you know about this, i think i have that class problem as u suggest. What am i missing?

you should add namespace before the class name like:

\Facebook\FacebookSession::setDefaultApplication('YOUR_APP_ID', 'YOUR_APP_SECRET');

and also you should require the class or use autoload.

Sounds very good. Please let me know if it has worked for you. Definitely am going to test this out. thanks alot.

Am running the Action auth/facebook and I get this error.

Fatal error: Class 'FacebookSDKException' not found in ..\app\plugins\facebook\FacebookRedirectLoginHelper.php on line 247.

What do you think could be the cause?