| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <?php
- namespace App\Http\Middleware;
- use App\Models\User;
- use App\Models\UserSession;
- use Closure;
- use Illuminate\Http\Request;
- class CheckToken
- {
- private const ACTIVITY_WRITE_INTERVAL = 60;
- /**
- * 处理传入请求
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle(Request $request, Closure $next)
- {
- // 1. 前台沿用 Authorization 请求头中的原始 Token
- $token = $request->header('authorization');
- // 2. 如果请求头没有 token,直接返回未授权
- if (empty($token)) {
- return response()->json([
- 'code' => 401,
- 'msg' => lang('请携带token访问')
- ], 401);
- }
- // 3. 查询 user_session:token 存在 + 未过期
- $time = now()->getTimestamp();
- $session = UserSession::findActiveToken($token, $time);
- // 4. 会话不存在或已过期
- if (!$session) {
- return response()->json([
- 'code' => 401,
- 'msg' => lang('token无效或已过期')
- ], 401);
- }
- // 5. 查询对应用户信息
- $user = User::where('user_id',$session->user_id)->first();
- // 6. 用户不存在
- if (!$user || !empty($user->getAttributes()['delete_time'])) {
- return response()->json([
- 'code' => 401,
- 'msg' => lang('用户不存在')
- ], 401);
- }
- if ((int)($user->getAttributes()['is_banned'] ?? 0) === 1) {
- return response()->json(['code' => 401, 'msg' => lang('账号已禁用')], 401);
- }
- if (!UserSession::renewActiveToken((string)$token, $time, (int)$session->id)) {
- return response()->json(['code' => 401, 'msg' => lang('token无效或已过期')], 401);
- }
- $attributes = $user->getAttributes();
- $cutoff = $time - self::ACTIVITY_WRITE_INTERVAL;
- if (array_key_exists('last_active_time', $attributes) && (int) $attributes['last_active_time'] <= $cutoff) {
- User::whereKey($user->getKey())
- ->where(fn ($query) => $query->whereNull('last_active_time')->orWhere('last_active_time', '<=', $cutoff))
- ->toBase()->update(['last_active_time' => $time]);
- }
- // 7. 把用户信息赋值给 $request->user
- $request->user = $user;
- // 8. 放行请求,进入控制器
- return $next($request);
- }
- }
|