chybridauth HybridAuth, open source social sign on for Facebook, Twitter, MySpace, LinkedIn, Google, Yahoo and etc

  1. Requirements
  2. Installation
  3. Configuration
  4. Setup, code preparation.
  5. Usage in views file
  6. Methods of CHybridAuth
  7. Change Log
  8. Resources
  9. [Extra] Sample Codes in User model

HybridAuth, Yii component version, enable developers to easily build social applications to engage websites vistors and customers on a social level by implementing social signin, social sharing, users profiles, friends list, activities stream, status updates and more.

Requirements

  • Yii 1.1 or above
  • Browsers support CSS3

Installation

  • Extract 'hybridAuth' folder to protected/extensions/widgets.

Configuration

Configure the components property of the application instance protected/config/main.php as following. Detail of HybridAuth configuration options, please refer to HybridAuth Configuration

array(
 ......
 'components'=>array(
    ......
        'hybridAuth'=>array(
            'class'=>'ext.widgets.hybridAuth.CHybridAuth',
            'enabled'=>true, // enable or disable this component
            'config'=>array(
                 "base_url" => "http://www.yourdomain.com/user/hybridauth/endpoint", 
                 "providers" => array(
                       "Google" => array(
                            "enabled" => false,
                            "keys" => array("id" => "", "secret" => ""),
                        ),
                       "Facebook" => array(
                            "enabled" => true,
                            "keys" => array("id" => "##", "secret" => "##"),
                        ),
                       "Twitter" => array(
                            "enabled" => false,
                            "keys" => array("key" => "", "secret" => "")
                       ),
                 ),
                 "debug_mode" => false,
                 "debug_file" => "",
             ),
         ),//end hybridAuth
        ......
     ),//end components
  ......
)

Setup, code preparation.

By referring the previous section

"base_url" => "http://www.yourdomain.com/user/hybridauth/endpoint", 

As the base_url suggest, create a HybridauthController.php in protected/modules/user/controllers/HybridauthController.php to process the hybridauth API.

Sample code of HybridauthController.php
class HybridauthController extends Controller{
    
    public $defaultAction='authenticate';
    public $debugMode=true;

    // important! all providers will access this action, is the route of 'base_url' in config
    public function actionEndpoint(){
        Yii::app()->hybridAuth->endPoint();
    }

    public function actionAuthenticate($provider='Facebook'){
        if(!Yii::app()->user->isGuest || !Yii::app()->hybridAuth->isAllowedProvider($provider))
            $this->redirect(Yii::app()->homeUrl);
        
        if($this->debugMode)
            Yii::app()->hybridAuth->showError=true;
        
        if(Yii::app()->hybridAuth->isAdapterUserConnected($provider)){
            $socialUser = Yii::app()->hybridAuth->getAdapterUserProfile($provider);
            if(isset($socialUser)){
                // find user from db model with social user info
                $user = User::model()->findBySocial($provider, $socialUser->identifier);
                if(empty($user)){ 
                    // if not exist register new user with social user info.
                    $model = new User('register');
                    $model->social_provider = $provider;
                    $model->social_identifier = $socialUser->identifier;
                    $model->social_avatar = $socialUser->photoURL;
                    $model->email = $socialUser->email;
                    $model->social_info1 = hash(......);
                    $model->social_info2 = hash(......);
                    ......
                    if($model->save()){
                       $user=$model; 
                    }else{
                       $user=false;
                    }
                }

                if($user){
                    $identity = new UserIdentity($user->social_info1, $user->social_info2);
                    $identity->authenticate('social');
                    switch ($identity->errorCode) {
                      ...... 
                      case UserIdentity::ERROR_NONE:
                           Yii::app()->user->login($identity);
                           $this->redirect(Yii::app()->request->urlReferer);
                           break;
                      ...... 
                    }
                }
            }
        }
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionLogout(){
        
        if(Yii::app()->hybridAuth->getConnectedProviders()){
            Yii::app()->hybridAuth->logoutAllProviders();
        }
        
        Yii::app()->user->logout();    
    }

}

For more available social user info, please refer Hybrid_User_Profile.

Sample code of UserIdentity
class UserIdentity extends CUserIdentity {
  private $_id;
  
      public function authenticate($type=null) {

        switch(strtolower($type)){
            case 'social': // for social user login - use in HybridauthController.php
                $user=User::model()->findByAuthSocial($this->username, $this->password);
                break;
            case 'user':
            default: 
                // for normal registered user login - use in your user login controller
                $user=User::model()->findByAuthUser($this->username, $this->password);
                break;
        }//end switch
        
        if (empty($user)) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        }else {
            $this->_id = $user->id;
            $this->setState('language', $user->preferredLanguage);
            ......
            $this->errorCode = self::ERROR_NONE;
        }
        return $this->errorCode == self::ERROR_NONE;
    }

  public function getId() {
        return $this->_id;
  }
}

Usage in views file

Put the Zocial CSS3 button widget in the view files. This widget button will hide if user is logged in. Styling the Zocial CSS3 button, please refer Zocial CSS3 Styling Guide

