I often use this when implementing a simple login screen for a password protected section of my application. In a Zend Framework application you can implement a preDispatch() function in a Zend_Controller_Action which will run before an action is dispatched. This lets you setup your filter to check to see if the visitor is logged in or not. If the visitor is not logged in, you can redirect them to the login screen of your application.

Setting Up Exceptions For preDispatch

If your login screen is managed by a different controller, the setup described above is fine. If, however, your login screen is managed by an action in the same controller as the protected actions, you will want to allow unauthenticated access to the login screen. To do this, we need to exclude certain actions from the authentication check. Ruby on Rails let’s you define :except => :actionName to allow certain actions to skip the before_filter. With the Zend Framework, we have to implement that functionality on our own… but it’s easy.

What Action Is Being Called?

To set up your preDispatch function to skip checking to see if a user is logged in for certain actions you need to know which action is being called. You do that like this…

$action = $this->_request->getActionName();

Example Code

Now all you have to do is see if the action that is being called is one of the actions that you want to skip. I set up a private function called verify() to check whether or not the visitor is logged in. If the user is not logged in, I forward them to the loginAction() function. Since an unauthenticated user needs to be able to access the login screeen, we tell the preDispatch() function not to verify visitors requesting the login action. My controller ends up looking someting like this.

class AccountController extends Zend_Controller_Action {

  function preDispatch() {
    // Discover what action is being requested
    $action = $this->_request->getActionName();

    // Create a list of actions which allow unauthenticated access
    $exclusions = array("login");
    if(!in_array($action, $exclusions)) {
      $this->verify();
    }
  }

  /**
   * Check to see if the visitor is logged in. If not, send to loginAction
  */
  private function verifty() {
    $auth = Zend_Auth::getInstance();
    if(!$auth->hasIdentity()) {
      $this->_forward("login");
    }
  }

  function loginAction() {
    // Display your login screen
  }

  // Continue the rest of your class...
}