Showing posts with label MySql. Show all posts
Showing posts with label MySql. Show all posts

Tuesday, August 24, 2010

Yii - Authentication from mysql database using a md5 password

Before proceeding make sure the database has been connected to Yii application. (see previous post)
For this example, the passwords are stored in the database as md5 hash.
You may be required to change the password encoding scheme.

Edit the authenticate method in ../my_app/protected/components/UserIdentity.php to look like this -

public function authenticate()
    {
        //$users=array(
            // username => password
            //'demo'=>'demo',
            //'admin'=>'admin',
        //);
       
        $user = myUsersTable::model()->findByAttributes( array( 'my_userid_column_name' => $this->username));
        if ($user===null) { // No user was found!
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        }
        // $user->Password refers to the "password" column name from the database
        else if($user->Password !== md5("my_salt1".$this->password))
        {   
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        }
        else { // User/pass match
            $this->errorCode=self::ERROR_NONE;
        }       
        return !$this->errorCode;
    }

Enter the username/password pair on the login page and you should be good to go.

Sunday, June 20, 2010

Yii + MySql + Wamp







First, I installed WampServer, which is a package of Apache, Php and MySql coupled into one. In the httpd.conf file I pointed the “DocumentRoot” and “Directory” configurations to the directory, where I would have my application and Yii framework.


I copied the Yii framwork in "d:/workspace/app_demo/”

To create the stub application from yii, I executed these commands for my setup:

>cd D:\workspace\app_demo

>yii\framework\yiic webapp myapp

-------

This created an application “myapp” under “app_demo” folder.

The “/app_demo/myapp/protected/config/main.php” file contains the database configurations. By default the database was pointed to an sqlite database. I changed that, to point to Mysql database. So I had these settings for my mysql database.

/* 'db'=>array(

'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',

),*/

'db'=>array(

'connectionString' => 'mysql:host=localhost;dbname=pages_db',

'emulatePrepare' => true,

'username' => 'root',

'password' => '',

'charset' => 'utf8',

),

I also enabled logging through this file to look like this:

'log'=>array(

'class'=>'CLogRouter',

'routes'=>array( array('class'=>'CFileLogRoute',

'levels'=>'error, warning',

),

array('class'=>'CWebLogRoute',

), ), ),

-------

My database had two tables (user and address). The sql is shown below:

CREATE TABLE IF NOT EXISTS `address` (

`addressid` int(11) NOT NULL AUTO_INCREMENT,

`firstline` varchar(45) DEFAULT NULL,

`secondline` varchar(45) DEFAULT NULL,

`city` varchar(45) DEFAULT NULL,

`state` varchar(45) DEFAULT NULL,

`country` varchar(45) DEFAULT NULL,

PRIMARY KEY (`addressid`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `user` (

`userid` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'This contains the userid of the user',

`fname` varchar(128) NOT NULL COMMENT 'This contains the first name of the user',

`lname` varchar(128) DEFAULT NULL COMMENT 'This contains the last name of the user',

`sex` varchar(1) NOT NULL COMMENT 'This contains the sex of the user',

`age` int(100) DEFAULT NULL COMMENT 'This contains the age of the user',

`creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'This contains the user account creation',

`user_addressid` int(11) DEFAULT NULL,

PRIMARY KEY (`userid`),

KEY `fk_user_address` (`user_addressid`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `user` ADD CONSTRAINT `fk_user_address` FOREIGN KEY

(`user_addressid`) REFERENCES `address` (`addressid`) ON DELETE NO ACTION ON

UPDATE NO ACTION;

-------

I had to create corresponding models for the tables. After the database configuration, I ran the following commands to create the models in my app.

cd app_demo\myapp

D:\workspace\app_demo\myapp>protected\yiic shell index.php

This opened the Yii Interactive Tool.

Yii Interactive Tool v1.1 (based on Yii v1.1.2)

Please type 'help' for help. Type 'exit' to quit.

>> model *

The following model classes (tables) match your criteria:

1. Address (address)

2. User (user)

Do you want to generate the above classes? [Yes|No] yes

generate models/Address.php

generate fixtures/address.php

generate unit/AddressTest.php

generate models/User.php

generate fixtures/user.php

generate unit/UserTest.php

The following model classes are successfully generated:

Address, User

If you have a 'db' database connection, you can test these models now with:

$model=User::model()->find();

print_r($model);

-------

After this, I edited the actionIndex function in SiteController.php to look like this:

public function actionIndex()

{

// renders the view file 'protected/views/site/index.php'

// using the default layout 'protected/views/layouts/main.php'

$this->render('index', array(

'user' => User::model()->findAll()

));

}

In the index.php, I added the following table to display the records from the database:

 
foreach($user AS $us):?> 
 echo $us->fname;?> 
echo $us->lname;?> 
echo $us->age;?> 
echo $us->user_address->city;?> 
 endforeach;?>

Then I pointed my browser to http://localhost/myapp/index.php and this generated a table with the results.

More on this later...