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

HasPermission::getAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 6
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
}