Archived
1
0
Fork 0

app/library/Auth.php: adding impersonate() and impersonateClear() methods

This commit is contained in:
Henrik Hautakoski 2023-04-30 17:34:59 +02:00
parent 1214b39502
commit ca6067e48c

View file

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