---
const pb = Astro.locals.pb
const redirectUrl = Astro.url.protocol + "//" + Astro.url.host + '/account/oauth';
const params = Astro.url.searchParams
const code = params.get('code')

// load the previously stored provider's data
const providerstr = Astro.cookies.get('provider')

if (!providerstr) {
    console.error("Fail to load provider")
    console.log(providerstr)
    return
}
const provider = providerstr.json()

if (!code) {
    console.error("Fail to load code params");
    return
}

// compare the redirect's state param and the stored provider's one
if (provider.state !== params.get('state')) {
    console.log(provider.state)
    console.log(params.get('state'))
    throw "State parameters don't match.";
}

let authenticated = false

await pb.collection('users').authWithOAuth2Code(
    provider.name,
    code,
    provider.codeVerifier,
    redirectUrl,
    {
        emailVisibility: false,
    }
).then((authData) => {
    //REDIRECT
    console.log("oauth OK !!");
    authenticated = true
  }).catch((err) => {
    console.log("oauth fail !!");
    console.log(err);
  });

if (authenticated) {
  return Astro.redirect("/account")
}

---


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>OAuth2 redirect page</title>
</head>
<body>
</body>
</html>
