CasbinAuthMiddleware.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace app\agent\middleware;
  3. use app\agent\model\auth\Log;
  4. use CasbinAdapter\Think\Facades\AgentCasbin;
  5. use Lettered\Support\Auth as IAuth;
  6. use Lettered\Support\Exceptions\ForbiddenException;
  7. use CasbinAdapter\Think\Facades\Casbin;
  8. /**
  9. * 操作权限验证
  10. * Class CasbinAuthMiddleware
  11. * @package app\http\middleware
  12. */
  13. class CasbinAuthMiddleware
  14. {
  15. /**
  16. * @var IAuth
  17. */
  18. protected $auth;
  19. /**
  20. * CasbinAuthMiddleware constructor.
  21. * @param IAuth $auth
  22. */
  23. public function __construct(IAuth $auth)
  24. {
  25. // 这里要做下来源 是admin 还是agent
  26. $this->auth = $auth->guard('agent');
  27. }
  28. /**
  29. * Casbin 授权验证
  30. *
  31. * @author 许祖兴 < zuxing.xu@lettered.cn>
  32. * @date 2020/3/21 20:28
  33. *
  34. * @param $request
  35. * @param \Closure $next
  36. * @return mixed
  37. * @throws ForbiddenException
  38. * @throws \Casbin\Exceptions\CasbinException
  39. * @throws \Lettered\Support\Exceptions\FailedException
  40. * @throws \think\db\exception\DataNotFoundException
  41. * @throws \think\db\exception\ModelNotFoundException
  42. * @throws \think\exception\DbException
  43. */
  44. public function handle($request, \Closure $next)
  45. {
  46. // 操作权限验证 v0 v1 v2
  47. // Uid Uri Method
  48. // 当前用户
  49. $user = $this->auth->user();
  50. // 在这里替换空
  51. // $baseUrl = str_replace('/agent', '', $request->baseUrl());
  52. $baseUrl = $request->baseUrl();
  53. // 检查忽略项
  54. if (in_array($baseUrl . '^' . strtolower($request->method()), config('casbin.ignore.policy'))
  55. || in_array($user->id, str2arr(config('casbin.ignore.users_idx')))) {
  56. } elseif (!AgentCasbin::enforce('user_id_' . $user->id, $baseUrl, strtolower($request->method()))) {
  57. $baseUrl = str_replace('/agent', '', $request->baseUrl());
  58. if (!AgentCasbin::enforce('user_id_' . $user->id, $baseUrl, strtolower($request->method()))) {
  59. throw new ForbiddenException([
  60. 'errmsg' => 'Unauthorized: 您无权操作!' . enjson(['user_id_' . $user->id, $baseUrl, strtolower($request->method())])
  61. ]);
  62. }
  63. }
  64. // 操作记录
  65. $log =[
  66. 'user_id' => $user->id,
  67. 'route' => $request->baseUrl(),
  68. 'operate' => strtolower($request->method()),
  69. 'query' => enjson($request->param()),
  70. 'ip' => $request->ip(),
  71. 'os' => get_user_agent(),
  72. 'browser' => get_user_agent('br')
  73. ];
  74. $Log = new Log();
  75. // 系统日志记录
  76. $result = $Log::where($log)->find();
  77. if (!$result) {
  78. $Log::create($log);
  79. } else {
  80. $log['id'] = $result->id;
  81. $log['count'] = $result->count+1;
  82. $Log::update($log);
  83. }
  84. return $next($request);
  85. }
  86. }