Personal Site

/callback now writes the result straight to ./.accessToken to be used later

vielle.dev 1243067f 4abcb8a4

verified
+35 -4
+35 -4
src/pages/_callback.astro
··· 1 1 --- 2 + import { SPOTIFY_CLIENT_SECRET } from "astro:env/server"; 2 3 import { SPOTIFY_CLIENT_ID, SPOTIFY_REDIRECT_URI } from "astro:env/server"; 3 - import { getAccessCode } from "/components/home/playing/spotify"; 4 + import fs from "node:fs/promises"; 5 + 4 6 // make a 404 if accidentally left in prod 5 7 if (import.meta.env.PROD) return Astro.redirect("/404", 404); 6 8 7 9 const userAuthCode = Astro.url.searchParams.get("code") ?? undefined; 8 10 9 - const userAccessToken = await getAccessCode(userAuthCode).catch((err) => err); 11 + if (userAuthCode) { 12 + fetch( 13 + "https://accounts.spotify.com/api/token", 14 + { 15 + method: "post", 16 + 17 + headers: { 18 + "content-type": "application/x-www-form-urlencoded", 19 + Authorization: 20 + "Basic " + 21 + Buffer.from(SPOTIFY_CLIENT_ID + ":" + SPOTIFY_CLIENT_SECRET).toString( 22 + "base64", 23 + ), 24 + }, 25 + 26 + body: new URLSearchParams({ 27 + code: userAuthCode, 28 + redirect_uri: SPOTIFY_REDIRECT_URI, 29 + grant_type: "authorization_code", 30 + }).toString(), 31 + }, 32 + ) 33 + .then((res) => res.text()) 34 + .then((token) => 35 + fs.writeFile("./.accessToken", token, { 36 + encoding: "utf-8", 37 + }), 38 + ) 39 + .catch((err) => console.error(err)); 40 + } 10 41 11 42 const href = `https://accounts.spotify.com/authorize?response_type=code&client_id=${SPOTIFY_CLIENT_ID}&scope=user-read-currently-playing&redirect_uri=${SPOTIFY_REDIRECT_URI}`; 12 43 --- ··· 35 66 </p> 36 67 37 68 <p> 38 - { 69 + <!-- { 39 70 userAuthCode && 40 71 (userAccessToken ? ( 41 72 <> ··· 45 76 ) : ( 46 77 <>Authentication Failed or was already used</> 47 78 )) 48 - } 79 + } --> 49 80 </p> 50 81 51 82 <style>