<?php


namespace app\middleware;


use Tinywan\Jwt\Exception\JwtTokenException;
use Tinywan\Jwt\JwtToken;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class WechatAuthCheck implements MiddlewareInterface
{

    /**
     * @inheritDoc
     */
    public function process(Request $request, callable $handler): Response
    {
        try {
            // 跳过不需要验证的控制器方法
            $controller = new \ReflectionClass($request->controller);
            $notNeedLogin = $controller->getDefaultProperties()['notNeedLogin'] ?? [];
            if (in_array($request->action, $notNeedLogin)) {
                return $handler($request);
            }

            $token = $request->header('Authorization');
            if (!$token) {
                throw new JwtTokenException('请先登录~', 500);
            }
            if (strpos($token, 'Bearer') === 0) {
                $token = trim(substr($token, 6));
            }
            JwtToken::verify(1, $token);
            $request->user_id = JwtToken::getCurrentId();
            $request->userInfo = JwtToken::getExtend();

            return $handler($request);
        } catch (JwtTokenException $e) {
            return json_fail($e->getMessage());
        }
    }
}