vitaly_74
@vitaly_74

Почему не работает авторизация (аутентификация) в Yii2?

Подскажите в чем может быть ошибка, пытаюсь написать авторизацию, но ничего не выходит. проблема в том что пытаясь передать identity в \Yii::$app->user->login, данные почему то не сохраняются в сессии, и в куки тоже.

вот действие которое обрабатываю:
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
    }


вот сама модель, которая фигурирует в данном действии:

<?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.
    }
}


вывожу отдельно $form_model - все выводится нормально но почему то не происходит логирования(
  • Вопрос задан
  • 709 просмотров
Пригласить эксперта
Ответы на вопрос 1
webinar
@webinar Куратор тега Yii
Учим yii: https://youtu.be/-WRMlGHLgRg
пытаясь передать identity в \Yii::$app->user->login

в том то и дело, что передаете Вы не identity , а модель формы
$dataUser = $form_model::findIdentity($form_model->email); // тут identity
\Yii::$app->user->login($form_model,1000*60*60*24); //а вот что передаете


ПС: Кстати я не совсем понимаю в чем смысл обращаться к findIdentity, как к статическому методу. Раз уж там все данные в этом объекте, то и передавать в него email не надо было бы. На мой взгляд метод не должен быть статическим.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы