From 30218d6f8004c7c9009a0917175d026eaef0e070 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Fromme?= Date: Wed, 17 Apr 2024 17:59:22 +0200 Subject: [PATCH] feat: improve user impersonation using dedicated voter --- config/packages/security.yaml | 2 +- src/Security/Voter/ImpersonationVoter.php | 45 +++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/Security/Voter/ImpersonationVoter.php diff --git a/config/packages/security.yaml b/config/packages/security.yaml index d56bb39..04d7aa8 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -22,7 +22,7 @@ security: custom_authenticators: - App\Security\BpnAuthenticator switch_user: - role: ROLE_ADMIN + role: CAN_IMPERSONATE logout: path: app_security_logout target: app_security_login diff --git a/src/Security/Voter/ImpersonationVoter.php b/src/Security/Voter/ImpersonationVoter.php new file mode 100644 index 0000000..691301b --- /dev/null +++ b/src/Security/Voter/ImpersonationVoter.php @@ -0,0 +1,45 @@ +getUser(); + $targetUser = $subject; + + // if the user is anonymous or if the subject is not a user, do not grant access + if (!$currentUser instanceof User || !$targetUser instanceof User) { + return false; + } + + // if the current user is trying to impersonate herself, do not grant access + if ($currentUser === $targetUser) { + return false; + } + + // if the current user is already impersonating, do not grant access + if ($this->security->isGranted('IS_IMPERSONATOR')) { + return false; + } + + // Admin is the only role allowed to impersonate + return $this->security->isGranted('ROLE_ADMIN'); + } +}