I'm a newbie Yii2 developer. I've started to create my own website based on Basic Yii2 template. And after creating registration and authorization logic I ran into some issues.
- I create new user. It's added to User table into my db right as it should.
- I go to login page and Log in with all needed information. It works too.
- But when it log me in it redirects me with
$this->goHome()
method. By default it'sactionIndex
in mySiteController
and this page is still denied by rules.
My DB scheme is:
$this->createTable('user', [
'id' => Schema::TYPE_PK,
'username' => Schema::TYPE_STRING . ' NOT NULL',
'email' => Schema::TYPE_STRING . ' NOT NULL',
'password_hash' => Schema::TYPE_STRING . ' NOT NULL',
'role' => Schema::TYPE_SMALLINT . ' NOT NULL',
]);
I set my identity class:
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
]
My User class extends ActiveRecord and implements IdentityInterface.
public function getId()
{
return $this->id;
}
public static function findIdentity($id)
{
self::find()
->select('*')
->where(['id' => $id])
->one();
}
SiteController
behavior method:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
],
[
'actions' => ['login'],
'allow' => true,
'roles' => ['?']
]
],
'denyCallback' => function ($rule, $action) {
echo 'DENIED ACTION: ' . $action->actionMethod;
echo ' IS GUEST: ' . Yii::$app->user->isGuest;
echo ' SESSION IS: ' . Yii::$app->user->enableSession;
}
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
As you can see I've done some var_dumps in my denyCallback
function. After I'm logged in it says:
IS DENIED: actionIndex IS GUEST: 1 SESSION IS: 1
- "Why is isGuest attribute set to 1 even when I'm logged in as user?
- "How can I fix my access logic?
Also here's some logs:
After login i have: SELECT * FROM "user" WHERE "username"='Test'
After redirect with goHome()
: SELECT * FROM "user" WHERE "id"=1
And in session there's an Id: __id 1
Finally if I change my guests' rule to :
[
'actions' => ['login', 'index'],
'allow' => true,
'roles' => ['?']
]
it shows me the page I need
Let me know if I should provide more information. Thanks in advance.