Skip to content

Commit

Permalink
Merge pull request #123 from koya0/development
Browse files Browse the repository at this point in the history
  • Loading branch information
0x4007 authored Oct 27, 2024
2 parents d76acb1 + 1831918 commit 4a88f66
Show file tree
Hide file tree
Showing 13 changed files with 823 additions and 132 deletions.
Binary file removed bun.lockb
Binary file not shown.
106 changes: 106 additions & 0 deletions functions/referral-manager.ts
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" },
});
}
18 changes: 18 additions & 0 deletions functions/types.ts
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>>;
23 changes: 23 additions & 0 deletions functions/validators.ts
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 };
}
}
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"node": ">=20.10.0"
},
"scripts": {
"start": "tsx build/esbuild-server.ts",
"start": "wrangler pages dev --port 8080",
"build": "tsx build/esbuild-build.ts",
"format": "run-s format:lint format:prettier format:cspell",
"format:lint": "eslint --fix .",
Expand All @@ -30,15 +30,16 @@
"open-source"
],
"dependencies": {
"@cloudflare/workers-types": "^4.20241011.0",
"@octokit/request-error": "^6.1.0",
"@octokit/rest": "^20.0.2",
"@supabase/supabase-js": "^2.39.0",
"dotenv": "^16.3.1",
"esbuild-plugin-env": "^1.0.8",
"marked": "^11.0.0"
"marked": "^11.0.0",
"wrangler": "^3.83.0"
},
"devDependencies": {
"@cloudflare/wrangler": "^1.21.0",
"@commitlint/cli": "^18.4.3",
"@commitlint/config-conventional": "^18.4.3",
"@types/node": "^20.10.0",
Expand Down
4 changes: 2 additions & 2 deletions src/home/authentication.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { trackDevRelReferral } from "./devrel-tracker";
import { trackReferralCode } from "./register-referral";
import { getGitHubAccessToken } from "./getters/get-github-access-token";
import { getGitHubUser } from "./getters/get-github-user";
import { GitHubUser } from "./github-types";
Expand All @@ -18,7 +18,7 @@ export async function authentication() {

const gitHubUser: null | GitHubUser = await getGitHubUser();
if (gitHubUser) {
trackDevRelReferral(gitHubUser.login + "|" + gitHubUser.id);
await trackReferralCode();
await displayGitHubUserInformation(gitHubUser);
}
}
22 changes: 0 additions & 22 deletions src/home/devrel-tracker.ts

This file was deleted.

34 changes: 34 additions & 0 deletions src/home/getters/get-github-referrals.ts
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;
}
}
4 changes: 2 additions & 2 deletions src/home/home.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { grid } from "../the-grid";
import { authentication } from "./authentication";
import { initiateDevRelTracking } from "./devrel-tracker";
import { displayGitHubIssues } from "./fetch-github/fetch-and-display-previews";
import { postLoadUpdateIssues } from "./fetch-github/fetch-issues-full";
import { readyToolbar } from "./ready-toolbar";
import { initiateReferralCodeTracking } from "./register-referral";
import { renderServiceMessage } from "./render-service-message";
import { renderErrorInModal } from "./rendering/display-popup-modal";
import { loadIssueFromUrl } from "./rendering/render-github-issues";
Expand All @@ -20,8 +20,8 @@ window.addEventListener("unhandledrejection", (event: PromiseRejectionEvent) =>
event.preventDefault();
});

initiateReferralCodeTracking();
renderGitRevision();
initiateDevRelTracking();
generateSortingToolbar();
renderServiceMessage();

Expand Down
43 changes: 43 additions & 0 deletions src/home/register-referral.ts
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}`);
}
}
}
12 changes: 0 additions & 12 deletions static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,6 @@
<meta charset="UTF-8" />
<title>DevPool Directory | Ubiquity DAO</title>

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-VZLJ61H1YM"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());

gtag("config", "G-VZLJ61H1YM");
</script>

<link rel="stylesheet" href="style/style.css" />
<link rel="stylesheet" href="style/inverted-style.css" />
<link rel="stylesheet" href="style/special.css" />
Expand Down
17 changes: 17 additions & 0 deletions wrangler.toml
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 = ""

Loading

1 comment on commit 4a88f66

@ubiquity-os
Copy link
Contributor

@ubiquity-os ubiquity-os bot commented on 4a88f66 Oct 27, 2024

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

path: plugins/0/uses/0/with
value: undefined
message: Instance does not have required property "registerWalletWithVerification".

Caution

approvalsRequired:

path: plugins/5/uses/0/with
value: {"approvalsRequired":{"collaborator":1},"mergeTimeout":{"collaborator":"3.5 days"},"repos":{"ignore":["ubiquibot","launch-party","staging","production"]}}
message: Property "approvalsRequired" does not match schema.

Caution

path: plugins/5/uses/0/with/approvalsRequired
value: {"collaborator":1}
message: Instance does not have required property "contributor".

Caution

approvalsRequired:

path: plugins/5/uses/0/with
value: {"approvalsRequired":{"collaborator":1},"mergeTimeout":{"collaborator":"3.5 days"},"repos":{"ignore":["ubiquibot","launch-party","staging","production"]}}
message: Property "mergeTimeout" does not match schema.

Caution

collaborator: "3.5 days"

path: plugins/5/uses/0/with/mergeTimeout
value: {"collaborator":"3.5 days"}
message: Instance does not have required property "contributor".

Caution

approvalsRequired:

path: plugins/5/uses/0/with
value: {"approvalsRequired":{"collaborator":1},"mergeTimeout":{"collaborator":"3.5 days"},"repos":{"ignore":["ubiquibot","launch-party","staging","production"]}}
message: Property "repos" does not match schema.

Caution

path: plugins/5/uses/0/with/repos
value: {"ignore":["ubiquibot","launch-party","staging","production"]}
message: Instance does not have required property "monitor".

Caution

reviewDelayTolerance: "3 Days"

path: plugins/6/uses/0/with
value: {"reviewDelayTolerance":"3 Days","taskStaleTimeoutDuration":"30 Days","startRequiresWallet":true}
message: Instance does not have required property "maxConcurrentTasks".

Caution

reviewDelayTolerance: "3 Days"

path: plugins/6/uses/0/with
value: {"reviewDelayTolerance":"3 Days","taskStaleTimeoutDuration":"30 Days","startRequiresWallet":true}
message: Instance does not have required property "emptyWalletText".

Caution

reviewDelayTolerance: "3 Days"

path: plugins/6/uses/0/with
value: {"reviewDelayTolerance":"3 Days","taskStaleTimeoutDuration":"30 Days","startRequiresWallet":true}
message: Instance does not have required property "rolesWithReviewAuthority".

Caution

path: plugins/7/uses/0/with
value: undefined
message: Instance does not have required property "matchThreshold".

Caution

path: plugins/7/uses/0/with
value: undefined
message: Instance does not have required property "warningThreshold".

Caution

path: plugins/7/uses/0/with
value: undefined
message: Instance does not have required property "jobMatchingThreshold".

Please sign in to comment.