In Yii 2, the login form is implemented in basic theme by default. But the main problem is login is not associated with any tables. It is done by a user array. We will implement it by user table.
Steps to login user with database
- In this example, what we will do is we will create user table. In user, table you must have username and password field. Store password in md5 which is more secure. In this example, I have used md5. Now when the user enters the password, Convert the string to md5 and match with the database password. Below is my user table.
123456789101112CREATE TABLE IF NOT EXISTS `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(255) NOT NULL,`password` varchar(255) NOT NULL,`authKey` varchar(255) NOT NULL,`accessToken` varchar(255) NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;// now insert one valueINSERT INTO `user` (`id`, `username`, `password`, `authKey`, `accessToken`) VALUES(1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'asdasd3423', 'sdfdsf3242'); - Now let’s try to understand everything steps by step. When the user enters username and password then our site controller login action is called.
1234567891011121314public 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,]);}
In this action, loginForm model is used. If we open, this model there are some rules is defined. First rules will be validated. let’s see which rules are applied.
1234567891011public 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'],];}
In this, username and password are required. you can change according to your needs. For password field, we have called validatePassword rule which is defined below in this model.
12345678910public function validatePassword($attribute, $params){if (!$this->hasErrors()) {$user = $this->getUser();if (!$user || !$user->validatePassword($this->password)) {$this->addError($attribute, 'Incorrect username or password.');}}}
This function will take the password and if there is no error then it will return the user info. To validate password it will call $user->validatePassword($this->password) . In the user model, we have the validatePassword function. see below
1234public function validatePassword($password){return $this->password === md5($password);}
I have used md5 here because, in the database, I have stored the password in md5 format. If the password will be equal then$model->login()
which is called in login action of site controller . below is the login action of loginForm model.
1234567public function login(){if ($this->validate()) {return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);}return false;}
$this->getUser() will call the getUser action which is defined below.
12345678public function getUser(){if ($this->_user === false) {$this->_user = User::findByUsername($this->username);}return $this->_user;}
In this, we have used User::findByUsername($this->username) . It will call findByUsername function of the user model. we have passed username because I am using username field to log in. you can use email field also. For this, you have to call custom function and define according to your need.
1234public static function findByUsername($username){return static::find()->where(['username'=>$username])->one();}
This function will find the user record from the user table. Also, you have to do one thing very important. Comment the virtual fields and user array which is written in this User model. Do like this below.
12345678910// public $id;// public $username;// public $password;// public $authKey;// public $accessToken;public static function tableName(){return 'user';}
One more thing, extend the active record to this class if it is not done earlier.
123456class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface{// ......// do your code}
This is all you have to do. If you face any issue please mention below in comments.
Incorrect username or password.