Completed
Pull Request — master (#1377)
by Chris
02:00
created

CascadePermissionMiddleware   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 10
c 0
b 0
f 0
wmc 8
lcom 0
cbo 1

1 Method

Rating   Name   Duplication   Size   Complexity  
B handle() 0 33 8
1
<?php
2
3
namespace Spatie\Permission\Middlewares;
4
5
use Closure;
6
use Spatie\Permission\Exceptions\UnauthorizedException;
7
8
class CascadePermissionMiddleware
9
{
10
    /**
11
     * Do a cascading permissions check by recreating the permission namespace tier-by-tier
12
     *
13
     * example:
14
     * admin.auth.users.modify.create
15
     *
16
     * checks the permissions in the following dot-notation-nested order to find first match
17
     * admin
18
     * admin.auth
19
     * admin.auth.users
20
     * admin.auth.users.modify
21
     * admin.auth.users.modify.create
22
     *
23
     * @param  \Illuminate\Http\Request  $request
24
     * @param  \Closure  $next
25
     * @return mixed
26
     */
27
    public function handle($request, Closure $next, $permission, $guard = null)
28
    {
29
        if (is_null($guard)) {
30
            $guard = config('auth.defaults.guard');
31
        }
32
33
        //guests are not allowed
34
        if (app('auth')->guard($guard)->guest()) {
35
            throw UnauthorizedException::notLoggedIn();
36
        }
37
38
        $permissions = is_array($permission) ? $permission : explode('|', $permission);
39
40
        foreach ($permissions as $permission) {
41
42
            // split elements using dot-notation
43
            $parts = explode('.', $permission);
44
            $ability = '';
45
46
            foreach ($parts as $part) {
47
                // reassemble and check each tier
48
                $ability .= $ability ? '.' . $part : $part;
49
50
                if (app('auth')->guard($guard)->user()->can($ability)) {
51
                    //exit on first match
52
                    return $next($request);
53
                }
54
            }
55
        }
56
57
        // if no requested permission tier is matched, deny
58
        throw UnauthorizedException::forPermissions($permissions);
59
    }
60
}
61