Zend Framework: checking if user is logged in

Posted by Peter
tags: php

In most of applications user should be authenticated in order to access it (or maybe some parts, like admin panel). Again, in most cases it will be some kind of mechanism performing authentication against database or some kind of other storage.

In this tutorial I won’t provide any authentication code, but my way of checking if user is authenticated - comments will be welcome ;)

These are conditions I’m assuming:

  • application has multiple controllers
  • some or all of them have to be protected
  1. method #1 I don’t want to include in every controller any code checking if someone can access it (is logged in). Instead I want ‘main’ controller to do this job.What do I mean by 'main’ controller? It’s my own controller, which extends ZendControllerAction. Any method or property in it will be inherited by controllers extending it. So as you may have guessed already - all my controllers will extend it instead of default ZendControllerAction.

    It’s generally a good practice to have one of those for every type of classes in your project: controllers, models, forms.. etc. It allows you to make some changes to all of them all at once, maybe include a property or something like that.

    Anyway, back to main topic.

    All you need is create method init() in your 'main’ controller and put something like this piece of code in there:

    1
    2
    3
    4
    5
    
    <?php
    if (!Zend_Auth::getInstance()->hasIdentity()) {
      $request->setControllerName('user');
      $request->setActionName('login');
    }
    

    where 'user’ is my controller name and 'login’ is method in this controller.

  2. method #2 Currently I’m using this one. It only requires you to write a simple plugin, which will do the same job as described earlier. Create plugin with a method:

    1
    2
    
    <?php
    preDispatch(Zend_Controller_Request_Abstract $request)
    

    in it include something like this code:

    1
    2
    3
    4
    5
    
    <?php
    if (!Zend_Auth::getInstance()->hasIdentity()) {
      $request->setControllerName('user');
      $request->setActionName('login');
    }
    

Both of these methods require some fine tuning, but should give you a basic idea how to perform checking if user is authenticated and if not - redirecting to login screen.