Basic authentication with Zend_Auth

for one of my projects I had to create a basic login form with DB validation. this is what I came up with


$autenticar=Zend_Auth::getInstance();
$autenticar_adaptador=new Zend_Auth_Adapter_Table();
$autenticar_adaptador->setTableName('user_credentials_table)
                     ->setIdentityColumn('username')
                     ->setCredentialColumn('password')

$correo=$request->getParam('user_email');
$clave=$request->getParam('user_pass');

$autenticar_adaptador->setIdentity($correo);
$autenticar_adaptador->setCredential(md5($clave));

$valid_user=$autenticar->autenticate($autenticar_adaptador);

if($valid_user->isValid()){
$user_data=$autenticar_adaptador->getResultRowObject(array('name','user_name'),'password');
$autenticar->getStorage()->write($user_data);
$this->_redirect('protected_page');
}else{
$this->_redirect('login_form');
}

in lines 7 and 8 we get the values from the form, in this case we’re validating with email and password.

10 and 11 we set the identity(in this case is the email field in our dB) and the credential(the password field in our DB which is encrypted with MD5) for the Zend_Auth_Adapter_Table.

Zend_Auth will compare the values pass in lines 10 and 11 against the values in the columns we specified in lines 04 and 05.

In line 16 we specified which column’s value we’re gonna get from the table we specified  in line 03, in this case those columns are sent as the first parameter of  getResultRowObject in form of an array, the second parameter is where we specified which fields are not going to be fetch from the table.

In line 17 we create an identity with the data fetched in line 16. This is use to validate if a user has logged in.

Example of simple identity validation

$autenticar=Zend_Auth::getInstance();
if(!$autenticar->hasIdentity()){
$this->redirect('login_form')
}

Getting the data from the Identity created in line 17


$user=$autenticar->getIdentity();
$user_full_name=$user->name;
$user_screen_name=$user->user_name;

A pretty easy way to validate data against a DB table and to create an identity with this info.

Advertisements

About phanorcoll

Fullstack Developer

Posted on January 4, 2011, in Articles, ZendFramework and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: