Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

让laravel-admin权限支持资源路由 #5843

Open
xpxw opened this issue Dec 13, 2023 · 0 comments
Open

让laravel-admin权限支持资源路由 #5843

xpxw opened this issue Dec 13, 2023 · 0 comments

Comments

@xpxw
Copy link

xpxw commented Dec 13, 2023

  • Laravel Version: 5.8
  • PHP Version:7.4
  • Laravel-admin: 18

说明:

默认情况下,不支持 如 /article/4/edit 或者 /article/4 这种编辑权限单独控制,如果用*通配符权限颗粒会太粗。

解决办法

复制LA的Permission模型到你自己的模型文件夹下,然后在配置文件中指定权限模型为你自己的模型类.我是放在 `App\Model下的,修改配置文件;

##修改 config/admin.php

// Permission table and model.
        'permissions_table' => 'admin_permissions',
        'permissions_model' => App\Model\Permission::class,

##然后在权限模型类文件中修改,不使用$request->is方法

protected function matchRequest(array $match, Request $request): bool
    {
        if ($match['path'] == '/') {
            $path = '/';
        } else {
            $path = trim($match['path'], '/');
        }

        /**
         * 原匹配仅支持*通配符,不支持 articles/1/edit
         * if (!$request->is($path)) {
         * return false;
         * }
         */

        #新增支持替换资源路由中的ID
        if (!self::matchPath($path, $request->decodedPath())) {
            return false;
        }

        $method = collect($match['method'])->filter()->map(function ($method) {
            return strtoupper($method);
        });

        return $method->isEmpty() || $method->contains($request->method());
    }

##增加方法

//**
#新增支持资源路由
*/

  public static function matchPath($pattern, $value)
   {
       $patterns = Arr::wrap($pattern);
       if (empty($patterns)) {
           return false;
       }

       foreach ($patterns as $pattern) {
           if ($pattern == $value) {
               return true;
           }
           $pattern = preg_quote($pattern, '#');
           $pattern = str_replace('\*', '.*', $pattern);

           if (preg_match("/\{.*?\}/",$pattern)) {
               $pattern = preg_replace('/\{.*?\}/', '\\d+', $pattern);
           }
           if (preg_match('#^' . $pattern . '\z#u', $value) === 1) {
               return true;
           }
       }
       return false;
   }

然后就可以在权限的路由中使用 /article/{article_id}/edit 这种模式了,我的主键全是自增int,所以替换成\d+就可以了,如果是uuid的,大家可以根据自己的需要去修改规则.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant