Search code examples
phpsessionyiiyii-extensionsyii-components

Auto-logout of session after x seconds for a user type (Yii 1.x)


I have a Yii 1.x application that uses the WebUser component for a login section of the website - within my config/main.php I have the following block within my components section that will automatically timeout the session after 2 hours (e.g 3600 x 2 or 7200 seconds).

This works fine in the sense that a user is 'kicked out' of my application after the set number of seconds - but how would I amend this to have this log out certain 'types' of user with different expirations.

e.g If user type == 1 then logout after 3600 seconds, if user type == 2 then logout after 7200 seconds...

// config/main.php
'components'        => array(
   'user'    => array(
       'class'   => 'application.components.WebUser',
       'allowAutoLogin' => true,
       'loginUrl'           => array('frontend/user/login'),
       'loginRequiredAjaxResponse' => 'CR_SESSION_EXPIRED',
       'authTimeout'       => 3600*2, // auto-logout after 2 hours
        ),
 .......

Note - this is using Yii 1.x rather than Yii 2.0.

I am presuming this would need to be within the WebUser integration rather than the config file..

-- update -- I've added the following block to the WebUser.php component (that extends CWebUser)

    public function init() {
    parent::init();

    if (($user = $this->getState('userModel')) !== null) {

        $this->authTimeout = 5;
        $this->absoluteAuthTimeout = 5;
        $this->setUserData(unserialize($user));
    }
}

I've set the authTimeout & absoluteAuthTimout to 5 seconds but I still remain logged in after 5 seconds... any ideas?


Solution

  • Like I said in my comment.

    I think you should be able to overwrite the value in your WebUser class.

    <?php
    class WebUser extends CWebUser{
    
        public $authTimeouts = array(); //array with the timeouts
    
        public function init(){
            //you need to get the userType first
            if(array_key_exists($userType,$this->authTimeouts)){ 
                $authTimeout = $this->authTimeouts[$userType];
            }
            parent::init();
        }
    }
    

    Then your config should look like this:

    // config/main.php
    'components'        => array(
       'user'    => array(
           'class'   => 'application.components.WebUser',
           'allowAutoLogin' => true,
           'loginUrl'           => array('frontend/user/login'),
           'loginRequiredAjaxResponse' => 'CR_SESSION_EXPIRED',
           'authTimeout'       => 3600*2, // auto-logout after 2 hours
           'authTimeouts'=> array(
                'userType1' => 10,
                'userType2' => 500,
                ),
            ),
     ......
    

    Something like that. For more info on the source code and the init() function see: https://github.com/yiisoft/yii/blob/1.1.16/framework/web/auth/CWebUser.php#L196