Yii2 walkthrough for entering from a table in MySQL

I am starting to take the first steps in Yii2. Until now, I could write an application and connect a table in the database to it, just like I learned to do in Yii1.

The contacts table and the form in my creation view send data to the database without any problems.

The problem is that I can log in using Admin / Admin or a demo / demo in the static user model that is built into Yii2.

In Yii1.xx, I manage to check the login from a table in the database using COMPONENTS / useridentity, in the same way (I used a table called utilizador , with id , utilizador and password fields):

 class UserIdentity extends CUserIdentity { public function authenticate() { $conexao=Yii::app()->db; $consulta="select utilizador,password from utilizador "; $consulta.="where utilizador='".$this->username."' and "; $consulta.="password='".$this->password."'"; $resultado=$conexao->createCommand($consulta)->query(); $resultado->bindColumn(1,$this->username); $resultado->bindColumn(2,$this->password); while($resultado->read()!==false){ $this->errorCode=self::ERROR_NONE; return !$this->errorCode; } } } 

With Yii2, I read a lot of guides, including one in Stack Overflow, but none of them enlightened me on the procedure for logging in with a username and password from a MySQL database. Yii2 does not have the /useridentity.php components, and I don’t know where to start, and what the correct code is to make it work, overriding the static user model that goes out of the box.

I also tried the Yii2-user extension, read the PDF manual, but did not understand how to call the route from the provider folder in my controllers. Several attempts were made, but all failed.

Can someone teach me to check the login from the database in Yii2, preferably without using the extension?

Edit

I read this tutorial in Stack Overflow Yii Framework 2.0 Logging in with a User Database

I also studied PDF from the Yii2-user extension , but I don’t know what to do with the next part and the next version of pdf. He talks about routes, but I don’t know how to work with them:

2.3.1 Show users The route / user / admin / index shows a list of registered users. You can see a lot of useful information, such as registration time and IP address, confirmation status and block status, etc.

I also read the following: http://www.yiiframework.com/doc-2.0/yii-web-user.html but I don’t think it has steps to solve my problem.

EDIT 2

I tried to implement the User Model and LoginForm in the base Yii template in order to verify user accounts. Created a database and connected to it. The database as a user of the table and fields username, password, authKey, acessToken are filled with values. An extended user model from ActiveRecord and implemented by \ yii \ web \ IdentityInterface to make Yii2's built-in functions do their job. Also typed the method public static function tableName () {return 'user'; }

Each time I try to log in, it throws → the username or password incorrectly from validatepassword () in the LoginForm model.

Here is my code: LoginForm Model:

 namespace app\models; use Yii; use yii\base\Model; /** * LoginForm is the model behind the login form. */ class LoginForm extends Model { public $username; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['username', '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 boolean 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); } else { return false; } } /** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = User::findByUsername($this->username); } return $this->_user; } 

}

... and here is my User.php model

 <?php namespace app\models; use yii\db\ActiveRecord; class User extends ActiveRecord implements \yii\web\IdentityInterface { public $id; public $username; public $password; public $authKey; public $accessToken; public static function tableName() { return 'user'; } /** * @inheritdoc */ public static function findIdentity($id) { $user = self::find() ->where([ "id" => $id ]) ->one(); if (!count($user)) { return null; } return new static($user); } /** * @inheritdoc */ public static function findIdentityByAccessToken($token, $userType = null) { $user = self::find() ->where(["accessToken" => $token]) ->one(); if (!count($user)) { return null; } return new static($user); } /** * Finds user by username * * @param string $username * @return static|null */ public static function findByUsername($username) { $user = self::find() ->where([ "username" => $username ]) ->one(); if (!count($user)) { return null; } return new static($user); } /** * @inheritdoc */ public function getId() { return $this->id; } /** * @inheritdoc */ public function getAuthKey() { return $this->authKey; } /** * @inheritdoc */ public function validateAuthKey($authKey) { return $this->authKey === $authKey; } /** * Validates password * * @param string $password password to validate * @return boolean if password provided is valid for current user */ public function validatePassword($password) { return $this->password === $password; } } 

Any ideas? → Thank you ...

I don’t know what else should I do, maybe it has a problem with checking the password or finding the username, in Yii2 debugging it shows that it is connected correctly to the mysql database.

Do not touch actionController siteController (), because it is equal to the extended template, and I think it's better to stay that way.

EDIT 3 → 4 HOURS, tinker with the model code, inserting pratis into every solution I read, and it still throws an “Invalid username or password”. of:

 public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Incorrect username or password.'); } } } 

I do not want to give up, but I am considering the possibility of returning to the old Yii1.xx. There I can easily query the database and create a good login system.

+5
source share
2 answers

The Yii2 extended application comes by default with a working example of the database login part (I see that the base ones use a static username and password). You do not need to install anything, just look at the code. Install the advanced application and look at the external interface.

In short, the SiteController uses the LoginModel to verify, and then login () the LoginModel to enter the User model for the User component.

If you do not want to use the User model, just create your own model and use it. You do not want to use the User component by default, just create your own. This is pretty easy to do.

Edit: mate, remove the public variable declarations below.

 class User extends ActiveRecord implements \yii\web\IdentityInterface { public $id; public $username; public $password; public $authKey; public $accessToken; 

You tell Yii to ignore what is in the database.

+6
source

Create your own model and then use it. I will send the code below.

1) First create a database table with your own requirements.

  CREATE TABLE `q_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(255) NOT NULL, `auth_key` varchar(32) NOT NULL, `password_hash` varchar(20) NOT NULL, `access_token` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; 
  • Now go to the model generator and create a model using the q_user table

  • It will generate a QUser model. In this model you will need to implement IdentityInterface

    class QUser extends \ yii \ db \ ActiveRecord implements \ yii \ web \ IdentityInterface

Now we implement all the methods. When using Netbeans, press alt + enter.

 public function getAuthKey() { return $this->auth_key; } public function getId() { return $this->id; } public function validateAuthKey($authKey) { return $this->auth_key = $authkey; } public static function findIdentity($id) { return self::findOne($id); } public static function findIdentityByAccessToken($token, $type = null) { return $this->access_token; } public static function findByUsername($email){ return self::findOne(['email'=>$email]); } public function validatePassword($password){ return $this->password_hash === $password; } 
  • Now in the login form you will need to define the Quser model so that it returns the user

    class LoginForm extends model {public $ username; public $ password; public $ email; public $ rememberMe = true;

     private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['email', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ['password','match','pattern'=>'$\S*(?=\S*[az])(?=\S*[AZ])(?=\S*[\d])\S*$','message'=>'Password must have atleast 1 uppercase and 1 number '], [['password'],'string','min'=>6], //email validation ['email','email'] ]; } /** * 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 boolean 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 = QUser::findByUsername($this->email); } return $this->_user; } 

    }

That it will solve your problem.

+1
source

Source: https://habr.com/ru/post/1208386/


All Articles