<?php
namespace app\middleware;

use Closure;
use app\service\Jwt as JwtService;

/**
 * API登录认证（需要先调用JWT解析用户信息）
 * Class ApiLogin
 * @package app\middleware
 */
class ApiLogin
{
    public function handle($request, Closure $next) {
        $authorization = $request->authorization ?? '';
        if (empty($authorization)) {
            return json(['code' => 6001, 'msg' => '请填写token']);
        }
        if (!JwtService::validate($authorization)) {
            return json(['code' => 6001, 'msg' => 'token验证失败或已失效']);
        }

        $userInfo = $request->user ?? [];
        if (!isset($userInfo['user_id']) || empty($userInfo['user_id'])) {
            return json(['code' => 6001, 'msg' => 'token已失效']);
        }

        // 自定义过期时间校验。
        if(isset($userInfo['expire_time']) && time() >= $userInfo['expire_time']) {
            return json(['code' => 6001, 'msg' => 'token已失效']);
        }

        return $next($request);
    }
}