0

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?

Ivan
  • 5,139
  • 11
  • 53
  • 86

2 Answers2

0

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;
    }
}
Community
  • 1
  • 1
tasmaniski
  • 4,767
  • 3
  • 33
  • 65
0

Zend Framework 2

In your other controllers

public function yourAction() {
        $this->_authenticate(); 
        $this->view['identity'] = (array)$this->identity;
        // your code here
}

// authentication function

public function _authenticate() {

    if(!$this->getServiceLocator()->get('AuthService')->hasIdentity()) {
         return $this->redirect()->toRoute('auth');
    } else {
        $this->identity = $this->getServiceLocator()->get('AuthService')->getIdentity();
    }
}

public function getAuthService()  {
    if (! $this->authservice) {
        $this->authservice = $this->getServiceLocator()->get('AuthService');
    }

    return $this->authservice;
}