File: //home/aliazzsr/api.crm.vqode.com/models/Session.php
<?php
namespace app\models;
use app\components\helpers\ValueHelper;
use app\models\core\User;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
/**
* Class Session
* @package app\models
* @property integer $user_id
* @property integer $duration
* @property string $login_at
* @property string $logout_at
* @property string $seen_at
*/
class Session extends ActiveRecord
{
/** @var integer token expiration, minutes */
protected $tokenExpiration;
const EXPIRES_DEFAULT = 60;
public function init()
{
parent::init();
$this->tokenExpiration = self::getTokenExpiration();
}
protected static function getTokenExpiration()
{
return ArrayHelper::getValue(\Yii::$app->params, 'session.expires', self::EXPIRES_DEFAULT);
}
public static function tableName()
{
return 'session';
}
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'login_at',
'updatedAtAttribute' => null,
'value' => ValueHelper::now(),
],
];
}
public static function start($attributes)
{
$session = new static($attributes);
return $session->save();
}
public function beforeSave($insert)
{
if (!$this->logout_at) {
$this->seen_at = ValueHelper::now();
}
return parent::beforeSave($insert);
}
public function stop()
{
if ($this->logout_at) {
return true;
}
$period = $this->tokenExpiration * 60;
$logout_at = <<<EXPR
case when unix_timestamp() - unix_timestamp(seen_at) > {$period}
then from_unixtime(unix_timestamp(seen_at) + {$period})
else now()
end
EXPR;
$duration = <<<EXPR
unix_timestamp($logout_at) - unix_timestamp(login_at)
EXPR;
$this->logout_at = new Expression($logout_at);
$this->duration = new Expression($duration);
return $this->save();
}
public static function stopExpired()
{
/** @var Session $sessions */
$sessions = static::find()
->andWhere([
'>',
new Expression('time_to_sec(timediff(now(), seen_at))'),
self::getTokenExpiration() * 60
])
->andWhere(['logout_at' => null])
->all();
foreach ($sessions as $session) {
$session->stop();
}
}
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
/**
* @SWG\Definition(
* definition="Session",
* type="object",
* description="Session model",
* allOf={
* @SWG\Schema(ref="#/definitions/Session"),
* @SWG\Schema(
* @SWG\Property(property="login", type="string", example="28/03/2018 09:12:33", description="Datetime the user has logged in"),
* @SWG\Property(property="logout", type="string", example="28/03/2018 09:13:44", description="Datetime the user has logged out"),
* @SWG\Property(property="duration", type="integer", example=71, description="The session duration"),
* )
* }
* )
*/