How to enable the authentication through the mysql database

In this tutorialsi explain the easy steps with code snipats which describe How to enable the authentication through the mysql database. The basic skeleton provided by the YII command line application, already includes a rudimentary authentication mechanism. This will check if the details entered matches the one specificed in the controller. Now what we want to do is to modify the controller, so that the authentication method will check the data against the user table in the database.The skeleton application uses the UserIdentity controller class for this purpose, we can find the file in WEBROOT\protected\components\UserIdentity.php. What we have to modify is the authenticate method, as shown in the code below:

now this is a method you should add in the User’s model class (located in WEBROOT\protected\models\User.php) which will help to validate the password according to your need. Here is a very easy example

1

2

3

4

5

6

7

8

9

publicfunctionvalidatePassword($password)

{

return$this->hashPassword($password,$this->salt)===$this->password;

}

publicfunctionhashPassword($password,$salt)

{

returnmd5($salt.$password);

}

In this step we have modified the UserIdentity component and the User’s model class. Some of you may get confused, but it’s really simple, the difference between these two script is that the former is like a plug-in used to aid in the authentication workflow, while the latter is used to represent the data related with the current user. You can use the UserIdentity multiple times depending on the various authentication methods you want to implement, while you will have only one User’s model which is the currently logged user and all related data grabbed from the database’s table.

About: Prem Tiwari

Prem Tiwari is the founder of FreeWebMentor.com and also a professional developer who has vast experience in PHP and open source technologies. Apart from this, he is a blogger by hobby and also he has been a regular speaker of WordPress sessions in various IT Companies. View all posts by Prem Tiwari