CheckAuth.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. // 不登录访问,无需权限验证
  25. if (in_array($request->action, $noNeedLogin)) {
  26. return $handler($request);
  27. }
  28. // 登录信息
  29. $token = getCurrentInfo();
  30. if ($token === false) {
  31. throw new SystemException('权限不足,无法访问或操作');
  32. }
  33. // 系统默认超级管理员,无需权限验证
  34. if ($token['id'] === 1) {
  35. return $handler($request);
  36. }
  37. // 接口请求权限判断
  38. $path = $request->path();
  39. // 处理接口路由替换
  40. $replace = config('plugin.saiadmin.saithink.route_replace');
  41. if (isset($replace[$path])) {
  42. $path = $replace[$path];
  43. }
  44. $path = strtolower($path);
  45. // 用户权限缓存
  46. $userAuthCache = new UserAuthCache($token['id']);
  47. // 全部路由文件
  48. $routes = $this->formatUrl($userAuthCache->getAllUri());
  49. // 请求接口有权限配置则进行验证
  50. if (in_array($path, $routes)) {
  51. $allowCodes = $userAuthCache->getAdminUri() ?? [];
  52. $allowCodes = $this->formatUrl($allowCodes);
  53. if (!in_array($path, $allowCodes)) {
  54. throw new SystemException('权限不足,无法访问或操作');
  55. }
  56. }
  57. return $handler($request);
  58. }
  59. /**
  60. * 格式化URL
  61. * @param array $data
  62. * @return array|string[]
  63. */
  64. public function formatUrl(array $data): array
  65. {
  66. return array_map(function ($item) {
  67. return strtolower($item);
  68. }, $data);
  69. }
  70. }