<?php

namespace app\middleware;

use addons\webman\model\ExternalApp;
use Tinywan\Jwt\JwtToken;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class ExternalAppMiddleware implements MiddlewareInterface
{
    /**
     * @throws \Exception
     */
    public function process(Request $request, callable $handler): Response
    {
        try {
            $id = JwtToken::getCurrentId();
            // 验证授权应用
            /** @var ExternalApp $externalApp */
            $externalApp = ExternalApp::where('id', base64_decode($id))->whereNull('deleted_at')->where('status', 1)->first();
            if (empty($externalApp)) {
                throw new \Exception('应用不存在');
            }
            // 验证服务器ip
            if (!empty($externalApp->white_ip) && !in_array(request()->getRealIp(), explode(',', $externalApp->white_ip))) {
                throw new \Exception('IP认证不通过');
            }
        } catch (\Exception $e) {
            return jsonFailResponse($e->getMessage(), [], 0);
        }
        return $handler($request);
    }
}