<?php
namespace app\middleware;

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

/**
 * 根据TOKEN解析用户信息
 *
 * Class JWT
 * @package app\middleware
 */
class JWT
{
    public function handle($request, Closure $next)
    {
        $authorization = $request->header('Authorization');
        $tokenStr      = $request->param('token/s', '');

        if ($authorization) {
            $authorization = str_replace('Bearer ', '', $authorization);
        }

        //优先取header中token
        $token      = $authorization ?: $tokenStr;
        $userInfo   = [];
        if (!empty($token)) {
            $userInfo = JwtService::parse($token);//token中携带的简易用户信息
        }

        $request->user          = $userInfo;
        // authorization用于移交ApiLogin认证
        $request->authorization = $token;

        return $next($request);
    }
}