123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- <?php
- namespace app\admin\middleware;
- use app\admin\attr\Permission;
- use app\common\exception\CatchException;
- use app\common\model\Admin;
- use app\common\model\Role;
- use think\Request;
- class CheckPermissionAttr
- {
- public function handle(Request $request, \Closure $next)
- {
-
- $admin = app(Admin::class);
- $role = $admin->role;
- $codes = $role->codes;
-
- if (in_array(Role::CODE_SUPER_ADMIN, $codes)) {
- return $next($request);
- }
-
- $controller = $request->controller();
- $controllerNameSpace = 'app\\admin\\controller\\' . $controller;
- $ref = new \ReflectionClass($controllerNameSpace);
- $attrs = $ref->getAttributes(Permission::class);
- $methodName = $request->action();
- $method = $ref->getMethod($methodName);
- $methodAttrs = $method->getAttributes(Permission::class);
-
- if ($methodAttrs) {
- foreach ($methodAttrs as $attrRaw) {
-
- $attr = $attrRaw->newInstance();
-
- if ($attr->ignore) {
- return $next($request);
- }
-
- $permission = $attr->value;
-
- if ($attr->inherit) {
- if (count($attrs) > 1) {
- throw new \InvalidArgumentException('使用了继承权限值,但是controller的权限Attribute不止一个');
- }
- $controllerAttr = $attrs[0]->newInstance();
- $controllerPermission = $controllerAttr->value;
-
-
- if (!$permission) {
- if ($controllerAttr->useMethodName) {
- $permission = "$controllerPermission.$methodName";
- } else {
- $permission = $controllerPermission;
- }
- }
- } else {
-
- if (!$permission) {
- if (count($attrs) > 1) {
- throw new \InvalidArgumentException('没有使用继承,而且权限值为空,尝试使用controller权限值规则,但是controller的权限Attribute不止一个');
- }
- $controllerAttr = $attrs[0]->newInstance();
- $controllerPermission = $controllerAttr->value;
-
-
- if ($controllerAttr->useMethodName) {
- $permission = $methodName;
- } else {
-
- $permission = strtolower($controller);
- }
- }
-
- }
-
- if (!in_array($permission, $codes)) {
- throw new CatchException("未具有权限$permission, 禁止访问", 403);
- }
-
- return $next($request);
- }
- }
-
-
- foreach ($attrs as $attrRaw) {
-
- $attr = $attrRaw->newInstance();
- $permission = $attr->value;
-
- if ($attr->useMethodName) {
- $permission = "$permission.$methodName";
- } elseif (!$permission) {
-
- $permission = strtolower($controller);
- }
- if (!in_array($permission, $codes)) {
- throw new CatchException("未具有权限$permission, 禁止访问", 403);
- }
- }
- return $next($request);
- }
- }
|