Configuring Session in Zend_Auth

classic Classic list List threaded Threaded
7 messages Options
Reply | Threaded
Open this post in threaded view
|

Configuring Session in Zend_Auth

calbear77
Hello, I have some code like this and I'm trying to configure the Zend Session created within Zend auth and so far, I've had no luck doing it:

                                $db = Zend_Db::factory($configuration->database);        //Connection to the database
                                $authAdapter = new Zend_Auth_Adapter_DbTable($db);
                                $authAdapter->setTableName('users');
                                $authAdapter->setIdentityColumn('user_email');
                                $authAdapter->setCredentialColumn('user_password');          //Verify table values with form values
                                $authAdapter->setIdentity($email);
                                $authAdapter->setCredential($password);
                                $auth = Zend_Auth::getInstance();
                                $result = $auth->authenticate($authAdapter);            //Authenticate using the adapter
                                if ($result->isValid())
                                {
                                        // store the identity as an object where only the username and
                                        // real_name have been returned
                                        Zend_Session::setOptions($configuration->session->toArray());
                                        Zend_Session::start ();
                                       
                                        $storage = $auth->getStorage();
                                        //Store all user table data except password as session variables
                                        $storage->write($authAdapter->getResultRowObject(null, 'password'));
                                        $this->view->user = Zend_Auth::getInstance()->getIdentity();
                                        $this->view->title = 'Welcome';
                                        $this->_helper->layout->setLayout('dynamiclayout');
                                        $this->_helper->redirector('index');
                                        //$this->_helper->redirector->gotoUrl('/project/project/index');
                                }

In my config.ini file, I have:
session.remember_me_seconds=7200

If I create a session using Zend_Session, without Auth, this works fine.  Any ideas what I am doing wrong?

Thanks,
Kevin
Reply | Threaded
Open this post in threaded view
|

Re: Configuring Session in Zend_Auth

kwylez
Is there a reason why you are setting the auth adapter values into a new session. Zend_Auth uses it's own namespace in Zend_Session. 

On Sun, Mar 22, 2009 at 6:49 PM, kadams <[hidden email]> wrote:

Hello, I have some code like this and I'm trying to configure the Zend
Session created within Zend auth and so far, I've had no luck doing it:

                               $db =
Zend_Db::factory($configuration->database);        //Connection to the
database
                               $authAdapter = new Zend_Auth_Adapter_DbTable($db);
                               $authAdapter->setTableName('users');
                               $authAdapter->setIdentityColumn('user_email');
                               $authAdapter->setCredentialColumn('user_password');          //Verify
table values with form values
                               $authAdapter->setIdentity($email);
                               $authAdapter->setCredential($password);
                               $auth = Zend_Auth::getInstance();
                               $result = $auth->authenticate($authAdapter);            //Authenticate
using the adapter
                               if ($result->isValid())
                               {
                                       // store the identity as an object where only the username and
                                       // real_name have been returned
                                       Zend_Session::setOptions($configuration->session->toArray());
                                       Zend_Session::start ();
                                       $storage = $auth->getStorage();
                                       //Store all user table data except password as session variables
                                       $storage->write($authAdapter->getResultRowObject(null, 'password'));
                                       $this->view->user = Zend_Auth::getInstance()->getIdentity();
                                       $this->view->title = 'Welcome';
                                       $this->_helper->layout->setLayout('dynamiclayout');
                                       $this->_helper->redirector('index');
                                       //$this->_helper->redirector->gotoUrl('/project/project/index');
                               }

In my config.ini file, I have:
session.remember_me_seconds=7200

If I create a session using Zend_Session, without Auth, this works fine.
Any ideas what I am doing wrong?

Thanks,
Kevin
--
View this message in context: http://www.nabble.com/Configuring-Session-in-Zend_Auth-tp22652278p22652278.html
Sent from the Zend Auth mailing list archive at Nabble.com.




--
Cory Wiles
[hidden email]
http://www.corywiles.com/
http://www.randomthoughtprocess.com/
Reply | Threaded
Open this post in threaded view
|

Re: Configuring Session in Zend_Auth

calbear77
Thanks for the reply...  I've tried a lot of permutations of this, with and without the Zend_Session::start() lines.

Are you saying I'm inadvertently changing the namespace here?  If so, I'm guessing there is a way to assign the config to the 'Zend_Auth' session?  I haven't been able to find an example of this in any of several tutorials on the matter.


kwylez wrote
Is there a reason why you are setting the auth adapter values into a new
session. Zend_Auth uses it's own namespace in Zend_Session.

