Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Social Login

How can I build social login functionality on phalcon



43.8k
Accepted
answer

I have gmail oauth setup in my Webird project. The library is fine enough for now but likely in about 3 months I'll be looking for a better library. My setup will work for you to get going and then just a about ten lines would change if you used a different library. There has been a lot of churn in the oauth endpoints and the library I'm using didn't have the latest google ones for the minimum exchange info that I was looking for. At one point a found what looked to be a better oauth library on a currated list.

I think that you can find what you are looking for here in these files to adapt to your needs:



1.5k

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.



33.6k

@dzungcao

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



1.5k

@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?

edited Jun '15

you should add namespace before the class name like:

\Facebook\FacebookSession::setDefaultApplication('YOURAPPID', 'YOURAPPSECRET');

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 APPPATH . 'app/plugins/facebook/FacebookSession.php'; FacebookSession::setDefaultApplication('YOURAPPID', 'YOURAPP_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('YOURAPPID', 'YOURAPPSECRET');

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

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('YOURAPPID', 'YOURAPPSECRET');

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?