V
V
vitaly_742019-01-30 00:36:46
This
vitaly_74, 2019-01-30 00:36:46

Why doesn't authorization (authentication) work in Yii2?

Tell me what could be the error, I'm trying to write authorization, but nothing comes out. the problem is that when trying to pass identity to \Yii::$app->user->login, for some reason the data is not saved in the session, and in cookies too.
Here is the action I'm processing:

function actionLogin () {
        $form_model = new trForm(); //создает модель

        if($form_model->load(\Yii::$app->request->post())){//лоудим модель получаем данные из формы. (емайл,пароль)

            $dataUser = $form_model::findIdentity($form_model->email); //ищем пользователя по email

            $validatePassword = $form_model->validatePassword($form_model->pass,$dataUser->hash); //получаем и сравниваем хеш и бд
            if($validatePassword && $dataUser){ //если все ок то аутефицируем пользвателя

                \Yii::$app->user->login($form_model,1000*60*60*24); //логиним
                echo '<pre>';
                var_export(\Yii::$app->session); //сессии пустые.
                // \Yii::$app->user->enableSession - true
                echo '</pre>';
                die;

               return $this->redirect('admin'); //редириктим в админку.
            }
        }
        return $this->render("login", compact('form_model'));//передает модель в вид login
    }

here is the model itself, which appears in this action:
<?php
/**
 * Created by PhpStorm.
 * User: Vitaly
 * Date: 26.01.2019
 * Time: 2:33
 */

namespace app\models;


use yii\base\Model;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class trForm extends ActiveRecord implements IdentityInterface
{
    public $email;
    public $pass;
    public $username;

    public function rules() {
        return [[['email', 'pass'], 'required']
            ];

    }
    public static function tableName()
    {
        return '{{user}}';
    }
    public function validatePassword($password,$hash)
    {
       return \Yii::$app->security->validatePassword($password,$hash);
    }


    /**
     * Finds an identity by the given ID.
     * @param string|int $id the ID to be looked for
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($email)
    {
        $dataUser = User::find()->where(['email'=>$email])->one();
        return $dataUser;
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return User::findOne(['authKey'=>$token]);
        // TODO: Implement findIdentityByAccessToken() method.
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|int an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        // TODO: Implement getId() method.
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        return \Yii::$app->security->generateRandomKey();
        // TODO: Implement getAuthKey() method.
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @param string $authKey the given auth key
     * @return bool whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey()===$authKey;
        // TODO: Implement validateAuthKey() method.
    }
}

I display separately $form_model - everything is displayed normally, but for some reason there is no logging (

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2019-01-30
@webinar

trying to pass identity to \Yii::$app->user->login

the fact of the matter is that you are not passing identity , but the form model
$dataUser = $form_model::findIdentity($form_model->email); // тут identity
\Yii::$app->user->login($form_model,1000*60*60*24); //а вот что передаете

PS: By the way, I do not quite understand what is the point of referring to findIdentity as a static method. Since there is all the data in this object, then it would not be necessary to transfer email to it. In my opinion, the method should not be static.

Similar questions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question