123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- <?php
- namespace Encore\Admin\Middleware;
- use App\Services\SubsiteService;
- use Encore\Admin\Auth\Permission as Checker;
- use Encore\Admin\Facades\Admin;
- use Illuminate\Http\Request;
- use Illuminate\Support\Str;
- class Permission
- {
- /**
- * @var SubsiteService
- */
- private $subsiteService;
- /**
- * @var string
- */
- protected $middlewarePrefix = 'admin.permission:';
- /**
- * Authenticate constructor.
- * @param SubsiteService $subsiteService
- */
- public function __construct(SubsiteService $subsiteService)
- {
- $this->subsiteService = $subsiteService;
- }
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @param array $args
- *
- * @return mixed
- */
- public function handle(Request $request, \Closure $next, ...$args)
- {
- if (!Admin::user() || !empty($args) || $this->shouldPassThrough($request)) {
- return $next($request);
- }
- //处理分站权限
- if (!Admin::user()->canVisitSubsite(get_subsite_id())) {
- Checker::error("你没有该分站权限");
- }
- if ($this->checkRoutePermission($request)) {
- return $next($request);
- }
- if (!Admin::user()->allPermissions()->first(function ($permission) use ($request) {
- return $permission->shouldPassThrough($request);
- })) {
- Checker::error();
- }
- return $next($request);
- }
- /**
- * If the route of current request contains a middleware prefixed with 'admin.permission:',
- * then it has a manually set permission middleware, we need to handle it first.
- *
- * @param Request $request
- *
- * @return bool
- */
- public function checkRoutePermission(Request $request)
- {
- if (!$middleware = collect($request->route()->middleware())->first(function ($middleware) {
- return Str::startsWith($middleware, $this->middlewarePrefix);
- })) {
- return false;
- }
- $args = explode(',', str_replace($this->middlewarePrefix, '', $middleware));
- $method = array_shift($args);
- if (!method_exists(Checker::class, $method)) {
- throw new \InvalidArgumentException("Invalid permission method [$method].");
- }
- call_user_func_array([Checker::class, $method], [$args]);
- return true;
- }
- /**
- * Determine if the request has a URI that should pass through verification.
- *
- * @param \Illuminate\Http\Request $request
- *
- * @return bool
- */
- protected function shouldPassThrough($request)
- {
- $excepts = [
- admin_base_path('auth/login'),
- admin_base_path('auth/logout'),
- ];
- foreach ($excepts as $except) {
- if ($except !== '/') {
- $except = trim($except, '/');
- }
- if ($request->is($except)) {
- return true;
- }
- }
- return false;
- }
- }
|