<?php
namespace app\admin\middleware;

use app\admin\model\SystemAdmin;
use Tinywan\Jwt\Exception\JwtTokenException;
use Tinywan\Jwt\JwtToken;
use Webman\Http\Response;
use Webman\Http\Request;
use Webman\MiddlewareInterface;

/**
 * 登录验证中间件
 * Class JwtAuthMiddleware
 * @package app\admin\middleware
 */
class JwtAuthMiddleware implements MiddlewareInterface
{

    public function process(Request $request, callable $next): Response
    {
        if ($request->method() === 'OPTIONS') {
            response('', 204);
        }
        try {
            $token = $request->header('Authorization');
            if (strpos($token, 'Bearer') === 0){
                $token = trim(substr($token, 6));
            }
            if(!$token)
            {
                throw new JwtTokenException('请登录', 500);
            }
            $rest = JwtToken::verify(1, $token);
            $request->admin_id = JwtToken::getCurrentId();
            $request->admin_token = $token;
            $request->admin_info = SystemAdmin::getAdminInfo($request->admin_id);
            return $next($request);
        } catch (JwtTokenException $e) {
            throw new JwtTokenException($e->getMessage(), $e->getCode());
        }
    }
}
