Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Module.php in Zend Framework 2 to redirect the user if is not in session (if he is not logged in)?

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).

like image 452
ilce Avatar asked Oct 30 '12 09:10

ilce


2 Answers

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 ();
}
like image 152
Emrah Mehmedov Avatar answered Nov 14 '22 10:11

Emrah Mehmedov


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

like image 5
samsonasik Avatar answered Nov 14 '22 11:11

samsonasik