Skip to content

Commit

Permalink
feat: removed key and value parameters of POST request and added refe…
Browse files Browse the repository at this point in the history
…rralCode to POST body
  • Loading branch information
koya0 committed Oct 19, 2024
1 parent c59954d commit 691d6c3
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 62 deletions.
64 changes: 30 additions & 34 deletions functions/tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ export async function onRequest(ctx: Context): Promise<Response> {
});

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);
}
Expand All @@ -46,55 +46,51 @@ export async function onRequest(ctx: Context): Promise<Response> {
}
}

async function handleSet(url: URL, env: Env, request: CustomRequest): Promise<Response> {
const key = url.searchParams.get("key");
const value = url.searchParams.get("value");
async function handleSet(env: Env, request: CustomRequest): Promise<Response> {
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<Response> {
const value = await env.userToReferral.get(key);
if (value) {
return new Response(`Value for '${key}': ${value}`, {
async function handleGet(githubUserId: string, env: Env): Promise<Response> {
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<Response> {
const keys = await env.userToReferral.list();
const keyValuePairs: Record<string, string | null> = {};
const githubUsersIds = await env.KVNamespace.list();
const referrals: Record<string, string | null> = {};

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" },
});
}
17 changes: 14 additions & 3 deletions functions/types.ts
Original file line number Diff line number Diff line change
@@ -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<Env, string, Record<string, string>>;
Expand Down
48 changes: 27 additions & 21 deletions functions/validators.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
export async function validatePOST(request: CustomRequest): Promise<ValidationResult> {
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 };
}
}
2 changes: 1 addition & 1 deletion src/home/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
9 changes: 6 additions & 3 deletions src/home/devrel-tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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) {
Expand Down

0 comments on commit 691d6c3

Please sign in to comment.