Created
December 8, 2021 00:53
-
-
Save Sija/a42b9ca4e379260557381ee9b7aca81b to your computer and use it in GitHub Desktop.
Identify users in Laravel 8.x for Sentry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class EventServiceProvider extends ServiceProvider | |
{ | |
/** | |
* The subscriber classes to register. | |
* | |
* @var array | |
*/ | |
protected $subscribe = [ | |
'App\Listeners\SentrySubscriber', | |
]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Listeners; | |
use Illuminate\Auth\Events\Authenticated; | |
use Illuminate\Auth\Events\Login; | |
use Illuminate\Auth\Events\Logout; | |
use App\Models\User; | |
class SentrySubscriber | |
{ | |
/** | |
* Sets the given user for the current Sentry scope. | |
*/ | |
protected function setUserInScope($user) { | |
\Sentry\configureScope(function (\Sentry\State\Scope $scope) use ($user) { | |
if ($user) { | |
$scope->setUser([ | |
'id' => $user->id, | |
'name' => $user->name, | |
'email' => $user->email, | |
]); | |
} else { | |
$scope->removeUser(); | |
} | |
}); | |
} | |
/** | |
* Handle user authenticated events. | |
*/ | |
public function onUserAuthenticated(Authenticated $event) { | |
$this->setUserInScope($event->user); | |
} | |
/** | |
* Handle user login events. | |
*/ | |
public function onUserLogin(Login $event) { | |
$this->setUserInScope($event->user); | |
} | |
/** | |
* Handle user logout events. | |
*/ | |
public function onUserLogout(Logout $event) { | |
$this->setUserInScope(null); | |
} | |
/** | |
* Register the listeners for the subscriber. | |
* | |
* @param Illuminate\Events\Dispatcher $events | |
*/ | |
public function subscribe($events) | |
{ | |
$events->listen( | |
'Illuminate\Auth\Events\Authenticated', | |
'App\Listeners\SentrySubscriber@onUserAuthenticated' | |
); | |
$events->listen( | |
'Illuminate\Auth\Events\Login', | |
'App\Listeners\SentrySubscriber@onUserLogin' | |
); | |
$events->listen( | |
'Illuminate\Auth\Events\Logout', | |
'App\Listeners\SentrySubscriber@onUserLogout' | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment