- Introducing the Zend Framework
- Improving the Registration Form
- Authenticating User Credentials with Zend_Auth
- What You Have Learned
Authenticating User Credentials with Zend_Auth
The end result of the improved registration form that you just created is the same as Dreamweaver’s built-in Insert Record server behavior—it inserts user details in the database. Dreamweaver’s User Authentication server behaviors can still be used to control access to pages. However, ZF makes it easy to create scripts to authenticate user credentials. Using external files for the scripts that control access and log out users simplifies their inclusion in any page.
Controlling user access with Zend_Auth
The Zend_Auth class creates a singleton object, which means that only one instance can exist at a time. In practical terms, the only difference is that you use getInstance() instead of the new keyword like this:
$auth = Zend_Auth::getInstance();
Zend_Auth is capable of using a variety of authentication methods. When the user credentials are stored in a database, authentication is done by an adapter called Zend_Auth_Adapter_DbTable, which takes the following five arguments:
- A Zend_Db object that connects to the database
- The name of the table that contains the user credentials
- The name of the column that contains the username
- The name of the password column
- The encryption, if any, to be applied to the password
The fifth argument uses a question mark as a placeholder for the password. The users table uses sha1() encryption, so you create an adapter like this:
$adapter = new Zend_Auth_Adapter_DbTable($dbRead, ‘users’, ‘username’, ‘password’, ‘sha1(?)’);
When a user logs in, pass the username and password to the adapter like this:
$adapter->setIdentity($_POST[‘username’]); $adapter->setCredential($_POST[‘password’]);
To check whether the user’s credentials are valid, pass the adapter to the Zend_Auth object’s authenticate() method:
$result = $auth->authenticate($adapter);
Finally, if the login succeeds, store the user’s details like this:
if ($result->isValid()) { $storage = $auth->getStorage(); $storage->write($adapter->getResultRowObject( array(‘username’, ‘first_name’, ‘family_name’))); }
The array passed as an argument to the getResultRowObject() method is a list of the database fields you want to store. Dreamweaver’s built-in Log In User server behavior stores only the username and access level, if any. Zend_Auth gives you access to as much information about the user as you want—provided, of course, it’s stored in the database.
You restrict access to pages by using the hasIdentity() method, which returns TRUE if the user has logged in.
To access details of a logged-in user, use the getIdentity() method like this:
$auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { $identity = $auth->getIdentity(); }
The details can then be accessed as properties of $identity, for example:
$identity->first_name
To log out a visitor, use the clearIdentity() method.
Creating the login script
The Log In User server behavior that you used in Lesson 6 sends the user to another page on failure or displays the login form again without explanation. This time you’ll display an error message so the user knows what’s happened.
- Create a new PHP page, and save it as user_authentication.php in lesson07/workfiles/scripts. The page will contain only PHP code, so delete the HTML inserted by Dreamweaver, and add an opening PHP tag.
- To control the error message, create a FALSE Boolean variable:
- The login script should run only if the form is submitted. Add a conditional statement to include library.php if the $_POST array equates to TRUE:
- The script uses objects, so add try and catch blocks inside the conditional statement, and get an instance of Zend_Auth in the try block.
- Create a Zend_Auth_Adapter_DbTable object. A quick way to select its code hint is by typing hada after the new keyword. This takes five arguments, but Dreamweaver helps you by highlighting the current argument in bold.
- Set the identity and credential values for the adapter. They come from the username and password values in the $_POST array:
- Pass the adapter to the authenticate() method of the Zend_Auth object, and save the result in a variable:
- Use the isValid() method to determine whether the user’s credentials are correct. If they are, store the details, and use header() to redirect the user to members_only.php. If the login attempt fails, reset $failed to TRUE. The code looks like this:
$failed = FALSE;
If the login fails, this will be reset to TRUE and display the message.
if ($_POST) { require_once(‘library.php’); // check the user’s credentials }
try { $auth = Zend_Auth::getInstance(); } catch (Exception $e) { echo $e->getMessage(); }
The rest of the script goes inside the try block.
The code for this line should look like this:
$adapter = new Zend_Auth_Adapter_DbTable($dbRead, ‘users’, ‘username’, ‘password’, ‘sha1(?)’);
$adapter->setIdentity($_POST[‘username’]); $adapter->setCredential($_POST[‘password’]);
$result = $auth->authenticate($adapter);
if ($result->isValid()) { $storage = $auth->getStorage(); $storage->write($adapter->getResultRowObject(array( ‘username’, ‘first_name’, ‘family_name’))); header(‘Location: members_only.php’); exit; } else { $failed = TRUE; }
Testing the login script
To use the login script, include it above the DOCTYPE declaration of the login page, and add a conditional statement to show an error message if the login fails.
- Copy login.php and members_only.php from lesson07/start to lesson07/workfiles.
- Include user_authentication.php in login.php by adding the following above the DOCTYPE declaration:
- In Design view, insert a new paragraph after the Members Only heading, and type Login failed. Check username and password.
- Switch to Code view, and wrap the paragraph you just created in a conditional statement like this:
- Save login.php, and test it in Live View or a browser. When the page first loads, the error message is not displayed. Try to log in using an invalid username or password. The error message is displayed.
- Click “Sign in” without typing anything in either field. You get the following message: “A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.”
- Switch back to user_authentication.php, and add another conditional statement inside the existing one near the top of the script:
- A red marker on the last line of the script reminds you that you need to add a closing curly brace to match the opening one of the else block. Technically speaking, the missing brace goes between the last two braces at the bottom of the script, but you can put it on the final line, and the red marker goes away.
- Save user_authentication.php, and test the login form again without filling in the fields. This time you get your custom error message in red.
- Test the login form with a registered username and password. When you click “Sign in,” you are taken to members_only.php.
<?php require_once(‘scripts/user_authentication.php’); ?>
With the insertion point anywhere in the paragraph, choose warning from the Class menu in the Property inspector. This turns the text bold red.
<?php if ($failed) { ?> <p class="warning">Login failed. Please check username and password.</p> <?php } ?>
The script in user_authentication.php sets $failed to FALSE and changes it to TRUE only if a login attempt fails, so this prevents the error message from being shown unless the user’s credentials are rejected.
This comes from the catch block. Failing to enter anything in the Username field has caused Zend_Auth to throw an exception. This is more elegant than the lengthy error message you get without try and catch, but it’s not something you want to show visitors to your site.
if ($_POST) { if (empty($_POST['username']) || empty($_POST['password'])) { $failed = TRUE; } else { require_once('library.php');
This uses empty() to test if $_POST[‘username’] or $_POST[‘password’] contains a value. If either is empty, $failed is reset to TRUE. The authentication script is now inside an else block that is executed only if $_POST[‘username’] and $_POST[‘password’] both have values.
You can compare your code with lesson07/completed/login.php and lesson07/completed/scripts/user_authentication01.php.
Password-protecting pages
Building the login script was the complex part. To restrict access to a page, you use the hasIdentity() method, which returns TRUE or FALSE. If the user is logged in, you retrieve his or her details with getIdentity(). Otherwise, you redirect the user to the login page.
- Create a PHP page, and save it as restrict_access.php in lesson07/workfiles/scripts. Delete the HTML inserted by Dreamweaver.
- The script is so short; here it is in its entirety:
- To password-protect members_only.php, just include this script above the DOCTYPE declaration like this:
<?php require_once(‘library.php’); try { $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { $identity = $auth->getIdentity(); } else { header(‘Location: login.php’); exit; } } catch (Exception $e) { echo $e->getMessage(); }
This includes library.php and creates an instance of Zend_Auth. The conditional statement checks whether the user is logged in. If it succeeds, the user’s details are stored in $identity. Otherwise, the page is redirected to login.php, and exit ensures that the script comes to an immediate halt, preventing the protected page from being displayed.
<?php require_once(‘scripts/restrict_access.php’); ?>
Assuming you’re already logged in, you need to log out before you can test this. For that, you need a logout button and script, which is coming up next.
Creating a logout system
Zend_Auth makes logging out easy with the clearIdentity() method. You can add the necessary code to user_authentication.php, and use a link to login.php to log out the user. A query string at the end of the link triggers the logout.
- Create a new paragraph in members_only.php, and type Log Out.
- Select the text, and link to login.php. Add ?logout to the end of the link. You can do this in the Link field of the Property inspector or in Code view. Save members_only.php.
- Switch to user_authentication.php, and add the following code at the bottom of the page:
- Save user_authentication.php, and load members_only.php in a browser or Live View. If the page displays, click the “Log out” link. You will be taken to the login form.
- Log in, and click the “Log out” link again.
- Now try to access members_only.php directly. You will be denied access and taken to the login form.
if (isset($_GET[‘logout’])) { require_once(‘library.php’); try { $auth = Zend_Auth::getInstance(); $auth->clearIdentity(); } catch (Exception $e) { echo $e->getMessage(); } }
Values passed through a query string are in the $_GET array. This uses isset() to see if $_GET[‘logout’] exists. If it does, the ZF files are included, an instance of Zend_Auth is created, and the clearIdentity() method performs the logout. That’s all there is to it. The session variables storing the user’s details are deleted automatically.
Displaying a logged-in user’s details
The code in restrict_access.php calls the getIdentity() method and stores the user’s username, first name, and family name as properties of $identity. This makes it possible to greet a user by name after logging in.
- In Code view, amend the beginning of the first paragraph in members_only.php like this:
- Save members_only.php, and log back in to be greeted by name.
<p>Hi, <?php echo "$identity->first_name $identity->family_name"; ?>. ÂYou're in!
The column names are treated as properties of $identity, allowing you to access the information they contain about the user with the -> operator.