I
I
Igor Braduloff2018-08-22 12:40:51
Yii
Igor Braduloff, 2018-08-22 12:40:51

Problem with validation in Yii2?

Hello! Question about validation in Yii2. Returns "Password or login entered incorrectly", although the data I enter from the MSSQL database is correct. Here is my SiteController , Login model and RecipientPortalUser model:

<?php
//namespace app\controllers;
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use app\models\Signup;
use app\models\Login;
use yii\db\Query;
use app\models\RecipientPortalUser;


/**
 * Site controller
 */
class SiteController extends Controller
{

    public function actionIndex()
    {
        $records = RecipientPortalUser::getAllRecords();
        return $this->render('index',compact('records'));
    }


    public function actionLogout()
    {
        if(!Yii::$app->user->isGuest)
        {
            Yii::$app->user->logout();
            return $this->redirect(['login']);
        }
    }
    // для регистрации
    public function actionSignup()
    {
        $model = new Signup();
        if(isset($_POST['Signup']))
        {
            $model->attributes = Yii::$app->request->post('Signup');
            if($model->validate() && $model->signup())
            {
                return $this->redirect(['index']);
            }
        }
        return $this->render('signup',['model'=>$model]);
    }
    //1. Проверить существует ли пользователь?
    //2. "Внести" пользователя в систему(в сессию)
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest)
        {

            return $this->goHome();
        }

        $login_model = new Login();

        if( Yii::$app->request->post('Login'))
        {
            $login_model->attributes = Yii::$app->request->post('Login');
          
            if($login_model->validate())
            {
                Yii::$app->user->login($login_model->getUser());
                return $this->goHome();
            }
            else
            {
                return "No validated";
            }
        }
        return $this->render('login',['login_model'=>$login_model]);
    }
}

//=============================================== =========================================
<?php

namespace app\models;
use yii\base\Model;
class Login extends Model
{
    public $login;      //   есть
    public $password;   //   есть
    public function rules()
    {
        return [
            [['login','password'],'required'],
            [['login'],'string'],
            [['login'],'trim'],
            [['password'],'trim'],
            ['password','validatePassword'] //собственная функция для валидации пароля
        ];
    }

    public function validatePassword($attribute,$params)
    {
        if(!$this->hasErrors()) // если нет ошибок в валидации
        {

            $user = $this->getUser();
     
            if(!$user || !$user->validatePassword($this->password))
            {
                //если мы НЕ нашли в базе такого пользователя
                //или введенный пароль и пароль пользователя в базе НЕ равны ТО,
                $this->addError($attribute,'Пароль или  логин введены неверно');
                //добавляем новую ошибку для атрибута password о том что пароль или имейл введены не верно

            }
        }
    }




    public  function getUser()
    {
        return RecipientPortalUser::findOne(['_login'=>$this->login]); // а получаем мы его по введенному логину
    }
}

//=============================================== ================================================
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class RecipientPortalUser extends ActiveRecord implements IdentityInterface
{

    //public $login;
    public $password;
    //public $id;

    public static function tableName()
    {
        return 'dbo.RecipientPortal_User';
    }

    public static function primaryKey()
    {
        return ['row_id'];
    }

    public  function setPassword($password)
    {
        $this->password = sha1($password);
    }
    public function validatePassword($password)
    {
        return $this->password === sha1($password);
    }
    //==========================
    public static function findIdentity($id)
    {
        return self::findOne($id);
    }
    public function getId()
    {
        return $this->id;
    }
    public static function findIdentityByAccessToken($token, $type = null)
    {
    }
    public function getAuthKey()
    {
    }
    public function validateAuthKey($authKey)
    {
    }
    public static function getAllRecords()
    {
        $findAll =  RecipientPortalUser::find()->all();
        return $findAll;
    }
   
}

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2018-08-22
@webinar

although the data I enter from the MSSQL database is correct

the password is stored in the database as a hash, how can you be sure that you enter it correctly?
Next, debug here:
if(!$user || !$user->validatePassword($this->password))
            {
                $this->addError($attribute,'Пароль или  логин введены неверно');
            }

There are two conditions, you need to check which one does not work. If the latter, then debug here:
public function validatePassword($password)
    {
        return $this->password === sha1($password);
    }

print that on the left and on the right side of the equality

D
Dmitry, 2018-08-22
@slo_nik

Good afternoon.
And why exactly Yii::$app->request->post('Login')?
Make it easy Yii::$app->request->post()
Why parameters in

public function validatePassword($attribute,$params)
?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question