@@ 8-34 (lines=27) @@ | ||
5 | use Closure; |
|
6 | use Spatie\Permission\Exceptions\UnauthorizedException; |
|
7 | ||
8 | class PermissionMiddleware |
|
9 | { |
|
10 | public function handle($request, Closure $next, $permission) |
|
11 | { |
|
12 | if (is_string($permission)) { // sample : 'create-admin|update-admin@admin' , here admin is guard name and create-admin , update-admin are permission. | Notice: guard is optional. |
|
13 | $parsed = explode('@', $permission); |
|
14 | $guard = isset($parsed[1]) |
|
15 | ? $parsed[1] |
|
16 | : null; |
|
17 | $permissions = explode('|', $parsed[0]); |
|
18 | } elseif (is_array($permission)) { |
|
19 | $guard = isset($permission['guard']) ? $permission['guard'] : null; |
|
20 | $permissions = $permission['permission']; |
|
21 | } |
|
22 | if (auth($guard)->guest()) { |
|
23 | throw UnauthorizedException::notLoggedIn(); |
|
24 | } |
|
25 | ||
26 | foreach ($permissions as $permission) { |
|
27 | if (auth($guard)->user()->can($permission)) { |
|
28 | return $next($request); |
|
29 | } |
|
30 | } |
|
31 | ||
32 | throw UnauthorizedException::forPermissions($permissions); |
|
33 | } |
|
34 | } |
|
35 |
@@ 9-34 (lines=26) @@ | ||
6 | use Illuminate\Support\Facades\Auth; |
|
7 | use Spatie\Permission\Exceptions\UnauthorizedException; |
|
8 | ||
9 | class RoleMiddleware |
|
10 | { |
|
11 | public function handle($request, Closure $next, $role) |
|
12 | { |
|
13 | if (is_string($role)) { // sample : 'support|super-admin@admin' , here admin is guard name and support , super-admin are role . | Notice: guard is optional. |
|
14 | $parsed = explode('@', $role); |
|
15 | $guard = isset($parsed[1]) |
|
16 | ? $parsed[1] |
|
17 | : null; |
|
18 | $roles = explode('|', $parsed[0]); |
|
19 | } elseif (is_array($role)) { |
|
20 | $guard = isset($role['guard']) ? |
|
21 | $role['guard'] : null; |
|
22 | $roles = $role['role']; |
|
23 | } |
|
24 | if (auth($guard)->guest()) { |
|
25 | throw UnauthorizedException::notLoggedIn(); |
|
26 | } |
|
27 | ||
28 | if (!auth($guard)->user()->hasAnyRole($roles)) { |
|
29 | throw UnauthorizedException::forRoles($roles); |
|
30 | } |
|
31 | ||
32 | return $next($request); |
|
33 | } |
|
34 | } |
|
35 |