Yii 2 — Попытка войти, но вернуться снова как гость. Как это решить?

Я пытаюсь войти в систему, используя пользовательскую модель User, но когда я пытаюсь войти, она оставляет меня в качестве гостя. Я имею в виду, когда я нажимаю кнопку входа в login.php просмотр, он возвращается на домашнюю страницу, но все еще как гость, а не зарегистрированный пользователь. Я не знаю, возникают ли у меня проблемы с печеньем или чем-то еще. Мне нужна помощь, пожалуйста.

Это моя пользовательская модель, названная Usuario.php

<?php

namespace app\models;

use Yii;

class Usuario extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{

public $authKey;

/**
* @inheritdoc
*/
public static function tableName()
{
return 'usuario';
}

/**
* @inheritdoc
*/
public function rules()
{
return [
[['rut', 'nombre', 'aPaterno', 'aMaterno', 'password', 'correo', 'direccion', 'telefono', 'idPerfil'], 'required'],
[['idPerfil', 'idSesion'], 'integer'],
[['rut', 'telefono'], 'string', 'max' => 15],
[['nombre', 'password', 'correo'], 'string', 'max' => 100],
[['aPaterno', 'aMaterno'], 'string', 'max' => 50],
[['direccion'], 'string', 'max' => 200],
[['idPerfil'], 'exist', 'skipOnError' => true, 'targetClass' => Perfil::className(), 'targetAttribute' => ['idPerfil' => 'idPerfil']],
[['idSesion'], 'exist', 'skipOnError' => true, 'targetClass' => Sesion::className(), 'targetAttribute' => ['idSesion' => 'idSesion']],
];
}

/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'rut' => 'Rut',
'nombre' => 'Nombre',
'aPaterno' => 'A Paterno',
'aMaterno' => 'A Materno',
'password' => 'Password',
'correo' => 'Correo',
'direccion' => 'Direccion',
'telefono' => 'Telefono',
'idPerfil' => 'Id Perfil',
'idSesion' => 'Id Sesion',
];
}

public function getIdPerfil0()
{
return $this->hasOne(Perfil::className(), ['idPerfil' => 'idPerfil']);
}

public function getIdSesion0()
{
return $this->hasOne(Sesion::className(), ['idSesion' => 'idSesion']);
}public static function findIdentity($rut)
{
return self::findOne(['rut' => $rut]);
}public static function findIdentityByAccessToken($token, $type = null)
{
throw new yii\base\NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}

public static function findByUsername($rut)
{
return self::findOne(['rut' => $rut]);
}

public function getId()
{
return $this->rut;
}

public function getAuthKey()
{
return $this->authKey;
}

public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}

public function validatePassword($password)
{
return $this->password === $password;
}
}

Это actionLogin() функция в SiteController.php

public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}

$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}

А это мой LoginForm.php

<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class LoginForm extends Model
{
public $rut;
public $password;
public $rememberMe = true;

private $_user = false;/**
* @return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['rut', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', '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->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}

/**
* Logs in a user using the provided username and password.
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}

/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = Usuario::findByUsername($this->rut);
}

return $this->_user;
}
}

0

Решение

Если вы снова видите страницу входа, эта строка возвращает false:

if ($model->load(Yii::$app->request->post()) && $model->login()) {

Итак, перед этой строкой, попробуйте проверить и проверить содержание ошибки член:

if(\Yii::$app->request->isPost)
{
$model->validate();
var_dump($model->errors);exit;
}

Вложение «Если» необходимо, в противном случае этот блок будет выполнен и при первом входе на страницу входа.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector