Completed
Push — master ( 84b7ee...d2f599 )
by Alexander
02:43
created

Impersonator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 127
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 8
dl 0
loc 127
c 0
b 0
f 0
rs 10
ccs 44
cts 44
cp 1

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getImpersonatingIdentifier() 0 4 1
A __construct() 0 15 1
A exitImpersonation() 0 16 2
A retrieveUser() 0 14 2
A enterImpersonation() 0 18 3
A isImpersonated() 0 4 1
A continueImpersonation() 0 6 1
1
<?php declare(strict_types=1);
2
3
namespace Scif\LaravelPretend\Service;
4
5
use Illuminate\Auth\AuthManager;
6
use Illuminate\Contracts\Auth\Authenticatable;
7
use Illuminate\Contracts\Auth\Guard;
8
use Illuminate\Contracts\Auth\UserProvider;
9
use Illuminate\Contracts\Config\Repository;
10
use Illuminate\Contracts\Events\Dispatcher;
11
use Illuminate\Session\Store;
12
use Scif\LaravelPretend\Event\Impersonated;
13
use Scif\LaravelPretend\Event\Unimpersonated;
14
15
class Impersonator
16
{
17
    /** @var  Guard $guard */
18
    protected $guard;
19
20
    /** @var Repository $config */
21
    protected $config;
22
23
    /** @var  UserProvider */
24
    protected $userProvider;
25
26
    /** @var Store $session */
27
    protected $session;
28
29
    /** @var Dispatcher $eventDispatcher */
30
    protected $eventDispatcher;
31
32
    /** @var  Authenticatable */
33
    protected $realUser;
34
35
    /** @var  Authenticatable */
36
    protected $impersonationUser;
37
38
    /** @var  bool */
39
    protected $isForbidden;
40
41
    const SESSION_NAME = 'pretend:_switch_user';
42
43 7
    public function __construct(
44
        AuthManager $auth,
45
        Repository $config,
46
        UserProvider $userProvider,
47
        Store $session,
48
        Dispatcher $eventDispatcher
49
    ) {
50 7
        $this->guard           = $auth->guard();
51 7
        $this->realUser        = $this->guard->user();
52 7
        $this->config          = $config;
53 7
        $this->userProvider    = $userProvider;
54 7
        $this->session         = $session;
55 7
        $this->eventDispatcher = $eventDispatcher;
56 7
        $this->isForbidden     = false;
57 7
    }
58
59 2
    public function exitImpersonation()
60
    {
61 2
        $username = $this->session->get(static::SESSION_NAME);
62
63 2
        if (null === $username) {
64 1
            return;
65
        }
66
67 1
        $this->session->remove(static::SESSION_NAME);
68
69 1
        $user     = $this->retrieveUser($username);
70 1
        $realUser = $this->guard->user();
71
72 1
        $event = new Unimpersonated($realUser, $user);
0 ignored issues
show
Bug introduced by
It seems like $realUser defined by $this->guard->user() on line 70 can be null; however, Scif\LaravelPretend\Even...rsonated::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
73 1
        $this->eventDispatcher->fire($event);
74 1
    }
75
76
    /**
77
     * @throws \HttpException Throw 403 exception if cannot find user
78
     *
79
     * @param string $username
80
     *
81
     * @return Authenticatable
82
     */
83 4
    protected function retrieveUser(string $username): Authenticatable
84
    {
85
        $conditions = [
86 4
            $this->config->get('pretend.impersonate.user_identifier') => $username,
87
        ];
88
89 4
        $user = $this->userProvider->retrieveByCredentials($conditions);
90
91 4
        if (null === $user) {
92 1
            abort(403, 'Cannot find user by this credentials');
93
        }
94
95 3
        return $user;
96
    }
97
98
    /**
99
     * @throws \HttpException Throw 403 exception if you try to impersonate yourself
100
     *
101
     * @param string $username Username of user you want to enter impersonate
102
     */
103 4
    public function enterImpersonation(string $username)
104
    {
105 4
        $user     = $this->retrieveUser($username);
106 3
        $realUser = $this->guard->user();
107
108 3
        if ($user->getAuthIdentifier() === $realUser->getAuthIdentifier()) {
109 1
            abort(403, 'Cannot impersonate yourself');
110
        }
111
112 2
        $this->impersonationUser = $user;
113 2
        $this->guard->setUser($user);
114
115 2
        if (!$this->session->has(static::SESSION_NAME)) {
116 2
            $this->session->put(static::SESSION_NAME, $username);
117
118 2
            $this->eventDispatcher->fire(new Impersonated($realUser, $user));
0 ignored issues
show
Bug introduced by
It seems like $realUser defined by $this->guard->user() on line 106 can be null; however, Scif\LaravelPretend\Even...rsonated::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
119
        }
120 2
    }
121
122 4
    public function isImpersonated(): bool
123
    {
124 4
        return $this->session->has(static::SESSION_NAME);
125
    }
126
127
    /**
128
     * @throws \HttpException Throw 403 exception if cannot find data in session
129
     */
130 1
    public function continueImpersonation()
131
    {
132 1
        $name = $this->getImpersonatingIdentifier();
133
134 1
        $this->enterImpersonation($name);
135 1
    }
136
137 1
    public function getImpersonatingIdentifier(): string
138
    {
139 1
        return $this->session->get(static::SESSION_NAME, '');
140
    }
141
}
142