I want to make authorization in my ZF-based application.
In Kohana I could make something like
public $auth;
public $user;
public function before()
{
parent::before();
$this->auth = Auth::instance();
$this->user = $this->auth->get_user();
// $this->user is object if user was logged in or FALSE if not
}
in my abstract controller.
How to make the same in Zend? I've read about plugins and think it's what I need but didnt found any information where to save plugin-classes files and where should I enable them?
You can also do something similar in ZF to what you did in Kohana. I personally have never used Kohana, but I thing that ZF's version of your example would be similar to that:
// assuming IndexController
class IndexController extends Zend_Controller_Action {
protected $_auth;
protected $_user;
// you could also use init() here.
public function preDispatch() {
$this->_auth = Zend_Auth::getInstance();
$this->_user = $this->_auth->getIdentity();
}
}
If you would like to have it in an abstract controller, then you could just create one (e.g. My_Controller_Action) that extends Zend_Controller_Action. Having this, IndexController would just extend your abstract controller rather than Zend_Controller_Action.
Hey! It's really simple, too. But if you want to get the authorization or process a new one? What ever, here comes both ones. First processing the authorization with credentials in a database table:
$db = $this->getInvokeArg('bootstrap')->db;
$auth = Zend_Auth::getInstance();
$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('authLogin')
->setIdentityColumn('username')
->setCredentialColumn('password')
->setIdentity($username)
->setCredential($password);
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
// Yeah, logged in. Do some stuff here...
}
And here comes the check, if the user is currently logged in:
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
// User is logged in. Retrieve its identity
$username = $auth->getIdentity();
}
Hope this helps...
Related
I want to capture the loggin event in zendframework2 and then update the database when the user last logged in.
i am aware that if i do the following in the onBootstrap(MVCEvent $e) of my module i will be able to capture the event etc:
$eventManager = $e->getApplication()->getEventManager();
$em = $eventManager->getSharedManager();
$em->attach(
'ZfcUser\Authentication\Adapter\AdapterChain',
'authenticate',
function($e)
{
$id = $e->getIdentity();
}
);
this will give me the Id of the user. however, the confusion is how i can then update my database from the bootstrap. i mean, i dont have access to the entity manager in my bootstrap and i am not sure how to transport it there. the entity manager is held in the service config file.
i.e
getServiceConfig()
'Members\Model\WorkerTable' => function($sm) {
$db = $sm->get('doctrine.entitymanager.orm_default');
$table = new Model\MemberTable($db);
return $table;
},
.
with the above settings i am able to access the entity manager in my MemberTable class
so, a simple solution would be to transfer the loggin event manager to my
** MemberTable class** where i would use my entity manager to update the database.
issue, i am not sure how to set this up:
$eventManager = $e->getApplication()->getEventManager();
$em = $eventManager->getSharedManager();
i mean, i dont know how to get the variable $e into the MemberTable class so that i can access the eventManger and the sharedManager.
in summary; the issues are twofold.
how do i get the entity manager into the bootstrap function
alternatively
how do i get the eventManager and shared eventmanager into a normal class so that i can call the eventmanger in a class that already contains the entity manager
Well, all you have to do is to retrieve the service manager this way:
$serviceManager = $e->getApplication()->getServiceManager();
and then get your entity manager like this:
$entityManager = $serviceManager->get('Members\Model\WorkerTable');
Does it solve your problem?
The answer to the second question
To bring a variable into the closure from outside you can use "use" operator like so:
function() use ($myVar){
// some code
}
So, in your case I would do:
$eventManager = $e->getApplication()->getEventManager();
$em = $eventManager->getSharedManager();
$em->attach(
'ZfcUser\Authentication\Adapter\AdapterChain',
'authenticate',
function($e) use ($entityManager){
$id = $e->getIdentity();
}
);
If you are planning to have a lot of code inside your closure I would suggest to put it into a separate class and make it invokable. For instance,
class YourClosureCode
{
private $entityManager;
public function __construct($eventManager)
{
$this->eventManager = $eventManager;
}
public function __invoke(EventInterface $e)
{
// put your closure code here
}
}
Then a slight modification here:
$eventManager = $e->getApplication()->getEventManager();
$em = $eventManager->getSharedManager();
$em->attach(
'ZfcUser\Authentication\Adapter\AdapterChain',
'authenticate',
new YourClosureCode($entityManager);
);
I'm trying to create a ZF1 plugin to centralize my Authentication system. So far here is what I did :
class Application_Plugin_Auth extends Zend_Controller_Plugin_Abstract {
private $_whitelist;
protected $_request;
public function __construct() {
$this->_whitelist = array(
'default'
);
}
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$this->_request = $request;
$module = strtolower($this->_request->getModuleName());
if (in_array($module, $this->_whitelist)) {
return;
}
$auth = Zend_Auth::getInstance();
if (!$auth->hasIdentity()) {
$this->_request->setModuleName('admin');
$this->_request->setControllerName('auth');
$this->_request->setActionName('login');
return;
}
}
}
It works perfectly to avoid people to access the backend if there are not logged. Now, I would like to implement a login function with no parameters which will grab the current request, check the param (getPost) and then do the login job :
public function login(){
// Here will check the request data and then try to login
}
My question is how can I get the current request object in this function? Also, how to use this login function in my controller?
Thanks a lot
This is what you want when you don't want to pass the request as argument to your function:
$request = Zend_Controller_FrontController::getInstance()->getRequest();
$postData = $request->getPost();
However, usually you do want to pass arguments to your function. Mostly because you want your object that operates with the login functionality to be independent from the rest of your system. There are only few cases I can think of that disagree from this methodology.
When you like to get the Request from your front controller, you can just issue:
$request = $this->getRequest();
Currently, I am using Zend_Auth::getInstance()->hasIdentity() to check if my user is logged in in every controller that requires a login. I feel like I am practicing Zend horribly, so I wanted to ask the more experienced and know if this is the proper way to do this? If not, could you please tell me what is?
We use a Controller plugin (bootstrapped in application.ini config file) that handles our authentications. It checks the requested controller/action in the preDispatch() phase and matches against ACL objects (could be fetched out of DB, config files, XML, etc.). If the user does not have the privilege to access the target controller/action, the a message is stored in the session and user is redirected to another page, displaying the access forbidden message.
If the user needs to have authentication to access the target controller/action, user is redirected to the login action by modifying the request object.
Using this plugin there is no need to check for user authentication/ACL in each controller and so all the "Access" code would be enclosed in one file, the "Access Plugin".
In order to check for user identity we mostly use the same method of "Zend_Auth::getInstance()->hasIdenity()", but this just shows if the user is authenticated or not. the '''getIdentity()''' method of Zend_Auth returns the current user identity, but again just the identity and not more. However if you would need more information of the user, you could store the user information in a session.
We implement our users as data models, so each user is defined as an object. after a user is authenticated on the login action, we create the appropriate user object and store it in the user session, like this:
// This could be a sample code in AuthController/processloginAction()
// suppose $username is validated before and stores the username
$user = new Default_Model_User($username);
// now $user is our user object, suppose $log is a Zend_Log instance
$log->info("user id '{$user->getId()}' username: '{$user->getUsername()}' logged in");
$sess = Zend_Session_Namespace('auth');
$sess->user = $user;
From now one, the $user property of the session namespace of 'auth' is the user object with all the information you would need about, not just the identity. and whenever you wanted to check if user is logged in (beside using Zend_Auth) you could check for availability of this value on the user session:
$sess = Zend_Session_Namespace('auth');
if (!isset($sess->user) || !$sess->user) {
// user is not logged in, redirect to login page
}
$user = $sess->user;
/*#var $user Default_Model_User*/
$email = $user->getEmail();
now we checked for authentication, and have access to user information (email, phone, etc.).
I use a method similar to the method described by Herman Radtke in his blog at http://www.hermanradtke.com/blog/more-reliable-authentication-in-zend-framework/. Basically create a controller plugin as farzad mentioned:
class My_Authentication extends Zend_Controller_Plugin_Abstract
{
private $_whitelist;
public function __construct()
{
$this->_whitelist = array(
'index/login'
);
}
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$controller = strtolower($request->getControllerName());
$action = strtolower($request->getActionName());
$route = $controller . '/' . $action;
if (in_array($route, $this->_whitelist)) {
return;
}
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
return;
}
self::setDispatched(false);
// handle unauthorized request...
}
}
and then register that plugin in your bootstrap:
public function run() {
$front->registerPlugin(new My_Authentication());
}
I generally take this approach a little farther and integrate the Zend_Acl into the system as well. To do that I would define the plugin below:
class My_Acl_Authentication extends Zend_Controller_Plugin_Abstract
{
private $_acl;
public function __construct($acl)
{
$this->_acl = $acl
}
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$controller = strtolower($request->getControllerName());
$action = strtolower($request->getActionName());
$route = $controller . '/' . $action;
if (in_array($route, $this->_whitelist)) {
return;
}
$auth = Zend_Auth::getInstance();
$role = 'anonymous';
if ($auth->hasIdentity()) {
$role = $auth->getStorage->read()->role;
}
if ($this->_acl->isAllowed($role, $route)) {
return;
}
self::setDispatched(false);
// handle unauthorized request...
}
}
If you go this route there is some more work to be done, specifically you have to setup the ACL and then you also have to store the user's role in the auth storage.
Thats perfectly ok to do so but to save you from repeating that code you can extend all your controllers from a class A which is subclass of Zend_Controller_Action . Then inside this class declare a method
protected function hasIdentity()
{
return Zend_Auth::getInstance()->hasIdentity();
}
Now in your controller which is subclass of A you can simply do $this->hasIdentity(); instead
Searched and searched for some guidance but cant seem to get anything to work. I wont to access the user data in any index controller to save repetetive code. I have created a ACTION HELPER which calls the Session and returns the users data. Below is how I implemented it all. Calling the helper works but I cant get the data out in any controller.
Application.ini
autoloaderNamespaces[] = "ZC"
Bootstrap.php
protected function _initActionHelpers()
{
Zend_controller_Action_HelperBroker::addHelper(new ZC_Action_Helpers_User());
}
User.php
<?php
Class ZC_Action_Helpers_User extends Zend_Controller_Action_Helper_Abstract
{
public function direct()
{
$storage = new Zend_Auth_Storage_Session();
$data = $storage->read();
$this->_user = $data;
}
}
IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$this->_helper->user;
}
I have no problems with the code but say for example how would I get the USERNAME or USERID from the helper???
Thanks for taking the time in looking at this.
J
First, your plugin function have to return the user information and not set it as a class variable:
Class ZC_Action_Helpers_User extends Zend_Controller_Action_Helper_Abstract
{
public function direct()
{
$storage = new Zend_Auth_Storage_Session();
$data = $storage->read();
return $data;
}
}
Then you can use the plugin in any controller you need:
$user = $this->_helper->User->Direct()
You might want to rename some of these functions and classes.
Try to declared in bootstrap path to helpers...
Zend_Controller_Action_HelperBroker::addPath(
APPLICATION_PATH .'/controllers/helpers');
Next use google for this simply question.... howto use helper in ZF
What is the best method in Zend Framework to provide restricted areas and redirect users to a login page? What I want to do is set a flag on my controllers for restricted pages:
class AdminController extends Zend_Controller_Action
{
protected $_isRestricted = true;
....
and have a plugin check to see if the controller is restricted and if the user has authenticated, otherwise redirect them to the login page. If I do this directly in the controller's preDispatch I can use $this->_redirect(), but looking at Action Helpers they won't have access to that. It's also a lot of duplicate code to copy/paste the authentication check code in every controller that needs it.
Do I need an Action Controller linked to preDispatch, or a Front Controller plugin? How would I do the redirect and still preserve things like the base URL?
Use Zend_Acl (best combined with Zend_Auth)
See also Practical Zend_ACL + Zend_Auth implementation and best practices
For one project, I've extended Zend_Controller_Action, and in that class's preDispatch put a check for logged-in-ness. I can override it on a per-action basis with an init() that checks the actionname and turns off the requirement (or preDispatch() that calls it's parent for the actual checks).
In a project I was working on, I had trouble with various users experiencing timeouts from their browsers. This meant the Zend_Auth no longer existed in the registry and users lost access to required pages/functions.
In order to stop this from occuring, I setup a Plugin (as you suggest) and have this plugin perform checks in the preDispatch(). An example is below:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function run()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new App_Controller_Plugin_Timeout());
parent::run();
}
}
with the timeout class implementing any Zend_Auth or Zend_Acl requirements, using a check via the function below.
class App_Controller_Plugin_Timeout extends Zend_Controller_Plugin_Abstract
{
/**
* Validate that the user session has not timed out.
* #param Zend_Controller_Request_Abstract $request
* #return void
* #todo Validate the user has access to the requested page using Zend_Acl
*/
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$frontController = Zend_Controller_Front::getInstance();
$controllerName = $frontController->getRequest()->getControllerName();
$actionName = $frontController->getRequest()->getActionName();
$authInstance = Zend_Auth::getInstance();
/** If the controller is not the Auth or Error controller, then check for
* a valid authorized user and redirect to the login page if none found */
if (($controllerName !== 'auth') && ($controllerName !== 'index') && ($controllerName !== 'error')) {
if (!$authInstance->hasIdentity()) {
$this->_response->setRedirect('/index/timeout')->sendResponse();
exit;
}
} else if (($controllerName == 'index') || (($controllerName == 'auth') && ($actionName !== 'logout'))) {
/** If running the Auth or Index (default) controller (and not the logout
* action), check if user already signed in and redirect to the welcome page */
if ($authInstance->hasIdentity()) {
$this->_response->setRedirect('/general/welcome')->sendResponse();
exit;
}
}
}
}
....
/**
* Test that the input user belongs to a role based on the user input and
* the values loaded into the Acl registry object setup when the site first
* loads
*
* #param mixed|Zend_Auth $userData
* #param string $userRole
* #return boolean
* #throws Zend_Exception When invalid input is provided
*/
public function isUserMemberOfRole($userData, $userRole)
{
if (empty($userData)) {
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {
$userData = $auth->getIdentity();
} else {
return FALSE;
}
}
if (!is_string($userRole)){
throw new Zend_Exception('Invalid input provided to ' . __METHOD__);
}
// Setup the required variables and access the registry for the Acl values
$rolesTable = new App_Model_Internal_UsersToRoles();
$registry = Zend_Registry::getInstance();
$acl = $registry->get('acl');
$roles = $rolesTable->getUserRoles($userData); // returns an array of values
foreach ($roles as $value) {
if ($value['Name'] == $userRole) {
return $acl->isAllowed($value['Name'], null, $userRole);
}
}
}
I had the user access implemented in a database table and then initialized as an "_init" function at Bootstrap->run() as follows:
protected function _initAclObjectForUserRoles()
{
$userTable = new App_Model_Internal_Roles();
$acl = new Zend_Acl();
$userRoles = $userTable->fetchAll();
$roles = $userRoles->toArray();
// Cycle through each Role and set the allow status for each
foreach($roles as $value) {
$department = $value['Name'];
$acl->addRole(new Zend_Acl_Role($department));
$acl->allow($department, null, $department);
}
// Add the new Acl to the registry
$registry = Zend_Registry::getInstance();
$registry->set('acl', $acl);
}
So, using this method you could put access restrictions via the roles loaded via from a database into an Zend_Acl object, or you could load the controller class attribute via the Timeout plugin and check it's value. Although, I've found it's easier to maintain access policies in a database than spread them throughout your code base... :-)