Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: DB Session Handler #5696

Merged
merged 6 commits into from
Mar 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 0 additions & 20 deletions phpstan-baseline.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -745,26 +745,6 @@ parameters:
count: 1
path: system/Session/Handlers/DatabaseHandler.php

-
message: "#^Property CodeIgniter\\\\Session\\\\Handlers\\\\BaseHandler\\:\\:\\$sessionID \\(string\\) in isset\\(\\) is not nullable\\.$#"
count: 1
path: system/Session/Handlers/DatabaseHandler.php

-
message: "#^Property CodeIgniter\\\\Session\\\\Handlers\\\\BaseHandler\\:\\:\\$sessionID \\(string\\) in isset\\(\\) is not nullable\\.$#"
count: 1
path: system/Session/Handlers/FileHandler.php

-
message: "#^Property CodeIgniter\\\\Session\\\\Handlers\\\\BaseHandler\\:\\:\\$sessionID \\(string\\) in isset\\(\\) is not nullable\\.$#"
count: 1
path: system/Session/Handlers/MemcachedHandler.php

-
message: "#^Property CodeIgniter\\\\Session\\\\Handlers\\\\BaseHandler\\:\\:\\$sessionID \\(string\\) in isset\\(\\) is not nullable\\.$#"
count: 1
path: system/Session/Handlers/RedisHandler.php

-
message: "#^Strict comparison using \\=\\=\\= between string and true will always evaluate to false\\.$#"
count: 1
Expand Down
20 changes: 19 additions & 1 deletion system/Config/Services.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
use CodeIgniter\Router\RouteCollectionInterface;
use CodeIgniter\Router\Router;
use CodeIgniter\Security\Security;
use CodeIgniter\Session\Handlers\Database\MySQLiHandler;
use CodeIgniter\Session\Handlers\Database\PostgreHandler;
use CodeIgniter\Session\Handlers\DatabaseHandler;
use CodeIgniter\Session\Session;
use CodeIgniter\Throttle\Throttler;
use CodeIgniter\Typography\Typography;
Expand All @@ -58,6 +61,7 @@
use Config\App;
use Config\Cache;
use Config\ContentSecurityPolicy as CSPConfig;
use Config\Database;
use Config\Email as EmailConfig;
use Config\Encryption as EncryptionConfig;
use Config\Exceptions as ExceptionsConfig;
Expand Down Expand Up @@ -585,7 +589,21 @@ public static function session(?App $config = null, bool $getShared = true)
$logger = AppServices::logger();

$driverName = $config->sessionDriver;
$driver = new $driverName($config, AppServices::request()->getIPAddress());

if ($driverName === DatabaseHandler::class) {
samsonasik marked this conversation as resolved.
Show resolved Hide resolved
$DBGroup = $config->sessionDBGroup ?? config(Database::class)->defaultGroup;
$db = Database::connect($DBGroup);

$driver = $db->getPlatform();

if ($driver === 'MySQLi') {
$driverName = MySQLiHandler::class;
} elseif ($driver === 'Postgre') {
$driverName = PostgreHandler::class;
}
}

$driver = new $driverName($config, AppServices::request()->getIPAddress());
$driver->setLogger($logger);

$session = new Session($driver, $config);
Expand Down
2 changes: 1 addition & 1 deletion system/Database/BaseConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ public function getPrefix(): string
}

/**
* The name of the platform in use (MySQLi, mssql, etc)
* The name of the platform in use (MySQLi, Postgre, SQLite3, OCI8, etc)
*/
public function getPlatform(): string
{
Expand Down
2 changes: 1 addition & 1 deletion system/Session/Handlers/BaseHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ abstract class BaseHandler implements SessionHandlerInterface
/**
* Current session ID
*
* @var string
* @var string|null
*/
protected $sessionID;

Expand Down
53 changes: 53 additions & 0 deletions system/Session/Handlers/Database/MySQLiHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Session\Handlers\Database;

use CodeIgniter\Session\Handlers\DatabaseHandler;

/**
* Session handler for MySQLi
*/
class MySQLiHandler extends DatabaseHandler
{
/**
* Lock the session.
*/
protected function lockSession(string $sessionID): bool
{
$arg = md5($sessionID . ($this->matchIP ? '_' . $this->ipAddress : ''));
if ($this->db->query("SELECT GET_LOCK('{$arg}', 300) AS ci_session_lock")->getRow()->ci_session_lock) {
$this->lock = $arg;

return true;
}

return $this->fail();
}

/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}

if ($this->db->query("SELECT RELEASE_LOCK('{$this->lock}') AS ci_session_lock")->getRow()->ci_session_lock) {
$this->lock = false;

return true;
}

return $this->fail();
}
}
100 changes: 100 additions & 0 deletions system/Session/Handlers/Database/PostgreHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Session\Handlers\Database;

use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Session\Handlers\DatabaseHandler;
use ReturnTypeWillChange;

/**
* Session handler for Postgre
*/
class PostgreHandler extends DatabaseHandler
{
/**
* Sets SELECT clause
*/
protected function setSelect(BaseBuilder $builder)
{
$builder->select("encode(data, 'base64') AS data");
}

/**
* Decodes column data
*
* @param mixed $data
*
* @return false|string
*/
protected function decodeData($data)
{
return base64_decode(rtrim($data), true);
}

/**
* Prepare data to insert/update
*/
protected function prepareData(string $data): string
{
return '\x' . bin2hex($data);
}

/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
$separator = '\'';
$interval = implode($separator, ['', "{$max_lifetime} second", '']);

return $this->db->table($this->table)->where('timestamp <', "now() - INTERVAL {$interval}", false)->delete() ? 1 : $this->fail();
}

/**
* Lock the session.
*/
protected function lockSession(string $sessionID): bool
{
$arg = "hashtext('{$sessionID}')" . ($this->matchIP ? ", hashtext('{$this->ipAddress}')" : '');
if ($this->db->simpleQuery("SELECT pg_advisory_lock({$arg})")) {
$this->lock = $arg;

return true;
}

return $this->fail();
}

/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}

if ($this->db->simpleQuery("SELECT pg_advisory_unlock({$this->lock})")) {
$this->lock = false;

return true;
}

return $this->fail();
}
}
Loading