GuardianMiddleware::hasGlobalAccess()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.2
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
3
namespace EmilMoe\Guardian\Http\Middleware;
4
5
use Closure;
6
use Illuminate\Http\Request;
7
use EmilMoe\Guardian\Http\Guardian;
8
use Illuminate\Support\Facades\Auth;
9
use EmilMoe\Guardian\Http\PermissionParameter;
10
11
class GuardianMiddleware
12
{
13
    /**
14
     * Handle an incoming request.
15
     *
16
     * @param  Request $request
17
     * @param  Closure $next
18
     * @param  String $permission
19
     * @return mixed
20
     */
21
    public function handle($request, Closure $next, $permission)
22
    {
23
        $this->toCollection($permission);
24
25
        if (! $this->hasAccess($request, $permission))
26
            return Guardian::restricted();
27
28
        return $next($request);
29
    }
30
31
    /**
32
     * Convert input to an array
33
     *
34
     * @param $permission
35
     */
36
    private function toCollection(&$permission)
37
    {
38
        $permission = collect(strpos($permission, ':') !== false ? explode(':', $permission) : [$permission]);
39
        $permission = $permission->map(function($item) {
40
            return new PermissionParameter($item);
41
        });
42
    }
43
44
    /**
45
     * Check if has local or global access
46
     *
47
     * @param $request
48
     * @param $permission
49
     * @return bool
50
     */
51
    private function hasAccess($request, $permission)
52
    {
53
        if (! Auth::check())
54
            return false;
55
56
        if ($this->hasGlobalAccess($permission) || $this->hasLocalAccess($request, $permission))
57
            return true;
58
59
        return false;
60
    }
61
62
    /**
63
     * Check if user has set global access
64
     *
65
     * @param $permission
66
     * @return mixed
67
     */
68
    private function hasGlobalAccess($permission)
69
    {
70
        if (is_string($permission))
71
            return Auth::user()->hasAccess($permission);
72
73
        foreach ($permission as $perm)
74
            if ($this->hasGlobalAccess($perm->getName()))
75
                return true;
76
77
        return false;
78
    }
79
80
    /**
81
     * Check if user has set local access to the current ID
82
     *
83
     * @param $request
84
     * @param $permission
85
     * @param null $id
86
     * @return bool
87
     */
88
    private function hasLocalAccess($request, $permission, $id = null)
89
    {
90
        if (is_string($permission))
91
            return Auth::user()->hasAccess($permission, $id);
92
93
        foreach ($permission as $perm)
94
            if ($this->hasLocalAccess($request, $perm->getName(), $request->{$perm->getColumn()}))
95
                return true;
96
97
        return false;
98
    }
99
}