Search code examples
phpfacebookyiifacebook-opengraphyii-extensions

Authenticate users using Facebook API through open-graph extension in yii


I am using Facebook Opengraph extension for login system. Facebook login is working perfectly, also I can easily save the data in my database tables. But it doesn't authenticate users in YII system.

For example, I am having accessRules for events as follows:

public function accessRules()
{
    return array(
        array('allow', // allow authenticated user to perform 'buy' actions
            'actions'=>array('buy'),
            'users'=>array('@'),
        ),
    );
}

When user uses login using Facebook, it couldn't reach to event/buy page. Its redirecting to profile page (default page when user is logged in).

Following code I am using for Facebook login:

//Facebook login
$user = Yii::app()->facebook->getUser();
try{
    $user_profile = Yii::app()->facebook->api('/me?scope=email');
} catch(Exception $e){}
if($user) {
    if(Yii::app()->user->isGuest){
        $mbr = Facebook::model()->findByPk($user_profile['id']);
        if($mbr===null){
            $randomNum = rand(0,99999);
            $fb = new Facebook;
            $fb->mbrm_id = $user_profile['id'];
            $fb->mbrm_username = $user_profile['username'].$randomNum;
            $fb->mbrm_emailid = $user_profile['email'];
            $fb->mbrm_name = $user_profile['name'];
            $fb->mbrm_visits = "0";
            $fb->mbrm_sts = "a";

            if($fb->save()){
                Yii::app()->user->setState('title',$user_profile['username'].$randomNum);
                $this->redirect(array('profile/view','id'=>$user_profile['username'].$randomNum));
            } 
        } else {
            Yii::app()->user->setState('title',$mbr->mbrm_username);
            $mbr->saveCounters(array('mbrm_visits'=>1));
            $this->redirect(array('profile/view','id'=>$mbr->mbrm_username));
        }
    } else {
            $this->redirect(array('profile/view','id'=>$mbr->mbrm_username));
        }
}

Even I am using Yii::app()->user->setState('title',$mbr->mbrm_username);, but its not working. Please help!


Solution

  • I have added the following rules in the controller. That helps in authenticating Facebook users.

    Code

    array('allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions'=>array('buy'),
        'expression'=>'Yii::app()->facebook->getUser()',
    ),