Completed
Push — master ( d2f599...3fd322 )
by Alexander
07:48
created

Impersonate   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 109
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 87.8%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 7
dl 0
loc 109
ccs 36
cts 41
cp 0.878
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A checkPermission() 0 19 4
A __construct() 0 13 1
C handle() 0 40 8
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 7
        $this->guard        = $guard;
41 7
        $this->gate         = $gate;
42 7
        $this->config       = $config;
43 7
        $this->impersonator = $impersonator;
44 7
        $this->redirect     = $redirect;
45 7
    }
46
47
    /**
48
     * Handle an incoming request.
49
     *
50
     * @throws \HttpException In event of double attempt to impersonate
51
     *
52
     * @param  \Illuminate\Http\Request $request
53
     * @param  \Closure                 $next
54
     *
55
     * @return mixed
56
     */
57 7
    public function handle(Request $request, Closure $next)
58
    {
59
        /** @var string $name */
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);
69
70 5
            if ('_exit' === $name) {
71 1
                $this->impersonator->exitImpersonation();
72
            } else {
73 4
                if ($this->impersonator->isImpersonated()) {
74
                    abort(403, 'Cannot use impersonation once you already done that');
75
                }
76
77 4
                $this->impersonator->enterImpersonation($name);
78
            }
79
80 2
            if (!$request->isXmlHttpRequest() && $request->isMethod('GET')) {
81 2
                $input = $request->input();
82 2
                unset($input['_switch_user']);
83 2
                $input += $request->route()->parameters();
84
85 2
                return $this->redirect->route(
86 2
                    $request->route()->getName(),
87 2
                    $input
88
                );
89
            }
90
        } elseif ($this->impersonator->isImpersonated()) {
91
            $this->checkPermission($this->impersonator->getImpersonatingIdentifier());
92
            $this->impersonator->continueImpersonation();
93
        }
94
95
        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