🎉 Join me on February 10th for a live event about building SaaS businesses with AI. 🎉

Checking Login Status Using a Zend Framework Action Helper

When building a framework-driven website it's standard practice to group related tasks within separate controllers. For instance I generally group user registration, login, logout, profile management, password reset, and password recovery tasks within a controller named Account. While the registration, login, and password recovery actions should be accessible to users who are not logged into the website, you'll logically want to restrict access to the profile and password reset actions. But doing so would require you to redundantly incorporate the logic necessary to determine whether the user is logged in, and if not redirect the user to a new location (likely the login action).

Not necessarily. You can eliminate the repetition by creating a custom action helper which encapsulates this logic. You can then call the action helper as needed at the top of those actions which you'd like to restrict. Here's how it's done:

<?php

class WJG_Controller_Action_Helper_LoginRequired extends Zend_Controller_Action_Helper_Abstract

{

  public function direct()

  {

    $auth = Zend_Auth::getInstance();

    if (! $auth->hasIdentity()) {
      $flash = Zend_Controller_Action_HelperBroker::getStaticHelper('flashMessenger');
      $flash->addMessage(Zend_Registry::get('config')->messages->login->required);
      $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
      $redirector->gotoUrl(Zend_Registry::get('config')->urls->login);
    }

  }

}

?>

With the custom action helper in place, you can execute it as needed within your controllers. For instance, I'm currently using this helper at the top of the profile helper which will ensure that only logged-in users can manage a profile:

public function indexAction()
{
  // Make sure the user is logged in
  $this->_helper->LoginRequired();

  ... Restricted logic goes here

}