soko-web/src/Session/DatabaseSessionHandler.php
Pőcze Bence 72fc78220f
All checks were successful
soko-web/pipeline/pr-master This commit looks good
check session validity by DatabaseSessionHandler
2023-05-02 12:37:31 +02:00

122 lines
2.8 KiB
PHP

<?php namespace SokoWeb\Session;
use DateTime;
use SokoWeb\Database\Query\Modify;
use SokoWeb\Database\Query\Select;
use SokoWeb\Interfaces\Database\IConnection;
use SokoWeb\Interfaces\Database\IResultSet;
use SokoWeb\Interfaces\Session\ISessionHandler;
class DatabaseSessionHandler implements ISessionHandler
{
private IConnection $dbConnection;
private string $table;
private DateTime $shouldBeNewerThan;
private bool $exists = false;
private bool $written = false;
public function __construct(IConnection $dbConnection, string $table, DateTime $shouldBeNewerThan)
{
$this->dbConnection = $dbConnection;
$this->table = $table;
$this->shouldBeNewerThan = $shouldBeNewerThan;
}
public function open($savePath, $sessionName): bool
{
return true;
}
public function close(): bool
{
return true;
}
public function read($id): string
{
$select = new Select($this->dbConnection, $this->table);
$select->columns(['data', 'updated']);
$select->whereId(substr($id, 0, 32));
$result = $select->execute()->fetch(IResultSet::FETCH_ASSOC);
if ($result === null) {
return '';
}
$this->exists = true;
if (new DateTime($result['updated']) < $this->shouldBeNewerThan) {
return '';
}
return $result['data'];
}
public function write($id, $data): bool
{
$modify = new Modify($this->dbConnection, $this->table);
if ($this->exists) {
$modify->setId(substr($id, 0, 32));
} else {
$modify->setExternalId(substr($id, 0, 32));
}
$modify->set('data', $data);
$modify->set('updated', (new DateTime())->format('Y-m-d H:i:s'));
$modify->save();
$this->written = true;
return true;
}
public function destroy($id): bool
{
$modify = new Modify($this->dbConnection, $this->table);
$modify->setId(substr($id, 0, 32));
$modify->delete();
$this->exists = false;
return true;
}
public function gc($maxlifetime): bool
{
// empty on purpose
// old sessions are deleted by MaintainDatabaseCommand
return true;
}
public function create_sid(): string
{
return bin2hex(random_bytes(16));
}
public function validateId($id): bool
{
return preg_match('/^[a-f0-9]{32}$/', $id) === 1;
}
public function updateTimestamp($id, $data): bool
{
if ($this->written) {
return true;
}
$modify = new Modify($this->dbConnection, $this->table);
$modify->setId(substr($id, 0, 32));
$modify->set('updated', (new DateTime())->format('Y-m-d H:i:s'));
$modify->save();
return true;
}
}