LogOperation.php 2.8 KB

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