|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace DatPM\Sentry\Serverless\Middlewares; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use Sentry\State\Scope; |
| 7 | +use Illuminate\Http\Request; |
| 8 | +use Sentry\Laravel\Integration; |
| 9 | +use Sentry\Laravel\Tracing\Middleware; |
| 10 | +use Illuminate\Database\Eloquent\Model; |
| 11 | +use Illuminate\Contracts\Auth\Authenticatable; |
| 12 | +use Illuminate\Contracts\Container\BindingResolutionException; |
| 13 | + |
| 14 | +class ServerlessSentryMiddleware extends Middleware |
| 15 | +{ |
| 16 | + /** |
| 17 | + * Handle an incoming request. |
| 18 | + * |
| 19 | + * @param \Illuminate\Http\Request $request |
| 20 | + * @param \Closure $next |
| 21 | + * |
| 22 | + * @return mixed |
| 23 | + */ |
| 24 | + public function handle(Request $request, Closure $next) |
| 25 | + { |
| 26 | + $response = parent::handle($request, $next); |
| 27 | + |
| 28 | + $this->setUserData(auth()->user()); |
| 29 | + |
| 30 | + return $response; |
| 31 | + } |
| 32 | + |
| 33 | + protected function setUserData($authUser) |
| 34 | + { |
| 35 | + if (!$authUser instanceof Model) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + // If the user is a Laravel Eloquent model we try to extract some common fields from it |
| 40 | + $userData = [ |
| 41 | + 'id' => $authUser instanceof Authenticatable |
| 42 | + ? $authUser->getAuthIdentifier() |
| 43 | + : $authUser->getKey(), |
| 44 | + 'email' => $authUser->getAttribute('email') ?? $authUser->getAttribute('mail'), |
| 45 | + ]; |
| 46 | + |
| 47 | + try { |
| 48 | + /** @var \Illuminate\Http\Request $request */ |
| 49 | + $request = app()->make('request'); |
| 50 | + |
| 51 | + if ($request instanceof Request) { |
| 52 | + $ipAddress = $request->ip(); |
| 53 | + |
| 54 | + if ($ipAddress !== null) { |
| 55 | + $userData['ip_address'] = $ipAddress; |
| 56 | + } |
| 57 | + } |
| 58 | + } catch (BindingResolutionException $e) { |
| 59 | + // If there is no request bound we cannot get the IP address from it |
| 60 | + } |
| 61 | + |
| 62 | + Integration::configureScope(static function (Scope $scope) use ($userData): void { |
| 63 | + $scope->setUser(array_filter($userData)); |
| 64 | + }); |
| 65 | + } |
| 66 | + |
| 67 | + public function terminate(Request $request, $response): void |
| 68 | + { |
| 69 | + # Do nothing when the application is terminating |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * @param Request $request |
| 75 | + * @param $response |
| 76 | + * @return void |
| 77 | + */ |
| 78 | + public function parentTerminate(Request $request, $response) |
| 79 | + { |
| 80 | + parent::terminate($request, $response); |
| 81 | + } |
| 82 | +} |
| 83 | + |
0 commit comments