<?php $this->widget('ext.widgets.hybridAuth.SocialLoginButtonWidget', array(
   'enabled'=>Yii::app()->hybridAuth->enabled,
   'providers'=>Yii::app()->hybridAuth->getAllowedProviders(),
   'route'=>'user/hybridauth/authenticate',
)); ?>
SocialLoginButtonWidget Parameters
  • type: button type. Options include 'button' or 'icon'. Default: 'button'.
  • buttonText: Button text. Default: 'Signin with {provider}'.
  • htmlOptions: widget htmlOptions.
  • buttonHtmlOptions: individual button htmlOptions.
  • route: route for processing hybrid auth.
  • params: array of parameters (name=>value) that should be used instead of GET when generating button URL.
  • paramVar: name of the GET variable. Default: 'provider'.
  • providers: array of providers.
  • enabled: Enable or disable this widget. Default: true.

Methods of CHybridAuth

Detail explanations please refer to Hybrid_Auth API

Hybrid_Auth object methods
  • endPoint(): Perform the functionality of HybridAuth Endpoint.
  • isAllowedProvider($provider): Return true if the current providers is enabled.
  • getAllowedProviders(): Return array of all enabled providers.
  • getHybridAuth(): Return the current Hybrid_Auth object. Equire to new Hybrid_Auth($config_file_path).
  • getAdapter($provider, $params=array()): equire to Hybrid_Auth::authenticate(provider, params)
  • isConnectedWith($provider): equire to Hybrid_Auth::isConnectedWith(provider)
  • getConnectedProviders(): equire to Hybrid_Auth::getConnectedProviders()
  • getSessionData(): equire to Hybrid_Auth::getSessionData()
  • restoreSessionData($sessiondata): equire to Hybrid_Auth::restoreSessionData(array)
  • logoutAllProviders(): equire to Hybrid_Auth::logoutAllProviders()
  • redirect($url): equire to Hybrid_Auth::redirect(url)
  • getCurrentUrl(): equire to Hybrid_Auth::getCurrentUrl()
Example 1: Using Hybrid_Auth methods
// get Hybrid_Auth object
$provider = 'Facebook';
$hybridAuth = Yii::app()->hybridAuth->getHybridAuth();
$facebook = $hybridAuth->authenticate($provider);
$facebook = $hybridAuth->getAdapter($provider);
$hybridAuth->isConnectedWith($provider);
$hybridAuth->getConnectedProviders();
$hybridAuth->logoutAllProviders();

or call method directly

$provider = 'Facebook';
$facebook = Yii::app()->hybridAuth->getAdapter($provider, $params=array());
Yii::app()->hybridAuth->isConnectedWith($provider);
Yii::app()->hybridAuth->getConnectedProviders();
Yii::app()->hybridAuth->logoutAllProviders();
Hybrid_Provider_Adapter object methods
  • getAdapterApi($provider): equire to Hybrid_Provider_Adapter::api()
  • isAdapterUserConnected($provider): equire to Hybrid_Provider_Adapter::isUserConnected()
  • logoutAdapter($provider): equire to Hybrid_Provider_Adapter::logout()
  • setAdapterUserStatus($provider, $status): equire to Hybrid_Provider_Adapter::setUserStatus($status)
  • getAdapterUserProfile($provider): equire to Hybrid_Provider_Adapter::getUserProfile()
  • getAdapterUserContacts($provider): equire to Hybrid_Provider_Adapter::getUserContacts()
  • getAdapterUserActivity($provider, $stream='timeline'): equire to Hybrid_Provider_Adapter::getUserContacts($stream)
  • getAdapterAccessToken($provider): equire to Hybrid_Provider_Adapter::getAccessToken()
Example 2: Using Hybrid_Provider_Adapter methods
$facebook = Yii::app()->hybridAuth->getAdapter('Facebook');
$facebook->isUserConnected();
$user = $facebook->getUserProfile();
echo $user->email;
echo $user->photoURL;
$facebook->api()->api('/me/friends', "post", array(message => "Hi there")); // post to user wall
$facebook->logout();

or call method directly

$provider = 'Facebook';
Yii::app()->hybridAuth->isAdapterUserConnected($provider);
$user = Yii::app()->hybridAuth->getAdapterUserProfile($provider);
echo $user->email;
echo $user->photoURL;
Yii::app()->hybridAuth->getAdapterApi($provider)->api('/me/friends', "post", array('message' => "Hi there")); // post to facebook user wall
Yii::app()->hybridAuth->logoutAdapter($provider);

Change Log

Version 1.0.2
  • Fix typo error for $this->htmlOptions['class']='social-sigin';
    Version 1.0.1
  • Rename 'HybridAuthLoginWidget' to 'SocialLoginButtonWidget' for readability.
    Version 1.0.0
  • Initial release.

Resources

[Extra] Sample Codes in User model

The social user login algorithm used in this extension is for reference only. With this approach you can custom to suit your own defined database fields.

class User extends CActiveRecord{
  ......
   public function findBySocial($provider, $identifier){
     return $this->findByAttributes(array(
             'social_provider'=>$provider,
             'social_identifier'=>$identifier,
     ));    
   }
   
   // for social user login
   public function findByAuthSocial($socialCode1, $socialCode2){
     return $this->findByAttributes(array(
             'social_info1'=>$socialCode1,
             'social_info2'=>$socialCode2,
             'social_secret_code' => hash(......),
     ));
   }
   
   // for normal registered user login
   public function findByAuthUser($username, $password){
      $user=$this->findByAttributes(array(
             'LOWER(email)'=>strtolower($username),
      ));
      return $user->password === crypt($password, $user->password)? $user:null;
   }
  ......
}
3 0
14 followers
1 927 downloads
Yii Version: Unknown
License: (not set)
Category: Auth
Developed by: vzangloo
Created on: Jul 8, 2013
Last updated: 5 years ago

Downloads

show all

Related Extensions