hoauth

hoauth - simple integration with social network authorization lib Hybridauth in Yii (facebook, google, twitter, vkontakte ...)
38 followers
  • hoauth extension provides simple integration with social network authorization lib Hybridauth in Yii. (facebook, google, twitter, vkontakte and much more).
  • Automatically finds and supports yii-user module (instruction for yii-user).

Requirements

  • Yii 1.1 or above. (I have tested it only in 1.1.13)

Available social networks

  • OpenID
  • Google
  • Facebook
  • Twitter
  • Yahoo
  • MySpace
  • Windows Live
  • LinkedIn
  • Foursquare
  • Vkontakte
  • AOL

Additional social networks providers can be found at HybridAuth website. And how to configure them here at the bottom of the page.

A little about how it's woks

This extension authenticates and if it's need creates new user. When user was registered "locally" (so he has login (email) and password), then he can also log in with it's social account (extension checks if user with provided email exists in db, when yes, the he will be logged in and it is no matter how had he registered earlier - locally or not). After the user logged in he will be redirected to Yii::app()->user->returnUrl.

In future releases, when it will be needed I can implement "classical algorithm": either local authorization or social authorization.

NOTE: this extension requires UserIdentity class. It doesn't use authenticate() method of UserIdentity class. Class constructor called with parameters new UserIdentity($mail, null) and than called CWebUser::login() method (while authentication work did for us social network). When social network didn't give us user's email, the hoauth will ask user for email, when email exists in our db, the password will be asked too. At the end we bind provided by social network unique user identifier to user id for future sign in.

NOTE 2: This extension will also automatically create user_oauth table in your database. About it see "UserOAuth model" section.

Installation and Usage

1. Simply copy the files in your extensions directory (or in any other directory you want).

2. Edit yours controller source code (eg. SiteController class with actionLogin() method) to add new actions:

class SiteController extends Controller
{
    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
      'oauth' => array(
        // the list of additional properties of this action is below
        'class'=>'ext.hoauth.HOAuthAction',
        // Yii alias for your user's model, or simply class name, when it already on yii's import path
        // default value of this property is: User
        'model' => 'User', 
        // map model attributes to attributes of user's social profile
        // model attribute => profile attribute
        // the list of avaible attributes is below
        'attributes' => array(
          'email' => 'email',
          'fname' => 'firstName',
          'lname' => 'lastName',
          'gender' => 'genderShort',
          'birthday' => 'birthDate',
          // you can also specify additional values, 
          // that will be applied to your model (eg. account activation status)
          'acc_status' => 1,
        ),
      ),
      // this is an admin action that will help you to configure HybridAuth 
      // (you must delete this action, when you'll be ready with configuration, or 
      // specify rules for admin role. User shouldn't have access to this action!)
      'oauthadmin' => array(
        'class'=>'ext.hoauth.HOAuthAdminAction',
      ),
        );
    }
}

