generated from ubiquity/ts-template
-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #123 from koya0/development
- Loading branch information
Showing
13 changed files
with
823 additions
and
132 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
import { Env, Context } from "./types"; | ||
import { validatePOST } from "./validators"; | ||
import { Request } from "@cloudflare/workers-types"; | ||
|
||
export const corsHeaders = { | ||
"Access-Control-Allow-Origin": "*", | ||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS", | ||
"Access-Control-Allow-Headers": "Content-Type", | ||
}; | ||
|
||
export async function onRequest(ctx: Context): Promise<Response> { | ||
const { request, env } = ctx; | ||
|
||
const url = new URL(request.url); | ||
|
||
try { | ||
switch (request.method) { | ||
case "OPTIONS": | ||
return new Response(null, { | ||
headers: corsHeaders, | ||
status: 204, | ||
}); | ||
|
||
case "POST": | ||
return await handleSet(env, request); | ||
|
||
case "GET": | ||
if (url.searchParams.has("key")) { | ||
const key = url.searchParams.get("key") as string; | ||
return await handleGet(key, env); | ||
} else { | ||
return await handleList(env); | ||
} | ||
|
||
default: | ||
return new Response("Method Not Allowed", { | ||
headers: corsHeaders, | ||
status: 405, | ||
}); | ||
} | ||
} catch (error) { | ||
console.error("Error processing request:", error); | ||
return new Response("Internal Server Error", { | ||
headers: corsHeaders, | ||
status: 500, | ||
}); | ||
} | ||
} | ||
|
||
async function handleSet(env: Env, request: Request): Promise<Response> { | ||
const result = await validatePOST(request); | ||
|
||
if (!result.isValid || !result.gitHubUserId || !result.referralCode) { | ||
return new Response("Unauthorized", { | ||
headers: corsHeaders, | ||
status: 400, | ||
}); | ||
} | ||
|
||
const { gitHubUserId, referralCode } = result; | ||
|
||
const oldRefCode = await env.KVNamespace.get(gitHubUserId); | ||
|
||
if (oldRefCode) { | ||
return new Response(`Key '${gitHubUserId}' already has a referral code: '${oldRefCode}'`, { | ||
headers: corsHeaders, | ||
status: 404, | ||
}); | ||
} | ||
|
||
await env.KVNamespace.put(gitHubUserId, referralCode); | ||
|
||
return new Response(`Key '${gitHubUserId}' added with value '${referralCode}'`, { | ||
headers: corsHeaders, | ||
status: 200, | ||
}); | ||
} | ||
|
||
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, | ||
}); | ||
} | ||
} | ||
|
||
async function handleList(env: Env): Promise<Response> { | ||
const gitHubUsersIds = await env.KVNamespace.list(); | ||
const referrals: Record<string, string | null> = {}; | ||
|
||
for (const { name: userId } of gitHubUsersIds.keys) { | ||
const referralCode = await env.KVNamespace.get(userId); | ||
referrals[userId] = referralCode; | ||
} | ||
|
||
return new Response(JSON.stringify(referrals, null, 2), { | ||
headers: { ...corsHeaders, "Content-Type": "application/json" }, | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { EventContext, KVNamespace } from "@cloudflare/workers-types"; | ||
|
||
export interface Env { | ||
KVNamespace: KVNamespace; | ||
} | ||
|
||
export interface POSTRequestBody { | ||
authToken: string; | ||
referralCode: string; | ||
} | ||
|
||
export interface ValidationResult { | ||
isValid: boolean; | ||
gitHubUserId?: string; | ||
referralCode?: string; | ||
} | ||
|
||
export type Context = EventContext<Env, string, Record<string, string>>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { POSTRequestBody, ValidationResult } from "./types"; | ||
import { GitHubUserResponse } from "../src/home/github-types"; | ||
import { Request } from "@cloudflare/workers-types"; | ||
import { Octokit } from "@octokit/rest"; | ||
|
||
export async function validatePOST(request: Request): Promise<ValidationResult> { | ||
const jsonData: POSTRequestBody = await request.json(); | ||
|
||
const { authToken, referralCode } = jsonData; | ||
|
||
const octokit = new Octokit({ auth: authToken }); | ||
|
||
try { | ||
const response = (await octokit.request("GET /user")) as GitHubUserResponse; | ||
|
||
const gitHubUser = response.data; | ||
|
||
return { isValid: true, gitHubUserId: gitHubUser.id.toString(), referralCode: referralCode }; | ||
} catch (error) { | ||
console.error("User is not logged in"); | ||
return { isValid: false }; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
export async function getReferralFromUser(devGitHubId: string): Promise<string | null> { | ||
const url = `/referral-manager?key=${encodeURIComponent(devGitHubId)}`; | ||
|
||
const response = await fetch(url, { | ||
method: "GET", | ||
}); | ||
|
||
if (response.status === 200) { | ||
const referralId = await response.text(); | ||
return referralId; | ||
} else if (response.status == 404) { | ||
// No referral id found for devGitHubId | ||
return null; | ||
} else { | ||
console.error(`Failed to get key: '${devGitHubId}'. Status: ${response.status}`); | ||
return null; | ||
} | ||
} | ||
|
||
export async function getListOfReferrals(): Promise<Record<string, string | null> | null> { | ||
const url = "/referral-manager"; | ||
|
||
const response = await fetch(url, { | ||
method: "GET", | ||
}); | ||
|
||
if (response.status === 200) { | ||
const data = await response.json(); | ||
return data; // return JSON file of pairs {key, value} | ||
} else { | ||
console.error(`Failed to fetch list. Status: ${response.status}`); | ||
return null; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { checkSupabaseSession } from "./rendering/render-github-login-button"; | ||
|
||
export function initiateReferralCodeTracking() { | ||
const oldRefCode = localStorage.getItem("ref"); | ||
if (!oldRefCode) { | ||
const urlParams = new URLSearchParams(window.location.search); | ||
const refCode = urlParams.get("ref"); | ||
if (refCode) { | ||
localStorage.setItem("ref", refCode); | ||
} | ||
} | ||
} | ||
|
||
export async function trackReferralCode() { | ||
const refCode = localStorage.getItem("ref"); | ||
|
||
if (refCode && refCode != "done") { | ||
const url = "/referral-manager"; | ||
|
||
const supabaseAuth = await checkSupabaseSession(); | ||
|
||
const response = await fetch(url, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
body: JSON.stringify({ | ||
authToken: supabaseAuth.provider_token, | ||
referralCode: refCode, | ||
}), | ||
}); | ||
|
||
if (response.status === 200) { | ||
localStorage.setItem("ref", "done"); | ||
|
||
const newURL = new URL(window.location.href); | ||
newURL.searchParams.delete("ref"); | ||
window.history.pushState({}, "", newURL.toString()); | ||
} else { | ||
console.error(`Failed to set referral. Status: ${response.status}`); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
name = "work-ubq-fi" | ||
|
||
compatibility_date = "2024-10-23" | ||
|
||
pages_build_output_dir = "./static" | ||
|
||
[[kv_namespaces]] | ||
binding = "KVNamespace" | ||
id = "0a6aaf0a6edb428189606b116da58ef7" | ||
|
||
[vars] | ||
YARN_VERSION = "1.22.22" | ||
|
||
# These secrets need to be configured via Cloudflare dashboard: | ||
# SUPABASE_URL = "" | ||
# SUPABASE_ANON_KEY = "" | ||
|
Oops, something went wrong.
4a88f66
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@0x4007 Configuration is invalid.
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 1 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 105 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 106 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 105 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 108 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 105 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 110 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 118 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 118 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 118 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 1 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 1 in 4a88f66
Caution
work.ubq.fi/.github/.ubiquity-os.config.yml
Line 1 in 4a88f66