Hi guys. I am dabbling around with Yii2’s AuthClient and I just can’t seem to login to my app.
Here is my codes:-
frontend\config\main.php
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'clientId' => 'xxx',
'clientSecret' => 'xxx',
],
],
]
],
frontend\controllers\SiteController.php
class SiteController extends Controller
{
public $successUrl = 'http://app.dev/index.php';
/**
* @inheritdoc
*/
public function actions()
{
return [
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'successCallback'],
'successUrl' => $this->successUrl,
],
];
}
public function successCallback($client)
{
if (!$this->action instanceof \yii\authclient\AuthAction) {
throw new \yii\base\InvalidCallException("successCallback is only meant to be executed by AuthAction!");
}
$attributes = $client->getUserAttributes();
$externalUser = \common\models\User::find()->where(['email' => $attributes['email']])->one();
if ($externalUser->validate())
{
if ($externalUser->isRegistered())
{
$externalUser->login();
return $this->action->redirect( Url::toRoute(['private/index'],true) );
}
else
{
$session = Yii::$app->session;
$session['attributes'] = $attributes;
$this->successUrl = \yii\helpers\Url::to(['signup']);
}
}
}
}
I am able to get user’s Facebook attributes and from those information, determine if user exists in my database. print_r on $attributes and $externalUser shows correct user data. It will then redirect to successUrl but Yii::$app->user->getId() suggests that the user is not logged in.
Any pointers on what I am missing here?
Thanks.