Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii 2 Separate User Instance in Module

Tags:

php

yii2

I have two different user table(editors and users) in database. User table as you know and the Editor table is just using in module.

I use this way to separating user instances from between module and main application in Yii 1.1.

But I can't find a way in yii 2. I try extend yii\web\User and I change user class in module but same results. If I login in module, same User instance is accessible from out of module and anywhere.

My module init like this:

public function init()
{
    parent::init();

    \Yii::$app->set('user', [
        'class' => 'app\modules\yonetim\components\yonetimUser',
        'identityClass' => 'app\models\Editor',
        'enableAutoLogin' => true,
        'loginUrl' => ['yonetim/default/login'],
    ]);
}

Also I try this way; in config.php

'components' => [
    'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => true,
    ],
    'editor' => [
        'class' => 'yii\web\User',
        'identityClass' => 'app\models\Editor',
        'enableAutoLogin' => true,
    ],
],

But this time I don't use authorization roles(like @)

How can I use different User instance in my module ?

like image 639
Serkan Ceylan Avatar asked Mar 08 '15 16:03

Serkan Ceylan


2 Answers

I found another way for different login instance. Yii2 uses session id param for authentication. So we need to change it.

Change your modules\module_name\module_name.php file to looks like this:

public function init()
{
    parent::init();

    Yii::$app->set('user', [
        'class' => 'yii\web\User',
        'identityClass' => 'app\models\Editor',
        'enableAutoLogin' => false,
        'loginUrl' => ['yonetim/default/login'],
        'identityCookie' => ['name' => 'editor', 'httpOnly' => true],
        'idParam' => 'editor_id', //this is important !
    ]);
}

idParam value defined in yii\web\User as default: $idParam = '__id'; So if we change this value, app and module use different user instances.

like image 174
Serkan Ceylan Avatar answered Oct 07 '22 01:10

Serkan Ceylan


I've not tested this, but you may find something like switchIdentity() works, so in your module use this;

public function init()
{
    parent::init();
    $editor = new app\models\Editor
    $user = Yii::$app->user;
    $user->switchIdentity($editor);

}
like image 24
Joe Miller Avatar answered Oct 07 '22 01:10

Joe Miller