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; } }