| @@ 9-33 (lines=25) @@ | ||
| 6 | use Illuminate\Support\Facades\Auth; |
|
| 7 | use Spatie\Permission\Exceptions\UnauthorizedException; |
|
| 8 | ||
| 9 | class PermissionMiddleware |
|
| 10 | { |
|
| 11 | public function handle($request, Closure $next, $permission, $guard = null) |
|
| 12 | { |
|
| 13 | if (is_null($guard)) { |
|
| 14 | $guard = (require config_path('auth.php'))['defaults']['guard']; |
|
| 15 | } |
|
| 16 | ||
| 17 | if (Auth::guard($guard)->guest()) { |
|
| 18 | throw UnauthorizedException::notLoggedIn(); |
|
| 19 | } |
|
| 20 | ||
| 21 | $permissions = is_array($permission) |
|
| 22 | ? $permission |
|
| 23 | : explode('|', $permission); |
|
| 24 | ||
| 25 | foreach ($permissions as $permission) { |
|
| 26 | if (Auth::guard($guard)->user()->can($permission)) { |
|
| 27 | return $next($request); |
|
| 28 | } |
|
| 29 | } |
|
| 30 | ||
| 31 | throw UnauthorizedException::forPermissions($permissions); |
|
| 32 | } |
|
| 33 | } |
|
| 34 | ||
| @@ 9-31 (lines=23) @@ | ||
| 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, $guard = null) |
|
| 12 | { |
|
| 13 | if (is_null($guard)) { |
|
| 14 | $guard = (require config_path('auth.php'))['defaults']['guard']; |
|
| 15 | } |
|
| 16 | ||
| 17 | if (Auth::guard($guard)->guest()) { |
|
| 18 | throw UnauthorizedException::notLoggedIn(); |
|
| 19 | } |
|
| 20 | ||
| 21 | $roles = is_array($role) |
|
| 22 | ? $role |
|
| 23 | : explode('|', $role); |
|
| 24 | ||
| 25 | if (! Auth::guard($guard)->user()->hasAnyRole($roles)) { |
|
| 26 | throw UnauthorizedException::forRoles($roles); |
|
| 27 | } |
|
| 28 | ||
| 29 | return $next($request); |
|
| 30 | } |
|
| 31 | } |
|
| 32 | ||