Impersonator::isUserImpersonated()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * HiPanel core package
4
 *
5
 * @link      https://hipanel.com/
6
 * @package   hipanel-core
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2014-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\logic;
12
13
use hiam\authclient\HiamClient;
14
use hipanel\models\User;
15
use yii\authclient\Collection;
16
use yii\helpers\Url;
17
use yii\web\Session;
18
19
class Impersonator
20
{
21
    public $defaultAuthClient = 'hiam';
22
    /**
23
     * @var Session
24
     */
25
    private $session;
26
    /**
27
     * @var \yii\web\User
28
     */
29
    private $user;
30
    /**
31
     * @var Collection
32
     */
33
    private $collection;
34
35
    public function __construct(Session $session, \yii\web\User $user, Collection $collection)
36
    {
37
        $this->session = $session;
38
        $this->user = $user;
39
        $this->collection = $collection;
40
    }
41
42
    /**
43
     * Method should be called to generate URL for user redirect.
44
     *
45
     * @param string $user_id
46
     * @return string
47
     */
48
    public function buildAuthUrl($user_id)
49
    {
50
        return $this->getClient()->buildAuthUrl([
51
            'redirect_uri' => Url::toRoute(['/site/impersonate-auth', 'authclient' => $this->defaultAuthClient], true),
52
            'user_id' => $user_id,
53
        ]);
54
    }
55
56
    /**
57
     * @return \hiam\authclient\HiamClient $client
58
     */
59
    private function getClient()
60
    {
61
        return $this->collection->getClient($this->defaultAuthClient);
62
    }
63
64
    /**
65
     * Method should be called when authentication succeeded.
66
     * @param HiamClient $client
67
     */
68
    public function impersonateUser(HiamClient $client)
69
    {
70
        $attributes = $client->getUserAttributes();
71
        $identity = new User();
72 View Code Duplication
        foreach ($identity->attributes() as $k) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
73
            if (isset($attributes[$k])) {
74
                $identity->{$k} = $attributes[$k];
75
            }
76
        }
77
        if ($this->user->getId() === $identity->getId()) {
78
            return;
79
        }
80
81
        $identity->save();
82
        $this->session->set('__realId', $this->user->getId());
83
        $this->user->setIdentity($identity);
84
        $this->session->set($this->user->idParam, $this->user->getId());
85
    }
86
87
    /**
88
     * Method should be called when user should be unimpersonated.
89
     */
90
    public function unimpersonateUser()
91
    {
92
        $realId = $this->session->remove('__realId');
93
        if ($realId !== null) {
94
            $this->user->identity->remove();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\web\IdentityInterface as the method remove() does only exist in the following implementations of said interface: hipanel\models\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
95
            $this->session->set($this->user->idParam, $realId);
96
            $identity = User::findOne($realId);
97
            $this->user->setIdentity($identity);
98
            $this->restoreBackedUpToken();
99
        }
100
    }
101
102
    protected function restoreBackedUpToken()
103
    {
104
        $token = $this->getClient()->getState('real_token');
105
        $this->getClient()->removeState('real_token');
106
        if ($token !== null) {
107
            $this->getClient()->setState('token', $token);
108
        }
109
    }
110
111
    /**
112
     * Method should be called before user redirect to authentication server.
113
     */
114
    public function backupCurrentToken()
115
    {
116
        $token = $this->getClient()->getState('token');
117
        $this->getClient()->setState('real_token', $token);
118
    }
119
120
    /**
121
     * @return bool
122
     */
123
    public function isUserImpersonated()
124
    {
125
        return $this->session->has('__realId');
126
    }
127
}
128