z-song / laravel-admin

Build a full-featured administrative interface in ten minutes
https://laravel-admin.org
MIT License
11.1k stars 2.81k forks source link

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

Open xpxw opened 7 months ago

xpxw commented 7 months ago

说明:

默认情况下,不支持 如 /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的,大家可以根据自己的需要去修改规则.