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

3

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

Bibbs answered 30/10, 2012 at 9:27 Comment(0)
W
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 ();
}
Wyler answered 30/10, 2012 at 10:8 Comment(1)
Is there nicer way to redirect from Module.php ? I really don't like sending headers directly, without using ZF's internal redirection mechanisms.Heterolecithal
C
5

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

Carcinogen answered 13/11, 2013 at 10:9 Comment(2)
Paste that piece of code here also that will be some quick referenceAmine
But that doesn't change the URL displayed though? Is there a way to do that?Lelandleler
R
2

Some like:

$e->getRouteMatch()
->setParam('controller', 'Application\Controller\Login')
->setParam('action', 'login');
Revalue answered 17/6, 2014 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.