Completed
Push — master ( 38553f...072343 )
by Stephen
03:34 queued 01:22
created

HasPermission   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
c 2
b 0
f 0
lcom 1
cbo 2
dl 0
loc 73
ccs 0
cts 35
cp 0
rs 10
1
<?php namespace z1haze\Acl\Middleware;
2
3
use Closure;
4
5
class HasPermission
6
{
7
    protected $request;
8
9
    /**
10
     * Handle an incoming request.
11
     *
12
     * @param  \Illuminate\Http\Request $request
13
     * @param  \Closure $next
14
     * @return mixed
15
     */
16
    public function handle($request, Closure $next)
17
    {
18
        $this->request = $request;
19
20
        if (
21
            ($this->getAction('level') && $this->hasLevel()) ||
22
            ($this->getAction('permission') && $this->hasPermissionTo())
23
        ) {
24
            return $next($this->request);
25
        }
26
27
        if ($this->request->isJson() || $this->request->wantsJson()) {
28
            return response()->json([
29
                'error' => [
30
                    'status_code' => 401,
31
                    'code' => 'INSUFFICIENT_PERMISSIONS',
32
                    'description' => 'Unauthorized.'
33
                ],
34
            ], 401);
35
        }
36
37
        return abort(401, 'Unauthorized');
38
    }
39
40
    /**
41
     * Check if user has requested route level.
42
     *
43
     * @return bool
44
     */
45
    protected function hasLevel()
46
    {
47
        $level = $this->getAction('level');
48
49
        return $this->request->user()->hasLevel($level);
50
    }
51
52
    /**
53
     * Check if user has requested route permissions.
54
     *
55
     * @return bool
56
     */
57
    protected function hasPermissionTo()
58
    {
59
        $permission = $this->getAction('permission');
60
61
        return $this->request->user()->hasPermissionTo($permission);
62
    }
63
64
    /**
65
     * Extract required action from requested route.
66
     *
67
     * @param string $key action name
68
     * @return string
69
     */
70
    protected function getAction($key)
71
    {
72
        $action = $this->request->route()->getAction();
73
74
        return isset($action[$key]) ? $action[$key] : false;
75
    }
76
77
}