Reputation: 214
I have implemented LDAP authentication in my application, and I want to store username into session and have to check all the Controller/Action should be run if the LDAP user is logged in.
For this, should I use this following Container in every Module Controller and should I write a following constructor in every Module/controller in ZF2?
use Zend\Session\Container;
public function __construct()
{
$this->session = new Container('user');
// Check the user is already logged in
$sesUserNameExists = $this->session->offsetExists('username');
$sesUserName = $this->session->offsetGet('username');
}
Is there any simple way to manage session in all the Modules/Controller?
Upvotes: 1
Views: 140
Reputation: 17614
Try handling the DISPATCH event in onBootstrap() method of your module. There, using the Service Locator you should create an instance of your LDAP/session component and verify that user is logged in. If not, you can short circuit the application flow and redirect user to the login page.
Upvotes: 0
Reputation: 13558
If you have repeatable logic in different controllers, think of a controller plugin to implement the logic DRY. You can use this plugin in every controller you need the check:
class MyController extends AbstractActionController
{
public function indexAction()
{
if (!$this->ldapAuth()->isLoggedIn()) {
// Do something
}
}
}
The controller plugin must implement the interface Zend\Mvc\Controller\Plugin\PluginInterface
, but it's easier to use the provided abstract AbstractPlugin
:
namespace MyModule\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Session\Container;
class LdapAuth extends AbstractPlugin
{
const SESSION_KEY = 'user';
protected $session;
public function __construct()
{
$this->session = new Container(self::SESSION_KEY);
}
public function isLoggedIn()
{
return isset($this->session->username);
}
public function getUsername()
{
return $this->session->username;
}
}
The only trick in this setup is that you need to register the plugin in the service manager. So take your module.config.php
configuration file and add these lines:
'controller_plugins' => array(
'invokables' => array(
'ldapAuth' => 'MyModule\Controller\Plugin\LdapAuth',
),
),
Upvotes: 1