Skip to content

Instantly share code, notes, and snippets.

@vbugarsk
Created May 8, 2012 04:20
Show Gist options
  • Save vbugarsk/2632540 to your computer and use it in GitHub Desktop.
Save vbugarsk/2632540 to your computer and use it in GitHub Desktop.
Facebook connect by CApplicationComponent
<?php
/**
* FacebookConnect class file.
* @author Christoffer Niska <ChristofferNiska@gmail.com>
* @copyright Copyright &copy; Christoffer Niska 2011-
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
/**
* Facebook connection application component.
*/
require(dirname(__FILE__) . '/../../vendors/facebook/facebook.php'); // Yii::import() will not work in this case
class FacebookConnect extends CApplicationComponent
{
/**
* @property string Facebook application id.
*/
public $appId;
/**
* @property string Facebook application secret.
*/
public $appSecret;
/**
* @property string the application namespace.
*/
public $appNamespace;
/**
* @property boolean whether file uploads are enabled.
*/
public $fileUpload;
protected $_userId;
protected $_facebook;
/**
* Initializes this component.
*/
public function init()
{
$config = array(
'appId' => $this->appId,
'secret' => $this->appSecret
);
if ($this->fileUpload !== null)
$config['fileUpload'] = $this->fileUpload;
$this->_facebook = new Facebook($config);
parent::init();
}
/**
* Logs in the current user using facebook.
* @return boolean whether the user was logged in successfully
*/
public function login()
{
$profile = $this->api('me');
$user = User::model()->findByAttributes(array('email'=>$profile['email']));
if (!empty($profile))
{
if ($user === null)
{
$user = new User();
$user->name = $profile['username'];
$user->email = $profile['email'];
$user->fbuid = $profile['id'];
$user->status = User::STATUS_ACTIVATED;
$user->activated = new CDbExpression('NOW()');
}
$user->save(false);
}
if ($user !== null)
{
// NOTE: Facebook users are not authenticated using a password
// so we can simply generate a random one to prevent misuse.
$identity = new UserIdentity($user->name, $user->password);
$identity->authenticate(UserIdentity::AUTH_TYPE_FACEBOOK);
if ((int) $identity->errorCode === UserIdentity::ERROR_NONE)
{
$duration = 3600 * 24 * 30; // 30 days
Yii::app()->user->login($identity, $duration);
return true;
}
}
return false;
}
/**
* Registers an Open Graph action with Facebook.
* @param string $action the action to register.
* @param array $params the query parameters.
*/
public function registerAction($action, $params=array())
{
if (!isset($params['access_token']))
$params['access_token'] = $this->facebook->getAccessToken();
$this->api('me/'.$this->appNamespace.':'.$action, $params);
}
/**
* Returns the model for the currently logged in Facebook user.
* @return User the user model.
*/
public function loadUser()
{
$fbuid = $this->getUserId();
return $fbuid > 0 ? User::model()->findByAttributes(array('fbuid'=>$fbuid)) : null;
}
/**
* @return integer the Facebook user id.
*/
public function getUserId()
{
if ($this->_userId !== null)
return $this->_userId;
else
{
$userId = 0;
try
{
$userId = $this->_facebook->getUser();
}
catch (FacebookApiException $e)
{
}
return $this->_userId = $userId;
}
}
/**
* Calls the Facebook API.
* @param string $query the query to send.
* @param array $params the query paramters.
* @return array the response.
*/
public function api($query, $params=array())
{
$data = array();
if (!empty($params))
$query .= '?'.http_build_query($params);
try
{
$data = $this->_facebook->api('/'.$query);
}
catch (FacebookApiException $e)
{
}
return $data;
}
/**
* @return Facebook the Facebook application instance.
*/
public function getFacebook()
{
return $this->_facebook;
}
}
?>
<?php
/**
* UserIdentity class file.
* @author Christoffer Niska <ChristofferNiska@gmail.com>
* @copyright Copyright &copy; Christoffer Niska 2011-
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
class UserIdentity extends CUserIdentity
{
const AUTH_TYPE_DATABASE = 1;
const AUTH_TYPE_FACEBOOK = 2;
const ERROR_STATUS_INVALID = 10;
private $_id;
/**
* Authenticates a user.
* @param integer $type the authentication type, defaults to database.
* @return boolean whether authentication succeeds.
*/
public function authenticate($type = self::AUTH_TYPE_DATABASE)
{
switch ($type)
{
// Facebook authentication
case self::AUTH_TYPE_FACEBOOK:
$user = Yii::app()->fb->loadUser();
if ($user === null)
$this->errorCode = self::ERROR_USERNAME_INVALID;
else if ((int) $user->status !== User::STATUS_ACTIVATED)
$this->errorCode = self::ERROR_STATUS_INVALID;
else
{
$this->_id = $user->id;
$this->username = $user->name;
$this->setState('fbuid',$user->fbuid);
$this->setState('isAdmin', $user->admin);
$this->errorCode = self::ERROR_NONE;
}
break;
// Default authentication (name, status, password)
case self::AUTH_TYPE_DATABASE:
default:
/** @var User $user */
$user = User::model()->find('LOWER(name)=?', array(strtolower($this->username)));
if ($user === null)
$this->errorCode = self::ERROR_USERNAME_INVALID;
else if (!$user->validatePassword($this->password))
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else if ((int) $user->status !== User::STATUS_ACTIVATED)
$this->errorCode = self::ERROR_STATUS_INVALID;
else
{
$this->_id = $user->id;
$this->username = $user->name;
$this->setState('isAdmin', $user->admin);
$this->errorCode = self::ERROR_NONE;
}
break;
}
return $this->errorCode == self::ERROR_NONE;
}
/**
* @return integer the ID of the user record
*/
public function getId()
{
return $this->_id;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment