Search code examples
zend-framework2session-cookieszend-session

ZF2 Set Zend\AuthenticationService to use second session or cookie based on url or module


I have set up two user account modules - administrator and customer. My current set-up means if you log into administrator my app thinks you're logged in as a customer also. The solution I've decided upon is to create a session where the cookie path is based on the administrator url, i.e. set the cookie_path as /administrator.

In my administrator Module.php onBootstrap function I have included:

$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(['cookie_path' => '/administrator']);
$sessionManager = new SessionManager($sessionConfig, null, null);
Container::setDefaultManager($sessionManager);

which sets the cookie path, but this affects the entire application; i.e. the rest of the site is cookie free because the urls do not begin with /administrator.

How do I set up my application so that the cookie_path for my administrator module is different to the rest of the application?

[edit]

What I am after is two cookies - one for admin path, and one for the rest of the application.

[edit]

I am using Zend\Authentication\AuthenticationService for ACL. What I am trying to achieve is for a user to log into the customer section of the website and do stuff, and then log into the admin panel to do stuff.

As an example, Magento will set one cookie when dealing with customer account log in, then another cookie when dealing with admin account log in.

How do I set up Zend\Authentication\AuthenticationService to use a second session or cookie based on url / module?


Solution

  • To set a new namespace on the authentication service, do the following:

    $auth = $e->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');
    $auth->setStorage(new \Zend\Authentication\Storage\Session($_namespace));
    

    In my question I wanted create a disparate session for my admin area. In my abstract controller (where I am checking the $auth details against my acl set-up) I have:

    $params = $e->getRouteMatch()->getParams();
    
    /** @var \Zend\Authentication\AuthenticationService */
    $auth = $e->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');
    $_namespace = current(explode('\\', $params['__NAMESPACE__']));
    // Most generic session namespace.
    if(in_array($_namespace, ['Customer', 'Application', null])) {
        $_namespace = 'Zend_Auth';
    }
    $auth->setStorage(new \Zend\Authentication\Storage\Session($_namespace));
    

    This does not create a second cookie, but it does mean I can go to domain.dev/account (customer section) and be able to log in independently of domain.dev/administrator (admin section) which is ultimately what I was attempting to do.