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

Impersonate::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 5
crap 1
1
<?php declare(strict_types=1);
2
3
namespace Scif\LaravelPretend\Middleware;
4
5
use Closure;
6
use Illuminate\Contracts\Auth\Access\Gate;
7
use Illuminate\Contracts\Auth\Guard;
8
use Illuminate\Contracts\Config\Repository;
9
use Illuminate\Http\Request;
10
use Illuminate\Routing\Redirector;
11
use Scif\LaravelPretend\Interfaces\Impersonable;
12
use Scif\LaravelPretend\Service\Impersonator;
13
14
class Impersonate
15
{
16
    /** @var Gate $gate */
17
    protected $gate;
18
19
    /** @var Repository $config */
20
    protected $config;
21
22
    /** @var Impersonator $impersonator */
23
    protected $impersonator;
24
25
    /** @var Guard  */
26
    protected $guard;
27
28
    /** @var Redirector */
29
    protected $redirect;
30
31
    const SESSION_NAME = 'pretend:_switch_user';
32
33 7
    public function __construct(
34
        Guard $guard,
35
        Gate $gate,
36
        Repository $config,
37
        Impersonator $impersonator,
38
        Redirector $redirect
39
    )
40
    {
41 7
        $this->guard        = $guard;
42 7
        $this->gate         = $gate;
43 7
        $this->config       = $config;
44 7
        $this->impersonator = $impersonator;
45 7
        $this->redirect     = $redirect;
46 7
    }
47
48
    /**
49
     * Handle an incoming request.
50
     *
51
     * @throws \HttpException In event of double attempt to impersonate
52
     *
53
     * @param  \Illuminate\Http\Request $request
54
     * @param  \Closure                 $next
55
     *
56
     * @return mixed
57
     */
58 7
    public function handle(Request $request, Closure $next)
59
    {
60 7
        $name = $request->query('_switch_user', null);
61 7
        $allMiddlewares = $request->route()->gatherMiddleware();
62
63 7
        if (in_array(ForbidImpersonation::class, $allMiddlewares, true)) {
64 1
            abort(403, 'This route is forbidden to access as impersonated user');
65
        }
66
67 6
        if (null !== $name) {
68 6
            $this->checkPermission($name);
0 ignored issues
show
Bug introduced by
It seems like $name defined by $request->query('_switch_user', null) on line 60 can also be of type array; however, Scif\LaravelPretend\Midd...nate::checkPermission() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
69
70 5
            if ('_exit' === $name) {
71 2
                $this->impersonator->exitImpersonation();
72
            } else {
73 4
                if ($this->impersonator->isImpersonated()) {
74 1
                    abort(403, 'Cannot use impersonation once you already done that');
75
                }
76
77 4
                $this->impersonator->enterImpersonation($name);
0 ignored issues
show
Bug introduced by
It seems like $name defined by $request->query('_switch_user', null) on line 60 can also be of type array; however, Scif\LaravelPretend\Serv...r::enterImpersonation() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
78
            }
79
80 3
            if (!$request->isXmlHttpRequest() && $request->isMethod('GET')) {
81 3
                $input = $request->input();
82 3
                unset($input['_switch_user']);
83 3
                $input += $request->route()->parameters();
84
85 3
                return $this->redirect->route(
86 3
                    $request->route()->getName(),
87
                    $input
88
                );
89
            }
90 1
        } elseif ($this->impersonator->isImpersonated()) {
91 1
            $this->checkPermission($this->impersonator->getImpersonatingIdentifier());
92 1
            $this->impersonator->continueImpersonation();
93
        }
94
95 1
        return $next($request);
96
    }
97
98
    /**
99
     * @throws \HttpException In event of lack required abilities will be throw 403 exception
100
     *
101
     * @param string $username Username of impersonable user
102
     */
103 6
    protected function checkPermission(string $username)
104
    {
105 6
        $ability  = $this->config->get('pretend.impersonate.auth_check');
106
107 6
        if (!$this->gate->has($ability)) {
108
109 1
            $this->gate->define($ability, function ($user): bool {
110 1
                if (!$user instanceof Impersonable) {
111 1
                    return false;
112
                }
113
114 1
                return $user->canImpersonate();
115 1
            });
116
        }
117
118 6
        if (!$this->gate->forUser($this->guard->user())->check($ability, [ $username] )) {
119 2
            abort(403, "Current user have no ability '{$ability}'");
120
        }
121 5
    }
122
}
123