3. Add the findByEmail method to your user`s model class:

/**
   * Returns User model by its email
   * 
   * @param string $email 
   * @access public
   * @return User
   */
  public function findByEmail($email)
  {
    return self::model()->findByAttributes(array('email' => $email));
  }

4. Visit your oauthadmin action (eg. http://yoursite.com/site/oauthadmin) to create the HybridAuth config. For your HybridAuth Endpoint URL use this: http://yoursite.com/site/oauth. After install you can leave install.php in your file system, while it's in Yii protected directory. But you must remove oauthadmin action, or make such rules, that give access only for admin users. Config file can be found at application.config.hoauth

5. Add social login widget to your login page view (you can use route property, when you placing your widget not in the same module/controller as your oauth action):

<?php $this->widget('ext.hoauth.widgets.HOAuth'); ?>

Optional: 6. When you planning to use social networks like Twitter, that returns no email from user profile, you should declare verifyPassword($password) method in User model, that should take the password (not hash) and return true if it is valid. 7. You can also declare the sendActivationMail() method, that should mark the user account as inactive and send the mail for activation. This method, when it's exists will be used for social networks like Twitter, that give us no data about user's email (because we need to proof that user entered the right email).

Available social profile fields

You can find them at HybridAuth website. And here is some additional fields, that I needed in my project, you can use them too:

  • birthDate - The full date of birthday (eg. 1991-09-03)
  • genderShort - short representation of gender (eg. 'm', 'f')

Additional properties for HOAuthAction

  • useYiiUser - enables support for yii-user (default: false). hoauth will find yii-user module automatically, so you can leave this property as default. You may also leave attributes and model properties as default.
  • enabled - defines whether the ouath functionality is active. Useful for example for CMS, where user can enable or disable oauth functionality in control panel. (default: true)
  • scenario - scenario name for the $model (optional)
  • loginAction - name of a local login action (should be in the same controller as oauth action). (default: 'actionLogin')
  • duration - 'remember me' duration in ms. (default: 2592000 //30days)
  • usernameAttribute - you can specify username attribute, when it must be unique (like in yii-user extension), that hoauth will try to validate it's uniqueness.

UserOAuth model

UserOAuth model used to bind social services to user's account and to store session with social network profile. If you want to use this data (user profile) later, please use UserOAuth::getProfile() method:

$userOAuths = UserOAuth::model()->findUser(5); // find all authorizations from user with id=5
foreach($userOAuths as $userOAuth)
{
  $profile = $userOAuth->profile;
  echo "Your email is {$profile->email} and social network - {$userOAuth->provider}<br />";
}

or

$userOAuth = UserOAuth::model()->findUser(5, "Google"); // find all authorizations from user with id=5
$profile = $userOAuth->profile;
echo "Your email is {$profile->email} and social network - {$userOAuth->provider}<br />";

About how to use HybridAuth object you can read here.

Sources

  • [HybridAuth] (http://hybridauth.sourceforge.net)
  • [Zocial CSS3 Buttons] (https://github.com/samcollins/css-social-buttons/)
  • [Project page on Yii] (http://yiiframework.com/extension/hoauth/)
  • instruction for yii-user

New in hoauth v1.2.2

  • Enh#6: support of prefixed table names
  • Enh#7: added ability to setup alias (by default is application.config.hoauth) of HybridAuth config file in yii config (Yii::app()->params['hoauth']['configAlias'])
  • Enh#8: widget to display social networks that user bond to
  • Support of yii-user version, when Profile::regMode isn't static property
  • Fixed issue when password field apeared, when it should not do so during social network signup
  • Support of sending activation email by yii-user module
  • Added support of yii-user banned and not activated account status
  • Ability to register a new account with the same SN, when in db still exists SN relation to account that was deleted
  • HOAuthWidget moved to widgets directory (see UPGRADE.md)

New in hoauth v1.2.1

  • It was decieded to move HybridAuth config file to the yii's config diretory and rename to hoauth.php. Extension will try to do it automatically, when config diretory is not writable, it will run with config file from old directory, but old directory has the deprecated status.
  • fixed bug with to long username, when registering user for yii-user extension.
  • Support of login from social networks, that returning no email (also added HUserInfoForm class).
  • updates in installation instructions

New in hoauth v1.2

  • HOAuthWiget property $controllerId replaced by $route and now you can specify route e.g. module/controller
  • Modification of HybridAuth install script to generating Endpoint URL properly.
  • Renaming of user_oauth table columns: name -> provider, value -> identifier (model will automatically update schema)
  • New features in UserOAuth.php model.
  • Support for yii-user extension

Total 20 comments

#13288 report it
SleepWalker at 2013/05/21 12:23am
Hello. felizardo

And when you try to login here. Do you have this error? When not, than it is probably something with your server/php configuration.

I have no idea about why you have this issue. I can't say that this is something with HybridAuth lib, because it is works great (and not only by me). When you won't find the answer, you can try to send me email.

#13285 report it
felizardo at 2013/05/20 05:46pm
Getting NULL in $_REQUEST['signed_request']

Hi,

Im getting a NULL in $_REQUEST['signed_request'], line 492 of /hoauth/hybridauth/Hybrid/thirdparty/Facebook/base_facebook.php. Anyone know why this could be happening?

Thanks

#13281 report it
komannder at 2013/05/20 07:43am
Thanks SleepWalker

I did get the new git version, fixed a few issues I had, thanks.

I the end I decided to allow changing the email and passwords, and have made the email field unique again.

Everything seems to work great. Once linked by 'id' you can login either way, and you cannot change your email and 'take over' another account.

Thanks for all!

#13273 report it
SleepWalker at 2013/05/20 02:42am
Hi, komannder

I have planned so that account, created by social network authorization was the same, as when user registered "by hand" on site. So this is not like on other sites this usually done.

But after user has registered through hoauth he can set new password (when you let him) and then login with his email and password too. Also he can change his email, but his account will be still linked to social network.

When user changes email to another existing email, you should by yourself control this and decide to let him or not. hoauth linked to user id, so if user overrides another user, he will still have his past social networks connected (of coarse if you won't change his id).

And at last he can bind other social network to his account. To do that, he should use hoauth authentication widget, while he is logged in (you can check this feature on test site, to see how its works).

P.S. there is one newer version of extension on github. I haven't done all, that I am planing for next release, thats why I haven't posted it here. But you can download its intermediate implementation from github. I have fixed some bugs there.

#13261 report it
komannder at 2013/05/19 09:32am
Email uniqueness

Great extension, got it working perfectly!

One question though about email uniqueness.

In my apps I use email/password for logins, NOT usernames!!!

Before installing this extension, I customized UserIdentity and just added to the User's email field the 'unique' validator, on all my scenarios (registration, update, public profile).

The question is: how should handle emails now, as they can conflict with hoauth created accounts?

If I do in my User model: $rulesArray = array( array('email', 'unique', 'on'=>'registration'),

Users can register with new unique emails, but they will not be able to register if they first entered via facebook with same email.

... Or what happens when a user that was created via hoauth, goes to his profile (on mi site) and tries to change the email to another existing user? ...

There are many other combinations that can cause problems....

Does anyone have any idea how to handle this mess???

#12917 report it
jurassic82 at 2013/04/20 09:49am
thank you !

Thank you SleepWalker As you suggested I did the complete process but downloading the github last master commit (from yii, yii-user and your extension).

And now it's working ... :-)

Thank you again !!!

#12916 report it
SleepWalker at 2013/04/20 05:37am
@jurassic82

I have posted you link to the github(!) page of extension. Because on yii site the last upload of files was "Last updated: Jun 11, 2012" and on GitHub 18 days ago.

I have just downloaded the last code from yii-user GitHub page and installed it to the demo page. And it's works perfectly, as two month old version. But one year old version probably not... So try to use version from github and don't forget to clear db from old yii-user's tables, because it can cause another one bug :).

When it won't help you. Than probably this is something wrong in your application's config. hoauth has nothing to do with SiteController, when you don't ask it for that. You can send me email with your user folder, and config.php (but don't forget to clear passwords etc.) and we will try to get rid of this.

P.S. My email you can find here.

#12915 report it
jurassic82 at 2013/04/20 05:08am
Not working yet

Thank you SleepWalker, but as I told in the P.S of my previous post, I have also tried with Yii-user 0.3.61 from http://www.yiiframework.com/extension/yii-user Exactly the SAME problem.

#12914 report it
SleepWalker at 2013/04/20 04:56am
@jurassic82

Hi, jurassic82, try this one yii-user

#12911 report it
jurassic82 at 2013/04/20 04:13am
HOAuth + yii-user reports a 500 error

I have a fresh new installation of Yii 1.13 Then I installed step by step the Yii-User extension 0.8 (http://www.yiiframework.com/extension/yii-user-management)

Then I followed the steps of this to get HOauth working with that extension: https://github.com/SleepWalker/hoauth/wiki/%5Binstall%5D-hoauth-and-yii-user-extension

Then I go to {mysite}/user/login and I see the hoauth social buttons ... but when I click in one of them:

Error 500 include(SiteController.php): failed to open stream: No such file or directory

Why is that ? :(

Thank you in advance

P.D. I have also tried with Yii-user 0.3.61 from http://www.yiiframework.com/extension/yii-user

#12804 report it
SleepWalker at 2013/04/12 04:23pm
New version of hoauth

Hello, fburhan89, try to download the new version 1.2.2 (I have just uploaded it).

But probably this won't help you. The only place, where function unserialize in v1.2.1 was used is /hybridauth/Hybrid/Storage.php. Probably it is something with session in your app. I can't say more with that information that you have posted to me...

#12802 report it
fburhan89 at 2013/04/12 04:06pm
Error at offset 0 of 1 bytes

after following above steps it gives unserialize() [function.unserialize]: Error at offset 0 of 1 bytes , Please help me!!, thnks

#12610 report it
sebako at 2013/04/01 08:20am
UserIdentity with email

Hey Friends,

SleepWalker was so kind to assist me via email with this UserIdentity Issue I had, no it came out that I was missing something crucial for hoauth. However here's the new UserIdentity Class:

<?php
 
/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
  /**
   * @var EUser $user user model that we will get by email
   */
  public $user;
 
 
  private $_pwGuess;
 
  public function __construct($username,$password=null)
  {
    parent::__construct($username,$password);
 
    $this->user = EUser::model()->find('LOWER(email)=?',array(strtolower($this->username)));
 
    if($password === null)
    {
      $this->setState("userId", $user->id);
      $this->errorCode=self::ERROR_NONE;
    }else
        $this->_pwGuess = $password;
  }
 
    /**
     * Authenticates a user.
     * @return boolean whether authentication succeeds.
     */
    public function authenticate()
    {
        if($this->user===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        elseif($this->user->password !== hash("sha512", $this->_pwGuess)){
            $this->errorCode=self::ERROR_PASSWORD_INVALID;}
        else
        {
            $this->setState("userId", $user->id);
 
            $this->errorCode=self::ERROR_NONE;
        }
        return $this->errorCode==self::ERROR_NONE;
    }
 
    public function getName()
  {
    return $this->user->email;
  }
 
  public function getId()
  {
    return $this->user->id;
  }
}

I have made some modifications to it so that it fits my application but should work for almost any other application using Emailadress for login.

Thanks again for the Support!

Best,

Seb

#12603 report it
SleepWalker at 2013/04/01 02:22am
@sebako

sebako, do you use it with yii-user or not? Can I see UserIdentity class?

You can create an issue here Or send me email (see profile)

#12602 report it
sebako at 2013/03/31 08:35pm
UserIdentity Wrong?

Hey I am trying to setup this extension but I am getting an error after I authenticate with facebook:

Unspecified error.

Original error message: Can't sign in, something wrong with UserIdentity class.

Any Idea how to fix this?

Thanks in advance.

Seb

#12414 report it
SleepWalker at 2013/03/19 04:16am
Thanks, Dino

Thanks, Dino, I will include this in next release

#12413 report it
Dino at 2013/03/19 03:44am
Small bug

Greetings,

thanks for the implementation!

One remark:

in the file UserOAuth.php you put require instead of require_once - it causes fatal error since class was already defined and it tries to include it twice (in case 2+ networks are linked and it lazy loads profile 2+ times).

It is on the line 108 - it should be require_once($path.'/Hybrid/Auth.php');

instead of

require($path.'/Hybrid/Auth.php');

#12125 report it
SleepWalker at 2013/02/28 02:27am
Updates

So, I think, that I fixed bug and added support of Twitter and other social networks, that return no email with user profile. But I have no time to test it, beacuase I will drive to my homeland in 5 hours. You can watch it here and I go to pack my stuff. When you happy with current functionality, you can download current version of extension from dev branch

#12075 report it
SleepWalker at 2013/02/26 07:50am
@stepanic
  • I have fixed bug with user login, so now unregistered user can login to. There was problem with too long username (I will release this changes with modifications for twitter). But now you can fix this manually in HOAuthAction.php changing this:
$user->username = preg_replace('/[^A-Za-z0-9_]/u', '', $user->email);

to this:

$user->username = substr(preg_replace('/[^A-Za-z0-9_]/u', '', $user->email), 0, 20);
  • Here is the demo app. You can test facebook and google login now.
  • About twitter bug. That is not a bug. you can read about urls here and here
  • I develop this extension in Chromium (this is webkit browser) and everything works fine without "You cannot access this page directly.". I haven't tested this extension in different browsers, while it doesn't depends from browser, but I will do this before post new release with bug fixes.

But another problem is that twitter doesn't returns user email. So my algorithm will not work, because it's depends from email. I will fix this issue today or tomorrow and post about this here.

#12066 report it
stepanic at 2013/02/25 10:06pm
Webkit problem

In Firefox and Internet explorer, everything works perfect, but in Webkit browsers (Chrome and Safari) I got message "You cannot access this page directly." because of some session handler in ./hybridauth/Hybrid/Endpoint.php

Leave a comment

Please to leave your comment.

Create extension