icingaweb2/library/Icinga/Web/Dashboard/Common/DashboardUserManager.php
2023-07-14 20:05:35 +02:00

86 lines
1.8 KiB
PHP

<?php
/* Icinga Web 2 | (c) 2022 Icinga GmbH | GPLv2+ */
namespace Icinga\Web\Dashboard\Common;
use Icinga\Authentication\Auth;
use Icinga\Model\DashboardOwner;
use Icinga\User;
use Icinga\Util\DBUtils;
use ipl\Stdlib\Filter;
trait DashboardUserManager
{
/** @var User */
private static $user;
/**
* Init the current user
*
* Just ensures that the current user is stored in the DB
*
* @return void
*/
protected static function initUser()
{
if (! self::userExist()) {
$conn = DBUtils::getConn();
$conn->insert('icingaweb_dashboard_owner', ['username' => self::getUser()->getUsername()]);
self::getUser()->setAdditional('id', $conn->lastInsertId());
}
}
/**
* Set this dashboard's user
*
* @param User $user
*
* @return $this
*/
public function setUser(User $user): self
{
self::$user = $user;
self::initUser();
return $this;
}
/**
* Get this dashboard's user
*
* @return User
*/
public static function getUser(): User
{
if (self::$user === null) {
self::$user = Auth::getInstance()->getUser();
self::initUser();
}
return self::$user;
}
/**
* Get whether the current user is already in the database
*
* @return bool
*/
public static function userExist(): bool
{
$query = DashboardOwner::on(DBUtils::getConn())
->columns('id')
->filter(Filter::equal('username', self::getUser()->getUsername()));
$found = false;
$result = $query->execute();
if ($result->hasResult()) {
$found = true;
self::getUser()->setAdditional('id', $result->current()->id);
}
return $found;
}
}