对不起,我“取消删除”了我的问题,但是我想为可能有类似问题的其他人回答。 (在下面->评论)
我现在正在从事一个不需要用户标识(SessionID)的项目,除了用于维护的登录。
所以我想阻止Yii2自动启动会话,因为SessionID仍需要根据GDPR的规则进行选择。 (至少还没有其他的判决或发布。)
我现在的问题是,随着所选会话的打开,登录不再起作用。
我从以下位置更改了会话功能:
public function open()
to
public function open($acceptSC = false)
现在,我可以在任何需要的地方打开会话,但登录将不再起作用。
我尝试使用LoginForm中的登录名打开它:
public function validateSC() {
if ($this->validate()) {
if ($this->acceptSC {
Yii::$app->session->open(true);
return true;
} else {
return false;
}
}
}
public function login(){
if ($this->validate() && $this->validateSC()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
并且我试图(只是为了搜索问题)在main.php或login.php中打开一个会话。没用。
通过调试收费栏,我发现了一些东西。
在日志中:
...
< 3ms >
info yii\web\Session::open Session started
..\basic\models\LoginForm.php:64
..\basic\models\LoginForm.php:78
..\basic\controllers\SiteController.php:220
< 1ms >
info yii\web\User::login User '100' logged in from ::1 with duration 0.
..\basic\models\LoginForm.php:79
..\basic\controllers\SiteController.php:220
...
在请求下:
...
$_COOKIE
Empty.
...
我看到该会话尚未注册,仅此而已。 (缺少SessionID)
无论如何,一旦我让Yii2再次“自动启动”会话,登录就可以工作。
[如果有人知道可能出什么问题,请在下面写下。感谢您的帮助。
[我找到了一种方法,只有在确认使用得到任何用户的认可后,才可以在YII2中启动SessionID。
要实现这一点,您需要第二个函数,如果满足某些条件,该函数将打开会话。
示例:
/**
* Starts the session if $bool || isset($_COOKIE["acceptC"])
*
* for delaying the start of the session for after approval by the user
*/
public function open($bool)
{
if(isset($_COOKIE["cookieApproval"])) {
$this->openBase();
} else {
if($bool){
$this->openBase();
}
}
}
/**
* Start the session
*/
public function openBase()
{
if ($this->getIsActive()) {
return;
}
$this->registerSessionHandler();
$this->setCookieParamsInternal();
YII_DEBUG ? session_start() : @session_start();
if ($this->getIsActive()) {
Yii::info('Session started', __METHOD__);
$this->updateFlashCounters();
} else {
$error = error_get_last();
$message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
Yii::error($message, __METHOD__);
}
}
为了进行验证,我采用了一种懒惰的方式,因为我不需要每个用户都选择加入。仅在用户登录后才打开会话。
//checking if user checked accept cookies
public function validateCC(){
if($this->acceptCookie){
return true;
} else {
$this->addError('acceptCookie', 'We are sorry, without the needed cookies the login function does not work.');
return false;
}
}
//opening session
public function openSSession(){
Yii::$app->session->open(true);
}
//opening creating "cookie approval" cookie
public function openSCookie(){
$cookie = new Cookie([
'name'=>'cookieApproval',
'value'=>'true',
]);
Yii::$app->getResponse()->getCookies()->add($cookie);
}
/**
* Logs in a User if:
* username == true
* passwort == true
* coockie == checked
*/
public function login()
{
if ($this->validate() && $this->validateCC()) {
$this->openSCookie();
$this->openSSession();
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}