I'm trying to add functionality such that a user is automatically logged out after a specified period of inactivity. I think I have it working using a filter, and am just curious if there's a better way.
First, the lastActivity attribute is set upon user login in the authenticate() function:
$this->setState('lastActivity', time());
Next, the filter class defined in application.filters.UserInactivityFilter:
class UserInactivityFilter extends CFilter
{
const TIMEOUT_PERIOD=3600; //Number of seconds before auto-logout
protected function preFilter($filterChain)
{
$user = Yii::app()->getUser();
if (!$user->isGuest)
{
if (time() - $user->lastActivity > self::TIMEOUT_PERIOD)
Yii::app()->user->logout();
else
$user->lastActivity = time();
}
return true;
}
}
Then each controller that requires this inactivity check has it added to filters() prior to the accessControl filter:
public function filters()
{
return array(
array('application.filters.UserInactivityFilter'), // checks for user inactivity
'accessControl', // perform access control for CRUD operations
);
}
As I said, it seems to be working. But I'm pretty new at this, so there may be better alternatives that I'm not seeing. Thanks for any feedback.