CheckAuth.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. namespace plugin\saiadmin\app\middleware;
  8. use Webman\Http\Request;
  9. use Webman\Http\Response;
  10. use Webman\MiddlewareInterface;
  11. use plugin\saiadmin\app\cache\UserAuthCache;
  12. use plugin\saiadmin\app\cache\ReflectionCache;
  13. use plugin\saiadmin\exception\SystemException;
  14. /**
  15. * 权限检查中间件
  16. */
  17. class CheckAuth implements MiddlewareInterface
  18. {
  19. public function process(Request $request, callable $handler) : Response
  20. {
  21. $controller = $request->controller;
  22. $action = $request->action;
  23. // 通过反射获取控制器哪些方法不需要登录
  24. $noNeedLogin = ReflectionCache::getNoNeedLogin($controller);
  25. // 不登录访问,无需权限验证
  26. if (in_array($action, $noNeedLogin)) {
  27. return $handler($request);
  28. }
  29. // 登录信息
  30. $token = getCurrentInfo();
  31. if ($token === false) {
  32. throw new SystemException('用户信息读取失败,无法访问或操作');
  33. }
  34. // 系统默认超级管理员,无需权限验证
  35. if ($token['id'] === 1) {
  36. return $handler($request);
  37. }
  38. // 2. 获取接口权限属性 (使用缓存类)
  39. $permissions = ReflectionCache::getPermissionAttributes($controller, $action);
  40. if (!empty($permissions) && !empty($permissions['slug'])) {
  41. // 用户权限缓存
  42. $auth = UserAuthCache::getUserAuth($token['id']);
  43. if (!$this->checkPermissions($permissions, $auth)) {
  44. throw new SystemException('权限不足,无法访问或操作');
  45. }
  46. }
  47. return $handler($request);
  48. }
  49. /**
  50. * 检查权限
  51. */
  52. private function checkPermissions(array $attr, array $userPermissions): bool
  53. {
  54. // 直接对比 slug
  55. return in_array($attr['slug'], $userPermissions);
  56. }
  57. }