<?php
declare (strict_types=1);

namespace app\api\middleware;

use app\api\model\User;
use app\dict\sys\AppTypeDict;
use core\util\TokenAuth;

/**
 * API Token验证中间件
 */
class TokenMiddleware
{
    public function handle($request, \Closure $next)
    {
        $token = $request->header('Token');
        if (empty($token)) {
            return json(['code' => 0, 'msg' => '请先登录', 'data' => []], 401);
        }
        $token = trim($token);

        try {
            $tokenInfo = TokenAuth::parseToken($token, AppTypeDict::API);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '登录已过期，请重新登录', 'data' => []], 401);
        }

        $request->userId = $tokenInfo['user_id'] ?? 0;
        $request->userInfo = (new User())->find($request->userId);

        if (!$request->userInfo) {
            return json(['code' => 0, 'msg' => '用户不存在', 'data' => []], 401);
        }

        return $next($request);
    }
}
