|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the 2amigos/yii2-usuario project. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) 2amigOS! <http://2amigos.us/> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view |
|
9
|
|
|
* the LICENSE file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Da\User\Service; |
|
13
|
|
|
|
|
14
|
|
|
use Da\User\Contracts\ServiceInterface; |
|
15
|
|
|
use Da\User\Controller\AdminController; |
|
16
|
|
|
use Da\User\Event\UserEvent; |
|
17
|
|
|
use Da\User\Model\User; |
|
18
|
|
|
use Da\User\Module; |
|
19
|
|
|
use Da\User\Query\UserQuery; |
|
20
|
|
|
use Da\User\Traits\ContainerAwareTrait; |
|
21
|
|
|
use Yii; |
|
22
|
|
|
use yii\web\ForbiddenHttpException; |
|
23
|
|
|
use yii\web\IdentityInterface; |
|
24
|
|
|
|
|
25
|
|
|
class SwitchIdentityService implements ServiceInterface |
|
26
|
|
|
{ |
|
27
|
|
|
use ContainerAwareTrait; |
|
28
|
|
|
|
|
29
|
|
|
protected $controller; |
|
30
|
|
|
protected $switchIdentitySessionKey; |
|
31
|
|
|
protected $userId; |
|
32
|
|
|
protected $userQuery; |
|
33
|
|
|
|
|
34
|
|
|
public function __construct(AdminController $controller, $userId, UserQuery $userQuery) |
|
35
|
|
|
{ |
|
36
|
|
|
/** @var Module $module */ |
|
37
|
|
|
$module = $controller->module; |
|
38
|
|
|
$this->controller = $controller; |
|
39
|
|
|
$this->switchIdentitySessionKey = $module->switchIdentitySessionKey; |
|
40
|
|
|
$this->userId = $userId; |
|
41
|
|
|
$this->userQuery = $userQuery; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function run() |
|
45
|
|
|
{ |
|
46
|
|
|
$session = Yii::$app->session; |
|
47
|
|
|
if (null === $this->userId) { // switch back identities |
|
48
|
|
|
$user = $this->userQuery->whereId($session->get($this->switchIdentitySessionKey))->one(); |
|
49
|
|
|
$session->remove($this->switchIdentitySessionKey); |
|
50
|
|
|
} else { |
|
51
|
|
|
/** @var User $identity */ |
|
52
|
|
|
$identity = Yii::$app->user->identity; |
|
53
|
|
|
if (!$identity->getIsAdmin()) { |
|
54
|
|
|
// Only admins allowed on module. Developers can override the service and implement different |
|
55
|
|
|
// approach. For example, by roles other than, and including, admin. |
|
56
|
|
|
throw new ForbiddenHttpException(); |
|
57
|
|
|
} |
|
58
|
|
|
$user = $this->userQuery->whereId($this->userId)->one(); |
|
59
|
|
|
$session->set($this->switchIdentitySessionKey, $this->userId); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
$event = $this->make(UserEvent::class, [$user]); |
|
63
|
|
|
|
|
64
|
|
|
$this->controller->trigger(UserEvent::EVENT_BEFORE_SWITCH_IDENTITY, $event); |
|
65
|
|
|
/** @var IdentityInterface $user */ |
|
66
|
|
|
Yii::$app->user->switchIdentity($user, $session->timeout); |
|
67
|
|
|
$this->controller->trigger(UserEvent::EVENT_AFTER_SWITCH_IDENTITY, $event); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|