Completed
Pull Request — master (#12)
by
unknown
04:49
created

Impersonator::unimpersonateUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 8
nc 2
nop 0
1
<?php
2
3
namespace hipanel\logic;
4
5
use hiam\authclient\HiamClient;
6
use hipanel\models\User;
7
use yii\authclient\Collection;
8
use yii\helpers\Url;
9
use yii\web\Session;
10
11
class Impersonator
12
{
13
    public $defaultAuthClient = 'hiam';
14
    /**
15
     * @var Session
16
     */
17
    private $session;
18
    /**
19
     * @var \yii\web\User
20
     */
21
    private $user;
22
    /**
23
     * @var Collection
24
     */
25
    private $collection;
26
27
    public function __construct(Session $session, \yii\web\User $user, Collection $collection)
28
    {
29
        $this->session = $session;
30
        $this->user = $user;
31
        $this->collection = $collection;
32
    }
33
34
    /**
35
     * Method should be called to generate URL for user redirect
36
     *
37
     * @param string $user_id
38
     * @return string
39
     */
40
    public function buildAuthUrl($user_id)
41
    {
42
        return $this->getClient()->buildAuthUrl([
43
            'redirect_uri' => Url::toRoute(['/site/impersonate-auth', 'authclient' => $this->defaultAuthClient], true),
44
            'user_id' => $user_id,
45
        ]);
46
    }
47
48
    /**
49
     * @return \hiam\authclient\HiamClient $client
50
     */
51
    private function getClient()
52
    {
53
        return $this->collection->getClient($this->defaultAuthClient);
54
    }
55
56
    /**
57
     * Method should be called when authentication succeeded
58
     * @param HiamClient $client
59
     */
60
    public function impersonateUser(HiamClient $client)
61
    {
62
        $attributes = $client->getUserAttributes();
63
        $identity = new User();
64 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...
65
            if (isset($attributes[$k])) {
66
                $identity->{$k} = $attributes[$k];
67
            }
68
        }
69
        if ($this->user->getId() === $identity->getId()) {
70
            return;
71
        }
72
73
        $identity->save();
74
        $this->session->set('__realId', $this->user->getId());
75
        $this->user->setIdentity($identity);
76
        $this->session->set($this->user->idParam, $this->user->getId());
77
    }
78
79
    /**
80
     * Method should be called when user should be unimpersonated.
81
     */
82
    public function unimpersonateUser()
83
    {
84
        $realId = $this->session->remove('__realId');
85
        if ($realId !== null) {
86
            $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...
87
            $this->session->set($this->user->idParam, $realId);
88
            $identity = User::findOne($realId);
89
            $this->user->setIdentity($identity);
90
            $this->restoreBackedUpToken();
91
        }
92
    }
93
94
    protected function restoreBackedUpToken()
95
    {
96
        $token = $this->getClient()->getState('real_token');
0 ignored issues
show
Bug introduced by
The method getState() cannot be called from this context as it is declared protected in class yii\authclient\BaseClient.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
97
        $this->getClient()->removeState('real_token');
0 ignored issues
show
Bug introduced by
The method removeState() cannot be called from this context as it is declared protected in class yii\authclient\BaseClient.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
98
        if ($token !== null) {
99
            $this->getClient()->setState('token', $token);
0 ignored issues
show
Bug introduced by
The method setState() cannot be called from this context as it is declared protected in class yii\authclient\BaseClient.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
100
        }
101
    }
102
103
    /**
104
     * Method should be called before user redirect to authentication server
105
     */
106
    public function backupCurrentToken()
107
    {
108
        $token = $this->getClient()->getState('token');
0 ignored issues
show
Bug introduced by
The method getState() cannot be called from this context as it is declared protected in class yii\authclient\BaseClient.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
109
        $this->getClient()->setState('real_token', $token);
0 ignored issues
show
Bug introduced by
The method setState() cannot be called from this context as it is declared protected in class yii\authclient\BaseClient.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
110
    }
111
112
    /**
113
     * @return bool
114
     */
115
    public function isUserImpersonated()
116
    {
117
        return $this->session->has('__realId');
118
    }
119
}
120