Yii::$app->user->isGuest всегда true после логина в Yii2
Регистрация как-то работает, а вот с авторизацией проблемы.
В LoginForm::login() авторизация вроде как проходит нормально и в Yii::$app->user есть инфа о текущем юзере, но Yii::$app->user->isGuest всегда true во view всегда true и в сессии тоже пусто.
LoginForm.php
Код:
<?php
namespace appmodels;
use Yii;
use yiibaseModel;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class LoginForm extends Model
{
public $login;
public $pass;
public $rememberMe = true;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// login and password are both required
[['login', 'pass'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['pass', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->pass)) {
$this->addError($attribute, 'Неправильный логин или пароль.');
}
}
}
/**
* Logs in a user using the provided login and password.
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate())
{
$user = $this->getUser();
if (!$user->active)
{
$this->addError('login', 'Ваша учётная запись не активирована.');
return false;
}
return Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
public function attributeLabels()
{
return [
'login' => 'Логин',
'pass' => 'Пароль',
'rememberMe' => 'Запомнить меня'
];
}
/**
* Finds user by [[login]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false)
{
$this->_user = User::findByLogin($this->login);
}
return $this->_user;
}
}
namespace appmodels;
use Yii;
use yiibaseModel;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class LoginForm extends Model
{
public $login;
public $pass;
public $rememberMe = true;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// login and password are both required
[['login', 'pass'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['pass', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->pass)) {
$this->addError($attribute, 'Неправильный логин или пароль.');
}
}
}
/**
* Logs in a user using the provided login and password.
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate())
{
$user = $this->getUser();
if (!$user->active)
{
$this->addError('login', 'Ваша учётная запись не активирована.');
return false;
}
return Yii::$app->user->login($user, $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
public function attributeLabels()
{
return [
'login' => 'Логин',
'pass' => 'Пароль',
'rememberMe' => 'Запомнить меня'
];
}
/**
* Finds user by [[login]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false)
{
$this->_user = User::findByLogin($this->login);
}
return $this->_user;
}
}
Код:
<?php
namespace appmodels;
use Yii;
use yiibaseNotSupportedException;
use yiibehaviorsTimestampBehavior;
use yiidbActiveRecord;
use yiiwebIdentityInterface;
/**
* User model
*
* @property integer $id
* @property string $login
* @property string $pass
* @property string $password_reset_token
* @property string $email
* @property string $auth_key
* @property integer $status
* @property integer $created_at
* @property string $password write-only password
*/
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* @inheritdoc
*/
/*public function behaviors()
{
return [
TimestampBehavior::className(),
];
}*/
/**
* @inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by login
*
* @param string $login
* @return static|null
*/
public static function findBylogin($login)
{
return static::findOne(['login' => $login]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->pass);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->pass = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
//ВОССТАНОВЛЕНИЕ ПАРОЛЯ
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
namespace appmodels;
use Yii;
use yiibaseNotSupportedException;
use yiibehaviorsTimestampBehavior;
use yiidbActiveRecord;
use yiiwebIdentityInterface;
/**
* User model
*
* @property integer $id
* @property string $login
* @property string $pass
* @property string $password_reset_token
* @property string $email
* @property string $auth_key
* @property integer $status
* @property integer $created_at
* @property string $password write-only password
*/
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* @inheritdoc
*/
/*public function behaviors()
{
return [
TimestampBehavior::className(),
];
}*/
/**
* @inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by login
*
* @param string $login
* @return static|null
*/
public static function findBylogin($login)
{
return static::findOne(['login' => $login]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->pass);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->pass = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
//ВОССТАНОВЛЕНИЕ ПАРОЛЯ
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
Код:
'user' => [
'identityClass' => 'appmodelsUser',
'enableAutoLogin' => true,
],
'identityClass' => 'appmodelsUser',
'enableAutoLogin' => true,
],
В чём может быть проблема?
Код:
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
`created_at` int(11) NOT NULL,
`login` varchar(255) NOT NULL,
`auth_key` varchar(32) DEFAULT NULL,
`email_confirm_token` varchar(255) DEFAULT NULL,
`pass` varchar(255) NOT NULL,
`password_reset_token` varchar(255) DEFAULT NULL,
`email` varchar(255) NOT NULL,
`rights` tinyint(1) NOT NULL,
`active` tinyint(1) NOT NULL,
`status` smallint(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
`id` int(11) NOT NULL,
`created_at` int(11) NOT NULL,
`login` varchar(255) NOT NULL,
`auth_key` varchar(32) DEFAULT NULL,
`email_confirm_token` varchar(255) DEFAULT NULL,
`pass` varchar(255) NOT NULL,
`password_reset_token` varchar(255) DEFAULT NULL,
`email` varchar(255) NOT NULL,
`rights` tinyint(1) NOT NULL,
`active` tinyint(1) NOT NULL,
`status` smallint(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
Что такое "appmodelsUser"? Может туда надо все таки класс вашего юзера? Всю остальное не читал ибо много букоф
Цитата: kot_
Что такое "appmodelsUser"? Может туда надо все таки класс вашего юзера? Всю остальное не читал ибо много букоф
Уже решил. Проблема была в базе в поле status. Было 0, а надо 10...