CheckAuth.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. namespace plugin\saiadmin\app\middleware;
  8. use ReflectionClass;
  9. use Webman\Http\Request;
  10. use Webman\Http\Response;
  11. use Webman\MiddlewareInterface;
  12. use plugin\saiadmin\app\cache\UserAuthCache;
  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. // 通过反射获取控制器哪些方法不需要登录
  22. $controller = new ReflectionClass($request->controller);
  23. $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];
  24. print_r($request->action);
  25. print_r($noNeedLogin);
  26. // 不登录访问,无需权限验证
  27. if (in_array($request->action, $noNeedLogin)) {
  28. return $handler($request);
  29. }
  30. // 登录信息
  31. $token = getCurrentInfo();
  32. if ($token === false) {
  33. throw new SystemException('权限不足,无法访问或操作');
  34. }
  35. // 系统默认超级管理员,无需权限验证
  36. if ($token['id'] === 1) {
  37. return $handler($request);
  38. }
  39. // 接口请求权限判断
  40. $path = $request->path();
  41. // 处理接口路由替换
  42. $replace = config('plugin.saiadmin.saithink.route_replace');
  43. if (isset($replace[$path])) {
  44. $path = $replace[$path];
  45. }
  46. $path = strtolower($path);
  47. // 用户权限缓存
  48. $userAuthCache = new UserAuthCache($token['id']);
  49. // 全部路由文件
  50. $routes = $this->formatUrl($userAuthCache->getAllUri());
  51. // 请求接口有权限配置则进行验证
  52. if (in_array($path, $routes)) {
  53. $allowCodes = $userAuthCache->getAdminUri() ?? [];
  54. $allowCodes = $this->formatUrl($allowCodes);
  55. if (!in_array($path, $allowCodes)) {
  56. throw new SystemException('权限不足,无法访问或操作');
  57. }
  58. }
  59. return $handler($request);
  60. }
  61. /**
  62. * 格式化URL
  63. * @param array $data
  64. * @return array|string[]
  65. */
  66. public function formatUrl(array $data): array
  67. {
  68. return array_map(function ($item) {
  69. return strtolower($item);
  70. }, $data);
  71. }
  72. }