tomkirsch/psession

此软件包的最新版本(v2.1.3)没有提供许可证信息。

CI4的持久化会话库

安装: 21

依赖者: 0

建议者: 0

安全性: 0

星星: 0

关注者: 1

分支: 0

开放问题: 0

类型:项目

v2.1.3 2024-03-24 00:50 UTC

This package is auto-updated.

Last update: 2024-09-24 01:58:26 UTC


README

此模块扩展CI的Session和DatabaseHandler类,以提供持久化会话功能。

安装

数据库

创建您的数据库表

CREATE TABLE IF NOT EXISTS `ci_sessions` (
  `id` varchar(40) NOT NULL,
  `user_id` int unsigned DEFAULT NULL,
  `ip_address` varchar(45) NOT NULL,
  `timestamp` int unsigned NOT NULL,
  `data` blob,
  primary key (id),
  KEY `user_timestamp` (`user_id`,`timestamp`)
) ENGINE=InnoDB

CREATE TABLE IF NOT EXISTS `ci_tokens` (
  `token_id` int unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int unsigned NOT NULL,
  `token_series` char(64) NOT NULL,
  `token_value` char(64) NOT NULL,
  `token_useragent` varchar(255) NOT NULL,
  `token_timestamp` int unsigned NOT NULL,
  primary key (token_id),
  KEY `user_series_useragent` (`user_id`,`token_series`,`token_useragent`(10))
) ENGINE=InnoDB

如果您没有某种类型的用户表,您也可以创建此模板并修改以满足您的需求

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int unsigned NOT NULL AUTO_INCREMENT,
  `user_email` varchar(255) NOT NULL,
  `user_password` varchar(255) NOT NULL,
  `user_attempts` smallint UNSIGNED DEFAULT 0,
  `user_lastseen` datetime DEFAULT NULL,
  `user_created` datetime NOT NULL,
  `user_modified` datetime NOT NULL,
  primary key (user_id)
) ENGINE=InnoDB

不要担心密码字段的区分大小写,因为它在PHP中使用password_hash()进行比较,而不是在MYSQL中。

CodeIgniter

打开 App\Config\Session.php 并设置驱动器/表名。请注意,$expiration和$regenerateDestroy将被覆盖,因此没有效果。

public string $driver = \Tomkirsch\Psession\PersistentDatabaseHandler::class;
public string $savePath = 'YOUR_DB_TABLE';

PsessionConfig.php复制到App\Config中,并修改值以满足您的需求(表名、字段名等)

确保您的加密密钥在app/Config/Encryption.php中已设置

	public $key = 'some string';

确保您的数据库连接在.env中已设置

打开app/config/Services.php并覆盖会话函数

	public static function session(Session $config = null, bool $getShared = true)
    {
        $config ??= config('Session');
        if ($getShared) {
            return static::getSharedInstance('session', $config);
        }

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

        $session = new Psession($driver, $config);
        $session->setLogger($logger);
        if (session_status() === PHP_SESSION_NONE) {
            $session->start();
        }
        return $session;
    }

您可以选择不启动会话,以便更多地控制会话启动的位置。

现在在您的控制器中使用它

class MyPage extends Controller{
	function index(){
		$session = service('session'); // attempts to read session from cookie, falling back on persistent cookies...
		if(empty($_SESSION['user_id'])){
			return $this->response->redirect('auth/login');
		}
		// user is logged in...
	}
}

class Auth extends Controller{
	protected function doLogin(string $email, string $password, bool $rememberMe){
		$session = service('session');
		// include session data, and find by email
		$user = $session->findSession()->where('user_email', $email)->get()->getFirstRow();
		if(!password_verify($password, $user->user_password)){
			// invalid login
		}else{
			// tell session that login was successful - this will set the persistent session cookies depending on $rememberMe
			$this->session->loginSuccess($user, $rememberMe);
			// save user data in $_SESSION
			$_SESSION['user_id'] = $user->user_id;
			// set 'remember me' cookie
			if($rememberMe){
				$this->response->setCookie([
					'name'=>'user_email',
					'value'=>$user->user_email,
					'expire'=> config('app')->persistentSessionExpiry,
					'secure' => TRUE,
					'httponly'=>TRUE,
					'samesite'=>'Lax',
				]);
			}else{
				$this->response->deleteCookie('user_email');
			}
		}
	}
	protected function doLogout(){
		$session = service('session');
		$session->destroy();
	}
}