MerchantAuthMiddleware.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\middleware;
  12. use app\common\repositories\system\auth\MenuRepository;
  13. use app\common\repositories\system\auth\RoleRepository;
  14. use app\Request;
  15. use think\exception\ValidateException;
  16. use think\Response;
  17. class MerchantAuthMiddleware extends BaseMiddleware
  18. {
  19. public function before(Request $request)
  20. {
  21. $admin = $request->adminInfo();
  22. /** @var RoleRepository $role */
  23. $role = app()->make(RoleRepository::class);
  24. /** @var MenuRepository $menu */
  25. $menu = app()->make(MenuRepository::class);
  26. if ($admin->level) {
  27. $rules = $role->idsByRules($request->merId(), $admin->roles);
  28. $menus = $menu->idsByRoutes($rules);
  29. } else {
  30. $rules = [];
  31. $menus = [];
  32. }
  33. $request->macro('adminAuth', function () use (&$menus) {
  34. return $menus;
  35. });
  36. $request->macro('adminRule', function () use (&$rules) {
  37. return $rules;
  38. });
  39. $request->macro('checkAuth', function ($name, $vars) use (&$admin, &$menus, &$menu) {
  40. if (!$name || !$admin->level) return true;
  41. $isset = false;
  42. foreach ($menus as $_menu) {
  43. $keys = $menu->tidyParams($_menu['params']);
  44. if ($_menu['route'] != $name) continue;
  45. $isset = true;
  46. if (!count($keys)) return true;
  47. if ($menu->checkParams($keys, $vars))
  48. return true;
  49. }
  50. if ($isset || $menu->routeExists($name))
  51. return false;
  52. return true;
  53. });
  54. $rule = $request->rule();
  55. if (!$request->checkAuth($rule->getName(), $rule->getVars()))
  56. throw new ValidateException('没有权限访问');
  57. }
  58. public function after(Response $response)
  59. {
  60. // TODO: Implement after() method.
  61. }
  62. }