Search code examples
phpzend-frameworkzend-framework2zend-auth

ZF2 check if user logged in other modules


Guys how can i check in other modules if user is logged or not? Can i do that with sessions or Zend\Auth have better way to do that?

I created auth module using Zend \ Authentication component and evrything work fine.

I want separate my modules like this:

  • Auth Module
  • Custrommer Module
  • Order Module
  • Admin Module

No how with my existing Auth Module i can check in Admin, Order and Custommer modules if user logged or not? Does i need to create specific service for that?

I dont have to much expiriance with ZF, am in learing phase.

Any example and advice?


Solution

  • Check my answer here https://stackoverflow.com/a/32392608/949273

    $events->attach(MvcEvent::EVENT_ROUTE, __CLASS__ . '::checkPermission', -100);
    

    Basically in every request I execute

    public static function checkPermission(MvcEvent $e)
    {
        $auth = $e->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');
    
        if(!$auth->hasIdentity()){
            $url      = $e->getRouter()->assemble([], ['name' => 'login']);
            $response = $e->getResponse();
            $response->getHeaders()->addHeaderLine('Location', $url);
            $response->setStatusCode(302);
            $response->sendHeaders();
    
            return $response;
        }
    }