On Sun, Mar 22, 2009 at 6:49 PM, kadams <kadams@gmail.com> wrote:

>
> Hello, I have some code like this and I'm trying to configure the Zend
> Session created within Zend auth and so far, I've had no luck doing it:
>
>                                $db =
> Zend_Db::factory($configuration->database);        //Connection to the
> database
>                                $authAdapter = new
> Zend_Auth_Adapter_DbTable($db);
>                                $authAdapter->setTableName('users');
>
>  $authAdapter->setIdentityColumn('user_email');
>
>  $authAdapter->setCredentialColumn('user_password');          //Verify
> table values with form values
>                                $authAdapter->setIdentity($email);
>                                $authAdapter->setCredential($password);
>                                $auth = Zend_Auth::getInstance();
>                                $result = $auth->authenticate($authAdapter);
>            //Authenticate
> using the adapter
>                                if ($result->isValid())
>                                {
>                                        // store the identity as an object
> where only the username and
>                                        // real_name have been returned
>
>  Zend_Session::setOptions($configuration->session->toArray());
>                                        Zend_Session::start ();
>                                        $storage = $auth->getStorage();
>                                        //Store all user table data except
> password as session variables
>
>  $storage->write($authAdapter->getResultRowObject(null, 'password'));
>                                        $this->view->user =
> Zend_Auth::getInstance()->getIdentity();
>                                        $this->view->title = 'Welcome';
>
>  $this->_helper->layout->setLayout('dynamiclayout');
>                                        $this->_helper->redirector('index');
>
>  //$this->_helper->redirector->gotoUrl('/project/project/index');
>                                }
>
> In my config.ini file, I have:
> session.remember_me_seconds=7200
>
> If I create a session using Zend_Session, without Auth, this works fine.
> Any ideas what I am doing wrong?
>
> Thanks,
> Kevin
> --
> View this message in context:
> http://www.nabble.com/Configuring-Session-in-Zend_Auth-tp22652278p22652278.html
> Sent from the Zend Auth mailing list archive at Nabble.com.
>
>


--
Cory Wiles
kwylez@gmail.com
http://www.corywiles.com/
http://www.randomthoughtprocess.com/
Reply | Threaded
Open this post in threaded view
|

Re: Configuring Session in Zend_Auth

kwylez
After looking at your code again I think the problem you are having is that you are missing a boolean flag to allow the session lifetime to be overridden.  Let me know if I misunderstood.
          
 $saveHandler = Zend_Session::getSaveHandler();

 $saveHandler->setLifetime($this->_globalConfig->session->params->remember_me_seconds)
                        ->setOverrideLifetime(true);

In a global base file I start the session first:

    /**
     * Tell Zend_Session to use your Save Handler
     */
    $sessionDbTbl = new Zend_Session_SaveHandler_DbTable($sessionConfig);

    Zend_Session::setSaveHandler($sessionDbTbl);

    Zend_Session::start();


