I wondering how to perform an access control in a entire module. Let me explain : If I have got a module (/authentication/) which is only developed to create a session. And a another module (/Main/) which contains the main application.

What I want to do is to check in any request on the main module if a session was correctly created by a user.

During my research on the internet, I saw a method to do it. I'm not sure, so tell me if my solution is good : I will implemente an event in my bootstrap function (on module.php) which will check if the session is correctly created. If it is not I will redirect to the module authentication.

public function onBootstrap($e){

    $eventManager = $e->getApplication()->getEventManager();

    $auth = new AuthenticationService();
    if (!$auth->hasIdentity()) {
        $response  = $e->getResponse();
        $response->getHeaders()->addHeaderLine('Location', 'authentification');
        $response->setStatusCode(302);
    }

    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
}

What do you think about this solution ?

Unfortunately this solution is not good. I don't know why, but it seem that this code is executed even in the module authentication. So at the first call when you are trying to go in the url : /main, you will be redirect to the module /authentication and again the code will be re-executed and the module will redirect you to /authentication and again and again and again...

So I think the solution is to check if the requested url is different from this one /authentication.

How to do this ?

Hope my question is clear and easily understandable.

Thank you =D

有帮助吗?

解决方案

public function onBootstrap(MvcEvent $e) {

        $eventManager = $e->getApplication()->getEventManager();

        $eventManager->attach(MvcEvent::EVENT_DISPATCH, function($e) {

            $controller = $e->getTarget();
            $auth = new AuthenticationService();
            $is_login = $auth->hasIdentity();


                        //check if action is login

            $params = $e->getApplication()->getMvcEvent()->getRouteMatch()->getParams();

            if ($params['action'] == 'login') {


                if ($is_login) {
                    return $controller->redirect()->toRoute('adminindex');
                }

            } else {


                if (!$is_login) {
                    return $controller->redirect()->toRoute('adminauthlogin');
                }

            }
});

    }

a little bit better solution ;)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top