12

So, the question is how can I configure Module.php in my module to check if the user is or is not in session? If he is not I want to redirect him to the log in page.

I don't want the user to has permission to go on other action(controller) if he is not in session(not logged in).

Siguza
  • 21,155
  • 6
  • 52
  • 89
ilce
  • 1,007
  • 3
  • 12
  • 20

3 Answers3

9

This should be done with event in ZF2 for more details: click here also this code may help you. http://pastebin.com/FFGVCpki

public function init() {
    // Attach Event to EventManager
    $events = StaticEventManager::getInstance ();

    // Add event of authentication before dispatch
    $events->attach ( 'Zend\Mvc\Controller\AbstractActionController', 'dispatch', array (
            $this,
            'authPreDispatch' 
    ), 110 );
}
public function authPreDispatch($event){
$target = $event->getTarget ();
$serviceLocator = $target->getServiceLocator();
// Do what ever you want to check the user's identity
$url = $event->getRouter ()->assemble ( array (
                    "controller" => "<controller>" 
            ), array (
                    'name' => '<route name>' 
            ) );
$response = $event->getResponse ();
        $response->setHeaders ( $response->getHeaders ()->addHeaderLine ( 'Location', $url ) ));
        $response->setStatusCode ( 302 );
        $response->sendHeaders ();
        exit ();
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
Emrah Mehmedov
  • 1,492
  • 13
  • 28
  • 3
    Is there nicer way to redirect from Module.php ? I really don't like sending headers directly, without using ZF's internal redirection mechanisms. – Vitalii Lebediev Jan 05 '13 at 14:21
5

don't use redirect, do setParam() method using 'route' event, see this https://github.com/samsonasik/SanAuthWithDbSaveHandler/commit/e2ae4dfcebb7a952d7b1adaadcf6496c994423b9

samsonasik
  • 440
  • 1
  • 6
  • 11
2

Some like:

$e->getRouteMatch()
->setParam('controller', 'Application\Controller\Login')
->setParam('action', 'login');
sebob
  • 515
  • 6
  • 14