From 691d6c3d8b416dc828e5239893f44900179ac19d Mon Sep 17 00:00:00 2001 From: koya0 Date: Sat, 19 Oct 2024 00:48:47 -0300 Subject: [PATCH] feat: removed key and value parameters of POST request and added referralCode to POST body --- functions/tracker.ts | 64 ++++++++++++++++++-------------------- functions/types.ts | 17 ++++++++-- functions/validators.ts | 48 +++++++++++++++------------- src/home/authentication.ts | 2 +- src/home/devrel-tracker.ts | 9 ++++-- 5 files changed, 78 insertions(+), 62 deletions(-) diff --git a/functions/tracker.ts b/functions/tracker.ts index 93a0679a..019e00b6 100644 --- a/functions/tracker.ts +++ b/functions/tracker.ts @@ -21,12 +21,12 @@ export async function onRequest(ctx: Context): Promise { }); case "POST": - return await handleSet(url, env, request); + return await handleSet(env, request); case "GET": if (url.searchParams.has("key")) { - const keyParam = url.searchParams.get("key") as string; - return await handleGet(keyParam, env); + const key = url.searchParams.get("key") as string; + return await handleGet(key, env); } else { return await handleList(env); } @@ -46,55 +46,51 @@ export async function onRequest(ctx: Context): Promise { } } -async function handleSet(url: URL, env: Env, request: CustomRequest): Promise { - const key = url.searchParams.get("key"); - const value = url.searchParams.get("value"); +async function handleSet(env: Env, request: CustomRequest): Promise { + const result = await validatePOST(request); - if (key && value) { - const isValid = await validatePOST(url, request); - - if (!isValid) { - return new Response("Unauthorized", { - headers: corsHeaders, - status: 400, - }); - } - - await env.userToReferral.put(key, value); - return new Response(`Key '${key}' added with value '${value}'`, { + if (!result.isValid || !result.githubUserId || !result.referralCode) { + return new Response("Unauthorized", { headers: corsHeaders, - status: 200, + status: 400, }); } - return new Response("Missing key or value", { + + const { githubUserId, referralCode } = result; + + await env.KVNamespace.put(githubUserId, referralCode); + + return new Response(`Key '${githubUserId}' added with value '${referralCode}'`, { headers: corsHeaders, - status: 400, + status: 200, }); } -async function handleGet(key: string, env: Env): Promise { - const value = await env.userToReferral.get(key); - if (value) { - return new Response(`Value for '${key}': ${value}`, { +async function handleGet(githubUserId: string, env: Env): Promise { + const referralCode = await env.KVNamespace.get(githubUserId); + if (referralCode) { + return new Response(`Value for '${githubUserId}': ${referralCode}`, { headers: corsHeaders, status: 200, }); + } else { + return new Response(`No value found for '${githubUserId}'`, { + headers: corsHeaders, + status: 404, + }); } - return new Response(`No value found for '${key}'`, { - headers: corsHeaders, - status: 404, - }); } async function handleList(env: Env): Promise { - const keys = await env.userToReferral.list(); - const keyValuePairs: Record = {}; + const githubUsersIds = await env.KVNamespace.list(); + const referrals: Record = {}; - for (const key of keys.keys) { - keyValuePairs[key.name] = await env.userToReferral.get(key.name); + for (const { name: userId } of githubUsersIds.keys) { + const referralCode = await env.KVNamespace.get(userId); + referrals[userId] = referralCode; } - return new Response(JSON.stringify(keyValuePairs, null, 2), { + return new Response(JSON.stringify(referrals, null, 2), { headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } diff --git a/functions/types.ts b/functions/types.ts index 3b807458..c905822c 100644 --- a/functions/types.ts +++ b/functions/types.ts @@ -1,8 +1,19 @@ -import { EventContext, KVNamespace } from "@cloudflare/workers-types"; -import { Request, IncomingRequestCfProperties } from "@cloudflare/workers-types"; +import { EventContext, KVNamespace, Request, IncomingRequestCfProperties } from "@cloudflare/workers-types"; +import { OAuthToken } from "../src/home/getters/get-github-access-token"; export interface Env { - userToReferral: KVNamespace; + KVNamespace: KVNamespace; +} + +export interface POSTRequestBody { + authToken: OAuthToken; + referralCode: string; +} + +export interface ValidationResult { + isValid: boolean; + githubUserId?: string; + referralCode?: string; } export type Context = EventContext>; diff --git a/functions/validators.ts b/functions/validators.ts index fab19a68..f574f4ad 100644 --- a/functions/validators.ts +++ b/functions/validators.ts @@ -1,37 +1,43 @@ -import { CustomRequest } from "./types"; -import { OAuthToken } from "../src/home/getters/get-github-access-token"; +import { CustomRequest, POSTRequestBody, ValidationResult } from "./types"; import { Octokit } from "@octokit/rest"; -export async function validatePOST(url: URL, request: CustomRequest): Promise { +export async function validatePOST(request: CustomRequest): Promise { try { - const jsonData: unknown = await request.json(); - const authToken = jsonData as OAuthToken; + const jsonData: POSTRequestBody = await request.json(); - const providerToken = authToken?.provider_token; + const { authToken, referralCode } = jsonData; - if (providerToken) { - const octokit = new Octokit({ auth: providerToken }); + if (!authToken || !referralCode) { + console.error("Missing authToken or referralCode"); + return { isValid: false }; + } + + const providerToken = authToken.provider_token; - try { - await octokit.request("GET /user"); + if (!providerToken) { + console.error("Missing provider token"); + return { isValid: false }; + } - const githubUserId = authToken?.user?.user_metadata?.provider_id; + const octokit = new Octokit({ auth: providerToken }); - const key = url.searchParams.get("key"); + try { + await octokit.request("GET /user"); - if (githubUserId && githubUserId === key) { - return true; - } + const githubUserId = authToken.user?.user_metadata?.provider_id; - return false; - } catch (error) { - console.error("User is not logged in"); - return false; + if (githubUserId) { + return { isValid: true, githubUserId: githubUserId, referralCode: referralCode }; + } else { + console.error("Missing GitHub user ID"); + return { isValid: false }; } + } catch (error) { + console.error("User is not logged in"); + return { isValid: false }; } - return false; } catch (error) { console.error("Invalid JSON"); - return false; + return { isValid: false }; } } diff --git a/src/home/authentication.ts b/src/home/authentication.ts index 484fca2d..c3d251ad 100644 --- a/src/home/authentication.ts +++ b/src/home/authentication.ts @@ -13,7 +13,7 @@ export async function authentication() { const gitHubUser: null | GitHubUser = await getGitHubUser(); if (gitHubUser) { - await trackDevRelReferral(gitHubUser.id); + await trackDevRelReferral(); await displayGitHubUserInformation(gitHubUser); } } diff --git a/src/home/devrel-tracker.ts b/src/home/devrel-tracker.ts index 72c5a35e..05d48dcf 100644 --- a/src/home/devrel-tracker.ts +++ b/src/home/devrel-tracker.ts @@ -13,12 +13,12 @@ export function initiateDevRelTracking() { } } -export async function trackDevRelReferral(devGitHubId: number) { +export async function trackDevRelReferral() { const devRelCode = localStorage.getItem("devRel"); // key: user_id (devGitHubId), value: referral_id (devRelCode) if (devRelCode && devRelCode != "done") { - const url = `${WORKER_URL}/tracker?key=${encodeURIComponent(devGitHubId)}&value=${encodeURIComponent(devRelCode)}`; + const url = `${WORKER_URL}/tracker`; const authToken = await checkSupabaseSession(); @@ -27,7 +27,10 @@ export async function trackDevRelReferral(devGitHubId: number) { headers: { "Content-Type": "application/json", }, - body: JSON.stringify(authToken), + body: JSON.stringify({ + authToken: authToken, + referralCode: devRelCode, + }), }); if (response.status === 200) {