I struggle with yii2 at the moment. Following scenario:
I use yii2 advanced template and have a frontend and a backend with separate user tables and logins.
Now I'm looking for a way that a backend user can log in as a frontend user from backend. Let's say you're in the backend and view a frontend user, you can click "log in as this user".
Is this scenario possible?
I tried to configure a frontend use in backend's config:
'user' => [
'identityClass' => 'backend\models\BackendUser',
'enableAutoLogin' => false,
],
'frontendUser' => [
'class' => 'yii\web\User',
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
],
and in my controller I tried this:
if (Yii::$app->frontendUser->login($user_group->user, 0)) {
return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/index', 'client' => $client->login_address]));
}
EDIT after Sergey's answer:
backend config
'user' => [
'identityClass' => 'backend\models\BackendUser',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_backendUser', // unique for backend
]
],
frontend config:
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'loginUrl' => ['message/welcome'], // weil beim SessionTimeout darauf umgeleitet wird,
'authTimeout' => 1800,
'identityCookie' => [
'name' => '_frontendUser', // unique for frontend
]
],
controller function:
public function actionLoginAs($id)
{
$user_group = UserGroup::findOne($id);
if (is_null($user_group)) {
return $this->redirect(['site/index']);
}
$group = $user_group->group;
$client = $group->client;
$yiiuser = new yii\web\User([
'identityClass' => 'common\models\User',
'identityCookie' => [
'name' => '_frontendUser', // unique for frontend
]
]);
$user = $user_group->user;
if ($yiiuser->login($user, 15 * 60)) {
return $this->redirect(Yii::$app->urlManagerFrontend->createAbsoluteUrl(['site/index', 'client' => $client->login_address]));
}
}
frontend
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_frontendUser', // unique for frontend
]
],
backend
'user' => [
'identityClass' => 'backend\models\BackendUser',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_backendUser', // unique for backend
]
],
Actually separate front and backend users
admin/auth/loginUser
AuthController
public function actionLoginUser($login) {
// check admin is loggin in
$yiiuser = new yii\web\User([
'identityClass' => 'common\models\User',
'identityCookie' => [
'name' => '_frontendUser', // unique for frontend
]
]);
$user = common\models\User::findByUsername($login);
// check user exists
$yiiuser->login($user, false, 15 * 60); // 15 min
return $this->redirect('/');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With