75 lines
2.2 KiB
PHP
75 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace com\fwdekker\deathnotifier;
|
|
|
|
use com\fwdekker\deathnotifier\user\UserManager;
|
|
use Exception;
|
|
|
|
|
|
/**
|
|
* Starts a new user session, or continues an existing one.
|
|
*/
|
|
class StartSessionAction extends Action
|
|
{
|
|
/**
|
|
* @var array<string, mixed> the application's configuration
|
|
*/
|
|
private readonly array $config;
|
|
/**
|
|
* @var UserManager the manager to validate the session through
|
|
*/
|
|
private readonly UserManager $user_manager;
|
|
|
|
|
|
/**
|
|
* Constructs a new `StartSessionAction`.
|
|
*
|
|
* @param array<string, mixed> $config the application's configuration
|
|
* @param UserManager $user_manager the manager to validate the session through
|
|
*/
|
|
public function __construct(array $config, UserManager $user_manager)
|
|
{
|
|
parent::__construct(ActionMethod::GET, "start-session");
|
|
|
|
$this->config = $config;
|
|
$this->user_manager = $user_manager;
|
|
}
|
|
|
|
|
|
/**
|
|
* Starts a new user session, or continues an existing one.
|
|
*
|
|
* @return array{"logged_in": bool, "global_message"?: string} whether the user is logged in, and the message to be
|
|
* displayed at the top of the page, if any
|
|
* @throws ActionException if no CSRF token could be generated
|
|
*/
|
|
function handle(): array
|
|
{
|
|
$payload = [];
|
|
|
|
// Check if user is logged in
|
|
if (!isset($_SESSION["uuid"])) {
|
|
$payload["logged_in"] = false;
|
|
} else if ($this->user_manager->user_exists($_SESSION["uuid"])) {
|
|
$payload["logged_in"] = true;
|
|
} else {
|
|
// User account was deleted
|
|
session_destroy();
|
|
session_start();
|
|
try {
|
|
$_SESSION["token"] = Util::generate_csrf_token();
|
|
} catch (Exception) {
|
|
throw new ActionException("Failed to generate new CSRF token. Please try again later.", null);
|
|
}
|
|
|
|
$payload["logged_in"] = false;
|
|
}
|
|
|
|
// Read global message
|
|
if (isset($this->config["server"]["global_message"]) && trim($this->config["server"]["global_message"]) !== "")
|
|
$payload["global_message"] = trim($this->config["server"]["global_message"]);
|
|
|
|
return $payload;
|
|
}
|
|
}
|