Подскажите пожалуйста. После успешной аутентификации с $rememberMe = true и последующим закрытием браузера при попытке войти на страницу опять попадаю на "Логин", т.е. "запомнить меня" - не работает.
Кука ставится как положено(ниже фото), а после закрытия-открытия браузера удаляется каким-то образом.
По форуму полазИл, есть подобные темы, но все какое-то не то
Controller:
Код: Выделить всё
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\Srcs;
class SrcsController extends Controller
{
public $defaultAction = "login";
public function actionLogin()
{
if(Yii::$app->user->isGuest)
{
$LoginForm = new Srcs();
if($LoginForm->load(Yii::$app->request->post()))
{
if($LoginForm->validate())
{
Yii::$app->user->login($LoginForm->getUser(), $LoginForm->rememberMe ? 3600*24*30 : 0);
return $this->goHome();
}
else
{
Yii::$app->session->setFlash("username", $LoginForm->username);
Yii::$app->session->setFlash("forbidden", $LoginForm->errors);
return $this->refresh();
}
}
return $this->render("start_page", [
"LoginForm" => $LoginForm
]);
}
else
{
return $this->goHome();
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->redirect(["srcs/login"]);
}
public function actionError()
{
$exception = Yii::$app->errorHandler->exception;
if($exception !== null)
{
$statusCode = $exception->statusCode;
$name = $exception->getName();
$message = $exception->getMessage();
if(Yii::$app->user->isGuest)
{
$LoginForm = new Srcs();
return $this->render("error", [
"LoginForm" => $LoginForm,
"statusCode" => $statusCode,
"name" => $name,
"message" => $message,
]);
}
else
{
return $this->render("error", [
"statusCode" => $statusCode,
"name" => $name,
"message" => $message,
]);
}
}
}
}
Код: Выделить всё
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use app\models\User;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class Srcs extends ActiveRecord
{
public $username;
public $password;
public $rememberMe = true;
/**
* @return array the validation rules.
*/
public static function tableName()
{
return "srcs_users";
}
public function rules()
{
return [
// username and password are both required
['username', 'required', "message" => "Логин не может быть пустым"],
["password", "required", "message" => "Пароль не может быть пустым"],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors())
{
$user = $this->getUser();
if (!$user || !hash_equals($user->srcs_password, crypt($this->password, "$6$".$user->scrs_salt."rcs")))
{
$this->addError($attribute, 'Неверный логин/пароль.');
}
}
}
public function getUser()
{
return User::findOne(["srcs_username" => $this->username]);
}
}
Код: Выделить всё
<?php
namespace app\models;
use yii\db\ActiveRecord;
class User extends ActiveRecord implements \yii\web\IdentityInterface
{
public static function tableName()
{
return "srcs_users";
}
/**
* @inheritdoc
*/
public static function findIdentity($sid)
{
return self::findOne($sid);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
}
}
Код: Выделить всё
<?php
use yii\bootstrap\ActiveForm;
?>
<?php $this->beginBlock("login_form") ?>
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'method' => 'post',
'action' => ['srcs/login'],
'enableClientValidation' => false,
]) ?>
<div class="form-group">
<?= $form->field($LoginForm, 'username')->textInput(["value"=>Yii::$app->session->hasFlash("username") ? Yii::$app->session->getFlash("username") : NULL])->label("Логин") ?>
</div>
<div class="form-group">
<?= $form->field($LoginForm, 'password')->passwordInput()->label("Пароль") ?>
</div>
<div class="checkbox">
<?= $form->field($LoginForm, 'rememberMe')->checkbox()->label("Запомнить") ?>
</div><!--<input type="checkbox" name="rememberMe" checked="true">-->
<button type="submit" class="btn btn-primary btn-block" style="margin-bottom: 10px;">Вход</button>
<?php ActiveForm::end() ?>
<?php if(Yii::$app->session->hasFlash("forbidden")): ?>
<div class="alert alert-danger">
<?php foreach (Yii::$app->session->getFlash("forbidden") as $value): ?>
<p><?= $value[0] ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
<?php $this->endBlock() ?>
Код: Выделить всё
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'defaultRoute' => 'welcome/index',
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'sss',
'baseUrl' => '',
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'enableSession' => true,
'loginUrl' => array('srcs/login'),
],
'errorHandler' => [
'errorAction' => 'srcs/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;