From ca6067e48c938ffab87ebe36f72ebc36e1f8aaa9 Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Sun, 30 Apr 2023 17:34:59 +0200 Subject: [PATCH] app/library/Auth.php: adding impersonate() and impersonateClear() methods --- app/library/Auth.php | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/app/library/Auth.php b/app/library/Auth.php index 81750da..33a46f4 100644 --- a/app/library/Auth.php +++ b/app/library/Auth.php @@ -10,6 +10,7 @@ use App\Model\Data\User, class Auth extends Injectable { const SESSION_KEY = 'auth'; + const IMPERSONATEOR_ID = 'auth.impersonateor'; /** * Login using email/user + password combination. @@ -86,6 +87,34 @@ class Auth extends Injectable $this->eventsManager->fire('auth:onLogin', $this, 'System'); } + /** + * Impersonate a user + * + * @param User $user + */ + public function impersonate(User $user) + { + $current = $this->getIdentity(); + if ($current === null) { + throw new \InvalidArgumentException("Need to be authenticated to be able to impersonate someone"); + } + + if ($current->getId() === $user->getId()) { + // Same user + throw new \DomainException("Can't impersonate yourself"); + } + + $this->session->set(self::IMPERSONATEOR_ID, $current->getId()); + $this->setIdentity($user->getId()); + $this->eventsManager->fire('auth:onImpersonate', $this, $current); + } + + public function impersonateClear($imp_id) + { + $this->session->remove(self::IMPERSONATEOR_ID); + $this->session->set(self::SESSION_KEY, $imp_id); + } + /** * @param $identity * @return Auth @@ -135,7 +164,12 @@ class Auth extends Injectable */ public function clearIdentity() { - $this->session->remove(self::SESSION_KEY); + $imp_id = $this->session->get(self::IMPERSONATEOR_ID); + if ($imp_id !== null) { + $this->impersonateClear($imp_id); + } else { + $this->session->remove(self::SESSION_KEY); + } return $this; } }