Skip to content

Instantly share code, notes, and snippets.

@learyjk
Created April 22, 2024 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save learyjk/d5bf06d3ba9dfb43eb46975ba343c821 to your computer and use it in GitHub Desktop.
Save learyjk/d5bf06d3ba9dfb43eb46975ba343c821 to your computer and use it in GitHub Desktop.
// This endpoint lives on my cloudflare worker
// It is called each time the user launches the DE.
// Note that we already have the user's access token from initial app install.
// The access token is stored in KV SITEID_SITE_INFO.
app.post('/resolve', async (c) => {
// Get the siteId and idToken from the request body
const body = await c.req.json();
const { siteId, idToken } = body;
// Check KV for access token and credits
const siteInfoResonse = await c.env.SITEID_SITE_INFO.get(siteId);
if (!siteInfoResonse) {
c.status(401);
return c.json({ message: 'Unauthorized. Site info not found.' });
}
const accessToken = JSON.parse(siteInfoResonse).access_token;
const credits = JSON.parse(siteInfoResonse).credits;
const isPatreon = JSON.parse(siteInfoResonse).isPatreon;
// Resolve the token
const options = {
method: 'POST',
headers: {
accept: 'application/json',
'content-type': 'application/json',
authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
idToken,
}),
};
try {
// This WF endpoint tells our app if that idToken is authorized on that site.
// It returns some basic user data (email, name, id) if successful.
const response = await fetch('https://api.webflow.com/beta/token/resolve', options);
const userData = (await response.json()) as WebflowResolveResponse;
if (!response.ok) {
throw new Error(`Failed to resolve token: ${response.status} ${response.statusText}.`);
}
// Generate a session token (1 day ttl) and store the session in KV
const sessionToken = uuidv4();
const ttl = TOKEN_LIFE_IN_DAYS * 24 * 60 * 60;
const sessionValue: SessionValue = {
accessToken,
siteId,
userData,
isPatreon,
};
// store the session token. After 1 day, Cloudflare automatically urges the token.
await c.env.ACTIVE_SESSIONS.put(sessionToken, JSON.stringify(sessionValue), { expirationTtl: ttl });
console.log('Created new session:', sessionToken, userData, sessionValue);
return c.json({ message: 'success!', sessionToken, credits, userData, isPatreon });
} catch (error) {
console.error('Error resolving token:', error);
return c.json({ message: 'Failed to resolve token.', error });
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment