LogOperation.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Dcat\Admin\Middleware;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Models\OperationLog as OperationLogModel;
  5. use Dcat\Admin\Support\Helper;
  6. use Illuminate\Http\Request;
  7. class LogOperation
  8. {
  9. /**
  10. * Handle an incoming request.
  11. *
  12. * @param \Illuminate\Http\Request $request
  13. * @param \Closure $next
  14. *
  15. * @return mixed
  16. */
  17. public function handle(Request $request, \Closure $next)
  18. {
  19. if ($this->shouldLogOperation($request)) {
  20. $user = Admin::user();
  21. $log = [
  22. 'user_id' => $user ? $user->id : 0,
  23. 'path' => substr($request->path(), 0, 255),
  24. 'method' => $request->method(),
  25. 'ip' => $request->getClientIp(),
  26. 'input' => json_encode($request->input()),
  27. ];
  28. try {
  29. OperationLogModel::create($log);
  30. } catch (\Exception $exception) {
  31. // pass
  32. }
  33. }
  34. return $next($request);
  35. }
  36. /**
  37. * @param Request $request
  38. *
  39. * @return bool
  40. */
  41. protected function shouldLogOperation(Request $request)
  42. {
  43. return config('admin.operation_log.enable')
  44. && !$this->inExceptArray($request)
  45. && $this->inAllowedMethods($request->method());
  46. }
  47. /**
  48. * Whether requests using this method are allowed to be logged.
  49. *
  50. * @param string $method
  51. *
  52. * @return bool
  53. */
  54. protected function inAllowedMethods($method)
  55. {
  56. $allowedMethods = collect(config('admin.operation_log.allowed_methods'))->filter();
  57. if ($allowedMethods->isEmpty()) {
  58. return true;
  59. }
  60. return $allowedMethods->map(function ($method) {
  61. return strtoupper($method);
  62. })->contains($method);
  63. }
  64. /**
  65. * Determine if the request has a URI that should pass through CSRF verification.
  66. *
  67. * @param \Illuminate\Http\Request $request
  68. *
  69. * @return bool
  70. */
  71. protected function inExceptArray($request)
  72. {
  73. foreach (config('admin.operation_log.except') as $except) {
  74. $except = admin_base_path($except);
  75. if ($except !== '/') {
  76. $except = trim($except, '/');
  77. }
  78. if (Helper::matchRequestPath($except)) {
  79. return true;
  80. }
  81. }
  82. return false;
  83. }
  84. }