CasbinAuthMiddleware.php 2.5 KB

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