You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.4 KiB
41 lines
1.4 KiB
<?php |
|
|
|
namespace App\Http\Middleware; |
|
|
|
use Closure; |
|
use Illuminate\Http\Request; |
|
use Spatie\Permission\Exceptions\UnauthorizedException; |
|
use Symfony\Component\HttpFoundation\Response; |
|
|
|
class PermissionMiddleware |
|
{ |
|
/** |
|
* Handle an incoming request. |
|
* |
|
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next |
|
*/ |
|
public function handle($request, Closure $next, $permission, $guard = null) |
|
{ |
|
// dd(auth('api')->user()->can("user-list"), auth('api')->user()); |
|
$authGuard = app('auth')->guard($guard); |
|
if (auth()->guest()) { |
|
// return to login page with unauthorized message session |
|
// return response()->json(['message' => 'Unauthenticated.'], 401); |
|
return redirect()->route('login')->with('error', '請先登入'); |
|
// throw UnauthorizedException::notLoggedIn(); |
|
} |
|
|
|
$permissions = is_array($permission) |
|
? $permission |
|
: explode('|', $permission); |
|
|
|
foreach ($permissions as $permission) { |
|
// dd($authGuard->user(), $permission, $authGuard->user()->can($permission)); |
|
if ($authGuard->user()->can($permission)) { |
|
return $next($request); |
|
} |
|
} |
|
return redirect()->route('system.dashboard')->with('error', '您無權限訪問此頁面'); |
|
// throw UnauthorizedException::forPermissions($permissions); |
|
} |
|
}
|
|
|