- Requirements
- Installation
- Configuration
- Setup, code preparation.
- Usage in views file
- Methods of CHybridAuth
- Change Log
- Resources
- [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;
}
......
}
Css class typo
There's a typo in SocialLoginButtonWidget on line 39:
$this->htmlOptions['class']='social-sigin';
The class name should be 'social-signin', although it isn't defined in the extension css.
Thanks
The typo error, fixed.
how is this different from other hybridauth methods
Please explain how this differs from existing hybridauth extensions/direct usage of library in order to help us pick the correct one for our needs.
Is a Yii component version
This version is more flexible if you implement your project in different environments.
http://www.yiiframework.com/extension/yii-environment/
Thanks for the response!
For reference, the hoauth extension supports configuration via the Yii::app()->params['hoauth']['configAlias'] parameter and the hybridauth extension supports it via module config.
This component method seems to be a cleaner implementation that other extensions could also leverage.
Perhaps some things to add to docs:
LinkedIn, on cancel: "Authentication failed! LinkedIn returned an invalid Token."
When the I authorize the app all works well, but when I press cancel in the authorization dialoge I get:
Authentication failed. The user has canceled the authentication or the provider refused the connection.
which is good, since it was cancelled, however, after that I get:
followed by
Fatal error: Call to a member function isUserConnected() on a non-object in [...]\hybridAuth\CHybridAuth.php on line 155
This happens when after the cancel, the following is executed:
Yii::app()->hybridAuth->isAdapterUserConnected('LinkedIn')
(see also http://hybridauth.sourceforge.net/support.html)
Get error in HybridauthController
.....
$model->social_info1 = hash(......);
$model->social_info2 = hash(......);
Please let me know how can I put replace hash(......) ?
where I can it from???
Please help me.
Re: Chinda
The hash(....) used in the sample code above is only for depiction purpose. You can write your own hash function.
The coding depicted in this page is only a show case how I would use the 'CHybridAuth' to integrate into my application. You are not necessary follow exactly what I did, you may implement your own algorithm.
Got Error
Dear sir,
Please help me ???
As I follow your step and I got this error when I try Authorised by Facebook:
===================================================
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
How to get User Phone Number
Dear sir,
Please read my code
$facebook = Yii::app()->hybridAuth->getAdapter('Facebook');
$facebook->isUserConnected();
echo $user->phone;
But I get nothing, please tell me how can I get user phone number from hybridAuth?
Thanks in advanced
Re: Chinda
$facebook = Yii::app()->hybridAuth->getAdapter('Facebook');
$facebook->isUserConnected();
$user = $facebook->getUserProfile();
echo $user->email;
try if you can display email?
some people may not want to share their phone number.
Add PayPal Provider
Does someone know how to add PayPal? I have tried to create a new provider, but I always get the same error "User profile request failed! Paypal returned an error: exception 'Exception' with message 'The Authorization Service has return: invalid_client' in /home/content/43/10011243/html/protected/extensions/hybridAuth/vendors/hybridauth/Hybrid/thirdparty/OAuth/OAuth2Client.php:82"
It happens after consent the grants to paypal. Someone has the same problem or have got to install PayPal?
class Hybrid_Providers_Paypal extends Hybrid_Provider_Model_OAuth2 { // default permissions public $scope = "openid profile email address"; /** * IDp wrappers initializer */ function initialize() { parent::initialize(); // Provider api end-points $this->api->api_base_url = "https://api.paypal.com"; $this->api->authorize_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize"; $this->api->token_url = "https://api.paypal.com/v1/identity/openidconnect/tokenservice"; //$this->api->token_info_url = "https://api.paypal.com/v1/identity/openidconnect/tokenservice"; } /** * begin login step */ function loginBegin() { Hybrid_Auth::redirect( $this->api->authorizeUrl( array( "scope" => $this->scope ) ) ); } /** * load the user profile from the IDp api client */ function getUserProfile() { // refresh tokens if needed //$this->refreshToken(); // ask paypal api for user infos $response = $this->api->api( "https://api.paypal.com/v1/identity/openidconnect/userinfo" ); if ( ! isset( $response->id ) || isset( $response->error ) ){ throw new Exception( "User profile request failed! {$this->providerId} returned an invalide response.", 6 ); } $this->user->profile->identifier = (property_exists($response,'id'))?$response->id:""; $this->user->profile->firstName = (property_exists($response,'given_name'))?$response->given_name:""; $this->user->profile->lastName = (property_exists($response,'family_name'))?$response->family_name:""; $this->user->profile->displayName = (property_exists($response,'name'))?$response->name:""; $this->user->profile->gender = (property_exists($response,'gender'))?$response->gender:""; $this->user->profile->email = (property_exists($response,'email'))?$response->email:""; $this->user->profile->emailVerified = (property_exists($response,'email'))?$response->email:""; $this->user->profile->language = (property_exists($response,'locale'))?$response->locale:""; if( property_exists($response,'birthday') ){ list($birthday_year, $birthday_month, $birthday_day) = explode( '-', $response->birthday ); $this->user->profile->birthDay = (int) $birthday_day; $this->user->profile->birthMonth = (int) $birthday_month; $this->user->profile->birthYear = (int) $birthday_year; } return $this->user->profile; } }
Facebook returned an invalid user id.
I am getting the following error:
Authentication failed. The user has canceled the authentication or the provider refused the connection. Original error message: Authentication failed! Facebook returned an invalid user id.
And I cant figure out whats the problem, I red a lot of solutions, but nothing helped so far. Any guesses?
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.