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

Impersonate::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
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 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 2
                $this->impersonator->exitImpersonation();
72 4
            } elseif ($this->impersonator->isImpersonated()) {
73 1
                    abort(403, 'Cannot use impersonation once you already done that');
74
            } else {
75 4
                $this->impersonator->enterImpersonation($name);
76
            }
77
78 3
            if (!$request->isXmlHttpRequest() && $request->isMethod('GET')) {
79 3
                $input = $request->input();
80 3
                unset($input['_switch_user']);
81 3
                $input += $request->route()->parameters();
82
83 3
                return $this->redirect->route(
84 3
                    $request->route()->getName(),
85 3
                    $input
86
                );
87
            }
88 1
        } elseif ($this->impersonator->isImpersonated()) {
89 1
            $this->checkPermission($this->impersonator->getImpersonatingIdentifier());
90 1
            $this->impersonator->continueImpersonation();
91
        }
92
93 1
        return $next($request);
94
    }
95
96
    /**
97
     * @throws \HttpException In event of lack required abilities will be throw 403 exception
98
     *
99
     * @param string $username Username of impersonable user
100
     */
101 6
    protected function checkPermission(string $username)
102
    {
103 6
        $ability  = $this->config->get('pretend.impersonate.auth_check');
104
105 6
        if (!$this->gate->has($ability)) {
106
107 1
            $this->gate->define($ability, function ($user): bool {
108 1
                if (!$user instanceof Impersonable) {
109 1
                    return false;
110
                }
111
112 1
                return $user->canImpersonate();
113 1
            });
114
        }
115
116
        if (!$this->gate->forUser($this->guard->user())->check($ability, [$username])) {
117
            abort(403, "Current user have no ability '{$ability}'");
118
        }
119
    }
120
}
121