Completed
Push — master ( 3fd322...2f9820 )
by Alexander
03:08
created

Impersonator::getImpersonatingIdentifier()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php declare(strict_types=1);
2
3
namespace Scif\LaravelPretend\Service;
4
5
use HttpException;
6
use Illuminate\Auth\AuthManager;
7
use Illuminate\Contracts\Auth\Authenticatable;
8
use Illuminate\Contracts\Auth\Guard;
9
use Illuminate\Contracts\Auth\UserProvider;
10
use Illuminate\Contracts\Config\Repository;
11
use Illuminate\Contracts\Events\Dispatcher;
12
use Illuminate\Session\Store;
13
use Scif\LaravelPretend\Event\Impersonated;
14
use Scif\LaravelPretend\Event\Unimpersonated;
15
16
class Impersonator
17
{
18
    /** @var  Guard $guard */
19
    protected $guard;
20
21
    /** @var Repository $config */
22
    protected $config;
23
24
    /** @var  UserProvider */
25
    protected $userProvider;
26
27
    /** @var Store $session */
28
    protected $session;
29
30
    /** @var Dispatcher $eventDispatcher */
31
    protected $eventDispatcher;
32
33
    /** @var  Authenticatable */
34
    protected $impersonationUser;
35
36
    /** @var  bool */
37
    protected $isForbidden;
38
39
    const SESSION_NAME = 'pretend:_switch_user';
40
41 7
    public function __construct(
42
        AuthManager $auth,
43
        Repository $config,
44
        UserProvider $userProvider,
45
        Store $session,
46
        Dispatcher $eventDispatcher
47
    ) {
48 7
        $this->guard           = $auth->guard();
49 7
        $this->config          = $config;
50 7
        $this->userProvider    = $userProvider;
51 7
        $this->session         = $session;
52 7
        $this->eventDispatcher = $eventDispatcher;
53 7
        $this->isForbidden     = false;
54 7
    }
55
56
    /**
57
     * @throws HttpException Throw 403 exception if cannot find user
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
        $event = new Unimpersonated($this->guard->user(), $user);
0 ignored issues
show
Bug introduced by
It seems like $this->guard->user() can be null; however, __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...
71
72 1
        $this->eventDispatcher->fire($event);
73 1
    }
74
75
    /**
76
     * @throws HttpException Throw 403 exception if cannot find user
77
     */
78 4
    protected function retrieveUser(string $username): Authenticatable
79
    {
80
        $conditions = [
81 4
            $this->config->get('pretend.impersonate.user_identifier') => $username,
82
        ];
83
84 4
        $user = $this->userProvider->retrieveByCredentials($conditions);
85
86 4
        if (null === $user) {
87 1
            abort(403, 'Cannot find user by this credentials');
88
        }
89
90 3
        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 4
    public function enterImpersonation(string $username)
99
    {
100 4
        $user     = $this->retrieveUser($username);
101 3
        $realUser = $this->guard->user();
102
103 3
        if ($user->getAuthIdentifier() === $realUser->getAuthIdentifier()) {
104 1
            abort(403, 'Cannot impersonate yourself');
105
        }
106
107 2
        $this->impersonationUser = $user;
108 2
        $this->guard->setUser($user);
109
110 2
        if (!$this->session->has(static::SESSION_NAME)) {
111 2
            $this->session->put(static::SESSION_NAME, $username);
112
113 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 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
        }
115 2
    }
116
117 4
    public function isImpersonated(): bool
118
    {
119 4
        return $this->session->has(static::SESSION_NAME);
120
    }
121
122
    /**
123
     * @throws HttpException Throw 403 exception if cannot find data in session
124
     */
125 1
    public function continueImpersonation()
126
    {
127 1
        $name = $this->getImpersonatingIdentifier();
128
129 1
        $this->enterImpersonation($name);
130 1
    }
131
132 1
    public function getImpersonatingIdentifier(): string
133
    {
134 1
        return $this->session->get(static::SESSION_NAME, '');
135
    }
136
}
137