Completed
Push — master ( 59e399...f82a9f )
by Alexander
06:38
created

Impersonator::enterImpersonation()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 12
cts 12
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 4
nop 1
crap 3
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\Unimprersonated;
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 4
    public function __construct(AuthManager $auth, Repository $config, UserProvider $userProvider, Store $session, Dispatcher $eventDispatcher)
44
    {
45 4
        $this->guard           = $auth->guard();
46 4
        $this->realUser        = $this->guard->user();
47 4
        $this->config          = $config;
48 4
        $this->userProvider    = $userProvider;
49 4
        $this->session         = $session;
50 4
        $this->eventDispatcher = $eventDispatcher;
51 4
        $this->isForbidden     = false;
52 4
    }
53
54
    public function exitImpersonation()
55
    {
56
        $username = $this->session->get(static::SESSION_NAME);
57
58
        if (null === $username) {
59
            return;
60
        }
61
62
        $this->session->remove(static::SESSION_NAME);
63
64
        $user     = $this->retrieveUser($username);
65
        $realUser = $this->guard->user();
66
67
        $event = new Unimprersonated($realUser, $user);
0 ignored issues
show
Bug introduced by
It seems like $realUser defined by $this->guard->user() on line 65 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...
68
        $this->eventDispatcher->fire($event);
69
    }
70
71
    /**
72
     * @throws \HttpException Throw 403 exception if cannot find user
73
     *
74
     * @param string $username
75
     *
76
     * @return Authenticatable
77
     */
78 3
    protected function retrieveUser(string $username): Authenticatable
79
    {
80
        $conditions = [
81 3
            $this->config->get('pretend.impersonate.user_identifier') => $username,
82
        ];
83
84 3
        $user = $this->userProvider->retrieveByCredentials($conditions);
85
86 3
        if (null === $user) {
87 1
            abort(403, 'Cannot find user by this credentials');
88
        }
89
90 2
        return $user;
91
    }
92
93
    /**
94
     * @throws \HttpException Throw 403 exception if you try to impersonate yourself
95
     *
96
     * @param string $username Username of user you want to enter impersonate
97
     */
98 3
    public function enterImpersonation(string $username)
99
    {
100 3
        $user     = $this->retrieveUser($username);
101 2
        $realUser = $this->guard->user();
102
103 2
        if ($user->getAuthIdentifier() === $realUser->getAuthIdentifier()) {
104 1
            abort(403, 'Cannot impersonate yourself');
105
        }
106
107 1
        $this->impersonationUser = $user;
108 1
        $this->guard->setUser($user);
109
110 1
        if (!$this->session->has(static::SESSION_NAME)) {
111 1
            $this->session->put(static::SESSION_NAME, $username);
112
113 1
            $event = new Impersonated($realUser, $user);
0 ignored issues
show
Bug introduced by
It seems like $realUser defined by $this->guard->user() on line 101 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...
114 1
            $this->eventDispatcher->fire($event);
115
        }
116 1
    }
117
118 3
    public function isImpersonated(): bool
119
    {
120 3
        return $this->session->has(static::SESSION_NAME);
121
    }
122
123
    /**
124
     * @throws \HttpException Throw 403 exception if cannot find data in session
125
     */
126
    public function continueImpersonation()
127
    {
128
        $name = $this->getImpersonatingIdentifier();
129
130
        if (null === $name) {
131
            throw new \RuntimeException('Cannot find impersonating data in session');
132
        }
133
134
        $this->enterImpersonation($name);
135
    }
136
137
    public function getImpersonatingIdentifier(): string
138
    {
139
        return $this->session->get(static::SESSION_NAME, '');
140
    }
141
}
142