| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- namespace App\Models;
- class UserSession extends BaseModel
- {
- public const IDLE_SECONDS = 86400;
- public const LAST_ACTIVITY_SQL = 'CASE WHEN update_time > 0 THEN update_time ELSE create_time END';
- protected $table = 'user_session';
- protected $fillable = ['user_id', 'token', 'expire_time'];
-
- public $timestamps = true;
- protected $dateFormat = 'U'; // U 代表 UNIX 时间戳(int)
- // 2. 修改创建时间字段名为 create_time
- const CREATED_AT = 'create_time';
- const UPDATED_AT = 'update_time';
-
- public static function setToken($userId)
- {
- $time = now()->getTimestamp();
- $userSession = UserSession::where('user_id', $userId)->first();
- //获取token延长过期的时间
- $expireTime = $time + self::IDLE_SECONDS;
- $token = create_token($userId);
- //token处理
- if ($userSession) {
-
- //重新获取token
- $userSession->token = $token;
- $userSession->expire_time = $expireTime;
- $userSession->update_time = $time;
- $userSession->save();
- } else {
- //找不到在该终端的token记录,创建token记录
- $userSession = UserSession::create([
- 'user_id' => $userId,
- 'token' => $token,
- 'expire_time' => $expireTime
- ]);
- }
- return $token;
- }
- public static function validUntil(array $session): int
- {
- $lastActivity = (int)($session['update_time'] ?? 0);
- if ($lastActivity <= 0) $lastActivity = (int)($session['create_time'] ?? 0);
- return $lastActivity > 0 ? min((int)($session['expire_time'] ?? 0), $lastActivity + self::IDLE_SECONDS) : 0;
- }
- /** Renew only the same still-active token; never move the activity clock backwards. */
- public static function renewActiveToken(string $token, int $time, ?int $sessionId = null): ?self
- {
- if ($token === '') return null;
- $sessionId = $sessionId ?? static::where('token', $token)->value('id');
- if (!$sessionId) return null;
- static::where('id', $sessionId)->where('token', $token)->where('expire_time', '>', $time)
- ->whereRaw(self::LAST_ACTIVITY_SQL . ' > (? + 0)', [$time - self::IDLE_SECONDS])
- ->whereRaw(self::LAST_ACTIVITY_SQL . ' < (? + 0)', [$time])
- ->update(['expire_time' => $time + self::IDLE_SECONDS, 'update_time' => $time]);
- $session = static::where('id', $sessionId)->where('token', $token)->where('expire_time', '>', $time)->first();
- return $session && self::validUntil($session->getAttributes()) > $time ? $session : null;
- }
- }
|