Added basic logic for impersonation

This commit is contained in:
Jan Böhmer 2023-07-04 00:31:13 +02:00
parent 15e072a2ff
commit d20153c569
7 changed files with 163 additions and 27 deletions

View file

@ -46,6 +46,8 @@ use App\Entity\UserSystem\User;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Repository\LogEntryRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
@ -57,7 +59,7 @@ final class UserExtension extends AbstractExtension
{
private readonly LogEntryRepository $repo;
public function __construct(EntityManagerInterface $em)
public function __construct(EntityManagerInterface $em, private readonly Security $security)
{
$this->repo = $em->getRepository(AbstractLogEntry::class);
}
@ -76,9 +78,31 @@ final class UserExtension extends AbstractExtension
new TwigFunction('last_editing_user', fn(AbstractDBElement $element): ?User => $this->repo->getLastEditingUser($element)),
/* Returns the user which has created the given entity. */
new TwigFunction('creating_user', fn(AbstractDBElement $element): ?User => $this->repo->getCreatingUser($element)),
new TwigFunction('impersonator_user', $this->getImpersonatorUser(...)),
new TwigFunction('impersonation_active', $this->isImpersonationActive(...)),
];
}
/**
* This function returns the user which has impersonated the current user.
* If the current user is not impersonated, null is returned.
* @return User|null
*/
public function getImpersonatorUser(): ?User
{
$token = $this->security->getToken();
if ($token instanceof SwitchUserToken) {
return $token->getOriginalToken()->getUser();
}
return null;
}
public function isImpersonationActive(): bool
{
return $this->security->isGranted('IS_IMPERSONATOR');
}
/**
* This function/filter generates a path.
*/