-
Notifications
You must be signed in to change notification settings - Fork 180
Improve logging of the user when he logged in programmatically #720
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cleptric
merged 12 commits into
getsentry:master
from
ste93cry:fix-user-context-filling
Jul 31, 2023
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
2471970
Implement a login listener to fill the Sentry User context
ste93cry b3863a1
Clean up no longer useful code from the `RequestListener` class
ste93cry 9059f8f
Update PHPStan baseline
ste93cry b4c2bfc
Move `symfony/security-http` to `require` section
ste93cry 7883164
Fix tests for the `LoginListener` class
ste93cry 847c4b3
Update PHPStan baseline (again)
ste93cry ab59358
Remove unneeded check
ste93cry 57c64b7
Avoid overwriting the user context on the scope in `RequestListener` …
ste93cry 05a2c3c
Add back listener for `kernel.request` event
ste93cry 52673a7
Rename data providers and reword test case descriptions
ste93cry ecf154b
Fix errors reported by PHPStan and update baseline
ste93cry 1f4e33b
Merge branch 'master' into fix-user-context-filling
cleptric File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
29 changes: 29 additions & 0 deletions
29
src/DependencyInjection/Compiler/AddLoginListenerTagPass.php
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Sentry\SentryBundle\DependencyInjection\Compiler; | ||
|
||
use Sentry\SentryBundle\EventListener\LoginListener; | ||
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; | ||
use Symfony\Component\DependencyInjection\ContainerBuilder; | ||
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent; | ||
use Symfony\Component\Security\Http\Event\LoginSuccessEvent; | ||
|
||
final class AddLoginListenerTagPass implements CompilerPassInterface | ||
{ | ||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function process(ContainerBuilder $container): void | ||
{ | ||
$listenerDefinition = $container->getDefinition(LoginListener::class); | ||
|
||
if (!class_exists(LoginSuccessEvent::class)) { | ||
$listenerDefinition->addTag('kernel.event_listener', [ | ||
'event' => AuthenticationSuccessEvent::class, | ||
'method' => 'handleAuthenticationSuccessEvent', | ||
]); | ||
} | ||
} | ||
} |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Sentry\SentryBundle\EventListener; | ||
|
||
use Sentry\State\HubInterface; | ||
use Sentry\State\Scope; | ||
use Sentry\UserDataBag; | ||
use Symfony\Component\HttpKernel\Event\RequestEvent; | ||
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; | ||
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; | ||
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; | ||
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent; | ||
use Symfony\Component\Security\Core\User\UserInterface; | ||
use Symfony\Component\Security\Http\Event\LoginSuccessEvent; | ||
|
||
final class LoginListener | ||
{ | ||
use KernelEventForwardCompatibilityTrait; | ||
|
||
/** | ||
* @var HubInterface The current hub | ||
*/ | ||
private $hub; | ||
|
||
/** | ||
* @var TokenStorageInterface|null The token storage | ||
*/ | ||
private $tokenStorage; | ||
|
||
/** | ||
* Constructor. | ||
* | ||
* @param HubInterface $hub The current hub | ||
* @param TokenStorageInterface|null $tokenStorage The token storage | ||
*/ | ||
public function __construct(HubInterface $hub, ?TokenStorageInterface $tokenStorage) | ||
{ | ||
$this->hub = $hub; | ||
$this->tokenStorage = $tokenStorage; | ||
} | ||
|
||
/** | ||
* This method is called for each request handled by the framework and | ||
* fills the Sentry scope with information about the current user. | ||
*/ | ||
public function handleKernelRequestEvent(RequestEvent $event): void | ||
{ | ||
if (null === $this->tokenStorage || !$this->isMainRequest($event)) { | ||
return; | ||
} | ||
|
||
$token = $this->tokenStorage->getToken(); | ||
|
||
if (null !== $token) { | ||
$this->updateUserContext($token); | ||
} | ||
} | ||
|
||
/** | ||
* This method is called after authentication was fully successful. It allows | ||
* to set information like the username of the currently authenticated user | ||
* and of the impersonator, if any, on the Sentry's context. | ||
*/ | ||
public function handleLoginSuccessEvent(LoginSuccessEvent $event): void | ||
{ | ||
$this->updateUserContext($event->getAuthenticatedToken()); | ||
} | ||
|
||
/** | ||
* This method is called when an authentication provider authenticates the | ||
* user. It is the event closest to {@see LoginSuccessEvent} in versions of | ||
* the framework where it doesn't exist. | ||
*/ | ||
public function handleAuthenticationSuccessEvent(AuthenticationSuccessEvent $event): void | ||
{ | ||
$this->updateUserContext($event->getAuthenticationToken()); | ||
} | ||
|
||
private function updateUserContext(TokenInterface $token): void | ||
{ | ||
if (!$this->isTokenAuthenticated($token)) { | ||
return; | ||
} | ||
|
||
$client = $this->hub->getClient(); | ||
|
||
if (null === $client || !$client->getOptions()->shouldSendDefaultPii()) { | ||
return; | ||
} | ||
|
||
$this->hub->configureScope(function (Scope $scope) use ($token): void { | ||
$user = $scope->getUser() ?? new UserDataBag(); | ||
|
||
if (null === $user->getId()) { | ||
$user->setId($this->getUserIdentifier($token->getUser())); | ||
} | ||
|
||
$impersonatorUser = $this->getImpersonatorUser($token); | ||
|
||
if (null !== $impersonatorUser) { | ||
$user->setMetadata('impersonator_username', $impersonatorUser); | ||
} | ||
|
||
$scope->setUser($user); | ||
}); | ||
} | ||
|
||
private function isTokenAuthenticated(TokenInterface $token): bool | ||
{ | ||
if (method_exists($token, 'isAuthenticated') && !$token->isAuthenticated()) { | ||
return false; | ||
} | ||
|
||
return null !== $token->getUser(); | ||
} | ||
|
||
/** | ||
* @param UserInterface|\Stringable|string|null $user | ||
*/ | ||
private function getUserIdentifier($user): ?string | ||
{ | ||
if ($user instanceof UserInterface) { | ||
if (method_exists($user, 'getUserIdentifier')) { | ||
return $user->getUserIdentifier(); | ||
} | ||
|
||
if (method_exists($user, 'getUsername')) { | ||
return $user->getUsername(); | ||
} | ||
} | ||
|
||
if (\is_string($user)) { | ||
return $user; | ||
} | ||
|
||
if (\is_object($user) && method_exists($user, '__toString')) { | ||
return (string) $user; | ||
} | ||
|
||
return null; | ||
} | ||
|
||
private function getImpersonatorUser(TokenInterface $token): ?string | ||
{ | ||
if ($token instanceof SwitchUserToken) { | ||
return $this->getUserIdentifier($token->getOriginalToken()->getUser()); | ||
} | ||
|
||
return null; | ||
} | ||
} |
This file contains hidden or 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
This file contains hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure about this requirement. And to be frank, even the previous one could be invasive in some edge cases...
Maybe it's out of scope for this PR, but I think we should move these two requirements to
require-dev
, and make the code that uses them optional.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree, definitely. However, making the code optional is a completely different topic that I don't want to tackle here. We need the
security-http
package mostly because of the event classes that are part of it IIRC.