AuthController/LoginAction:
        /**
         * do the authentication
         */
        $auth   = Zend_Auth::getInstance();
        $result = $auth->authenticate($authAdapter);
       
        if ($result->isValid()) {

            /**
             * Check and see if the user wants to me remembered.  If they are then
             * their session is valid for 1 year.  If not then the session dies
             * when the user closes their browser.
             */
           
            $this->_logger->debug("Remember me value {$this->_getParam('rememberme')}");
           
            if ($this->_hasParam('rememberme') && $this->_getParam('rememberme')) {
               
                 /**
                  * 'remeberMe' setting is defined it the global config
                  */
                Zend_Session::rememberMe();
               
            $saveHandler = Zend_Session::getSaveHandler();
            $saveHandler->setLifetime($this->_globalConfig->session->params->remember_me_seconds)
                                  ->setOverrideLifetime(true);
            }
           
            $data                = array();
              $data['role']        = 'user';
              $data['username']    = $authAdapter->getUsername();
              $data['roles']       = $authAdapter->getAdRoles();
              $data['displayName'] = $authAdapter->getDisplayName();
              $data['email']       = $authAdapter->getEmail();

              $auth->getStorage()->write($data);

On Sun, Mar 22, 2009 at 9:26 PM, kadams <[hidden email]> wrote:

Thanks for the reply...  I've tried a lot of permutations of this, with and
without the Zend_Session::start() lines.

Are you saying I'm inadvertently changing the namespace here?  If so, I'm
guessing there is a way to assign the config to the 'Zend_Auth' session?  I
haven't been able to find an example of this in any of several tutorials on
the matter.



kwylez wrote:
>
> Is there a reason why you are setting the auth adapter values into a new
> session. Zend_Auth uses it's own namespace in Zend_Session.
>
> On Sun, Mar 22, 2009 at 6:49 PM, kadams <[hidden email]> wrote:
>
>>
>> Hello, I have some code like this and I'm trying to configure the Zend
>> Session created within Zend auth and so far, I've had no luck doing it:
>>
>>                                $db =
>> Zend_Db::factory($configuration->database);        //Connection to the
>> database
>>                                $authAdapter = new
>> Zend_Auth_Adapter_DbTable($db);
>>                                $authAdapter->setTableName('users');
>>
>>  $authAdapter->setIdentityColumn('user_email');
>>
>>  $authAdapter->setCredentialColumn('user_password');          //Verify
>> table values with form values
>>                                $authAdapter->setIdentity($email);
>>                                $authAdapter->setCredential($password);
>>                                $auth = Zend_Auth::getInstance();
>>                                $result =
>> $auth->authenticate($authAdapter);
>>            //Authenticate
>> using the adapter
>>                                if ($result->isValid())
>>                                {
>>                                        // store the identity as an object
>> where only the username and
>>                                        // real_name have been returned
>>
>>  Zend_Session::setOptions($configuration->session->toArray());
>>                                        Zend_Session::start ();
>>                                        $storage = $auth->getStorage();
>>                                        //Store all user table data except
>> password as session variables
>>
>>  $storage->write($authAdapter->getResultRowObject(null, 'password'));
>>                                        $this->view->user =
>> Zend_Auth::getInstance()->getIdentity();
>>                                        $this->view->title = 'Welcome';
>>
>>  $this->_helper->layout->setLayout('dynamiclayout');
>>
>> $this->_helper->redirector('index');
>>
>>  //$this->_helper->redirector->gotoUrl('/project/project/index');
>>                                }
>>
>> In my config.ini file, I have:
>> session.remember_me_seconds=7200
>>
>> If I create a session using Zend_Session, without Auth, this works fine.
>> Any ideas what I am doing wrong?
>>
>> Thanks,
>> Kevin
>> --
>> View this message in context:
>> http://www.nabble.com/Configuring-Session-in-Zend_Auth-tp22652278p22652278.html
>> Sent from the Zend Auth mailing list archive at Nabble.com.
>>
>>
>
>
> --
> Cory Wiles
> [hidden email]
> http://www.corywiles.com/
> http://www.randomthoughtprocess.com/
>
>

--
View this message in context: http://www.nabble.com/Configuring-Session-in-Zend_Auth-tp22652278p22653391.html
Sent from the Zend Auth mailing list archive at Nabble.com.




--
Cory Wiles
[hidden email]
http://www.corywiles.com/
http://www.randomthoughtprocess.com/
Reply | Threaded
Open this post in threaded view
|

Re: Configuring Session in Zend_Auth

calbear77
In reply to this post by calbear77
Thanks for all your help, Cory.  I really appreciate it.  I just wanted to give everyone a working code snippet to play off of, here, just because this was a nightmare for me:

in my indexController:

        function loginAction()
        {
                $salt = "abchefghjkmnpqrstuvwxyz0123456789";
                $registry = Zend_Registry::getInstance();
                $configuration = $registry->configuration;
                require_once 'default/forms/LoginForm.php';                      //Include the form
                $form = new LoginForm();                                           //Create a new object of the form class
                if ($this->_request->isPost())                                        //Check for empty form
                {
                        $formData = $this->_request->getPost();
                        if ($form->isValid($formData))                                 //Check for valid inputs
                        {
                                $email=$formData['user_email'];
                                $password=md5($salt.$formData["user_password"]);
                                $db = Zend_Db::factory($configuration->database);        //Connection to the database
                                $authAdapter = new Zend_Auth_Adapter_DbTable($db);
                                $authAdapter->setTableName('users');
                                $authAdapter->setIdentityColumn('user_email');
                                $authAdapter->setCredentialColumn('user_password');          //Verify table values with form values
                                $authAdapter->setIdentity($email);
                                $authAdapter->setCredential($password);
                                $auth = Zend_Auth::getInstance();
                                $result = $auth->authenticate($authAdapter);           //Authenticate using the adapter
                                if ($result->isValid())
                                {
                                        // store the identity as an object where only the username and
                                        // real_name have been returned
                                        Zend_Session::setOptions($configuration->session->toArray());
                                        Zend_Session::start ();

                                        $storage = $auth->getStorage();
                                        //Store all user table data except password as session variables
                                        $storage->write($authAdapter->getResultRowObject(null, 'password'));
                                        $this->view->user = Zend_Auth::getInstance()->getIdentity();
                                        $this->view->title = 'Welcome';
                                        $this->_helper->layout->setLayout('dynamiclayout');
                                        $this->_helper->redirector('index');
                                        //$this->_helper->redirector->gotoUrl('/project/project/index');
                                }
                                else
                                {
                                        $this->view->message="sorry,login failed";
                                        $this->_helper->layout->setLayout('login');
                                        $this->view->form = $form;
                                        $form->populate($formData);
                                        return $this->render('login');
                                }
                        }
                } else {
                        $this->_helper->layout->setLayout('login');
                        $this->view->form = $form;
                }
        }

my base controller:

class Athena_Controller_Action extends Zend_Controller_Action
{
        function init()
    {
    parent::init();
        $this->_helper->actionStack('setnav', 'menu', 'system');
    }

    public function preDispatch()
    {
        if (Zend_Auth::getInstance()->hasIdentity()) {        
            // If the user is logged in, we extend his session except in the case of logout
        if ('logout' != $this->getRequest()->getActionName()) {
                                $registry = Zend_Registry::getInstance();
                                $configuration = $registry->configuration;
               $authSession = new Zend_Session_Namespace('Zend_Auth');
                                $authSession->setExpirationSeconds($configuration->session->remember_me_seconds);

        }
        } else {
        if (!((($this->getRequest()->getActionName() == 'index' ||
        $this->getRequest()->getActionName() == 'login')
        && $this->getRequest()->getControllerName() == 'index')
        || (($this->getRequest()->getActionName() == 'registration-submitted' ||
        $this->getRequest()->getActionName() == 'register')
        && $this->getRequest()->getControllerName() == 'management'
        && $this->getRequest()->getModuleName() == 'user'))) {
                                $this->_helper->redirector('default', 'index', 'index'); // back to login page
        }
        }
    }
}

and in my app.ini, I have a line:
session.remember_me_seconds=7200

My problem, I think, was that I wasn't using 'Zend_Auth' as the namespace of the session.  The preDispatch method basically resets the remember_me_seconds any time the user does anything (including AJAX calls) and it redirects to the login page otherwise.  It's a pretty simple code example, but I think it's pretty powerful.  The reason I didn't use a Plugin helper for this was because not all my controllers inherit from my base controller, so I couldn't make it universal like that.

I'd love to see any feedback, and hopefully this example helps people avoid the problems that I had.

Thanks again, Cory, for your help.

Cheers,
Kevin
Reply | Threaded
Open this post in threaded view
|

Re: Configuring Session in Zend_Auth

calbear77
also, I just tried it without the Zend_Session::start(); command and it works just fine, so you can remove that from your code.  I guess it makes sense that the Zend_Auth session gets started within that class.
Reply | Threaded
Open this post in threaded view
|

Re: Configuring Session in Zend_Auth

Goran Juric
In reply to this post by calbear77

kadams wrote
and in my app.ini, I have a line:
session.remember_me_seconds=7200

My problem, I think, was that I wasn't using 'Zend_Auth' as the namespace of the session.  The preDispatch method basically resets the remember_me_seconds any time the user does anything (including AJAX calls) and it redirects to the login page otherwise.  It's a pretty simple code example, but I think it's pretty powerful.  The reason I didn't use a Plugin helper for this was because not all my controllers inherit from my base controller, so I couldn't make it universal like that.

I'd love to see any feedback, and hopefully this example helps people avoid the problems that I had.
Hi kadams,

your problem seems to be affected by this bug -> http://framework.zend.com/issues/browse/ZF-3324 and the snippet you posted probably works just because you are calling setExpirationSeconds() explicitly in your base controller.

I would suggest you to remove session configuration from your base controller.

Although, In your case I would remove the whole base controller because you don't really need it and it is just bloating your scripts.

If you want to access your Zend_Config object from your Controller write an Action plugin, it is really simple.

You would also be better of creating a view helper for the menu generation instead of adding another action to the stack (see documentation and appendix on performance).

Checking for identity and redirecting appropriately should also be done in your controller and if you need to check for identity for access to the certain parts of your site (controllers and action) you should take a look at Zend_Acl and create a Front Controller plugin.

Regards,

Goran Juric
http://gogs.info/