From dbd16d6cbef974d37f35fff3785e63ab8448c2d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=91cze=20Bence?= Date: Sat, 13 Jun 2020 20:39:42 +0200 Subject: [PATCH] MAPG-131 create custom session handler for DB sessions --- src/Session/DatabaseSessionHandler.php | 113 +++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 src/Session/DatabaseSessionHandler.php diff --git a/src/Session/DatabaseSessionHandler.php b/src/Session/DatabaseSessionHandler.php new file mode 100644 index 0000000..a50a668 --- /dev/null +++ b/src/Session/DatabaseSessionHandler.php @@ -0,0 +1,113 @@ +columns(['data']); + $select->whereId($id); + + $result = $select->execute()->fetch(IResultSet::FETCH_ASSOC); + + if ($result === null) { + return ''; + } + + $this->exists = true; + + return $result['data']; + } + + public function write($id, $data): bool + { + $modify = new Modify(\Container::$dbConnection, 'sessions'); + + if ($this->exists) { + $modify->setId($id); + } else { + $modify->setExternalId($id); + } + + $modify->set('data', $data); + $modify->set('updated', (new DateTime())->format('Y-m-d H:i:s')); + $modify->save(); + + $written = true; + + return true; + } + + public function destroy($id): bool + { + $modify = new Modify(\Container::$dbConnection, 'sessions'); + $modify->setId($id); + $modify->delete(); + + return true; + } + + public function gc($maxlifetime): int + { + $select = new Select(\Container::$dbConnection, 'sessions'); + $select->columns(['id']); + $select->where('updated', '<', (new DateTime('-' . $maxlifetime . ' seconds'))->format('Y-m-d H:i:s')); + + $result = $select->execute(); + + while ($session = $result->fetch(IResultSet::FETCH_ASSOC)) { + $modify = new Modify(\Container::$dbConnection, 'sessions'); + $modify->setId($session['id']); + $modify->delete(); + } + + return true; + } + + public function create_sid(): string + { + return hash('sha256', random_bytes(10) . microtime()); + } + + public function validateId($id): bool + { + return preg_match('/^[a-f0-9]{64}$/', $id); + } + + public function updateTimestamp($id, $data): bool + { + if ($this->written) { + return true; + } + + $modify = new Modify(\Container::$dbConnection, 'sessions'); + + $modify->setId($id); + $modify->set('updated', (new DateTime())->format('Y-m-d H:i:s')); + $modify->save(); + + return true; + } +}