async function stageTwoExchange()

in app/login/OAuthService.ts [21:97]


async function stageTwoExchange(
  searchParams: URLSearchParams,
  clientId: string,
  redirectUri: string,
  tokenUri: string
): Promise<OAuthResponse> {
  const authCode = searchParams.get("code");
  const errorInUrl = searchParams.get("error");
  const codeChallenge = sessionStorage.getItem("cx") as string | null; //this is set in OAuthContext.tsx, in @guardian/pluto-headers, via makeLoginUrl()
  sessionStorage.removeItem("cx");

  if (errorInUrl) {
    return {
      token: undefined,
      refreshToken: undefined,
      error: errorInUrl,
    };
  }

  if (!authCode) {
    return {
      error: "There was no code provided to exchange",
    };
  } else {
    const postdata: Record<string, string> = {
      grant_type: "authorization_code",
      client_id: clientId,
      redirect_uri: redirectUri,
      code: authCode,
    };
    console.log("passed client_id ", clientId);

    if (!!codeChallenge && codeChallenge != "") {
      console.log(`have code_verifier '${codeChallenge}' from step one`);
      postdata["code_verifier"] = codeChallenge;
    }

    const content_elements = Object.keys(postdata).map(
      (k) => k + "=" + encodeURIComponent(postdata[k])
    );

    const body_content = content_elements.join("&");

    const response = await fetch(tokenUri, {
      method: "POST",
      body: body_content,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
    switch (response.status) {
      case 200:
        const content = await response.json();

        return {
          token: content.id_token ?? content.access_token,
          refreshToken: content.hasOwnProperty("refresh_token")
            ? content.refresh_token
            : undefined,
          error: undefined,
        };

      default:
        const errorContent = await response.text();
        console.log(
          "token endpoint returned ",
          response.status,
          ": ",
          errorContent
        );
        return {
          error: "Could not get token from server",
        };
    }
  }
}