<?php
declare (strict_types = 1);

namespace app\openapi\middleware;

use OAuth2\OAuth2;
use OAuth2\OAuth2ServerException;
use oauth\OAuthStorage;

class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        try {
            $oauth = new OAuth2(new OAuthStorage, [
                'access_token_lifetime'  => intval(env('OPENAPI.ACCESS_TOKEN_LIFETIME', 3600)),
                'refresh_token_lifetime' => intval(env('OPENAPI.REFRESH_TOKEN_LIFETIME', 1209600)),
            ]);
            $token = $oauth->getBearerToken();
            $oauth->verifyAccessToken($token);
        } catch (OAuth2ServerException $e) {
            return json(json_decode($e->getHttpResponse()->getContent(), true), 401);
        } catch (\Throwable $th) {
            return json([
                'error'             => 'invalid_token',
                'error_description' => $th->getMessage()
            ], 401);
        }

        return $next($request);
    }
}
