Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement new tracker #123

Merged
merged 47 commits into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
d7d7378
chore: add node-fetch
koya0 Oct 12, 2024
a8f4e51
feat: add WORKER_URL to .env
koya0 Oct 12, 2024
a722e83
feat: add WORKER_URL to bundler
koya0 Oct 12, 2024
11860cb
feat: remove gtag.js
koya0 Oct 12, 2024
134db4d
feat: write new referral tracker
koya0 Oct 12, 2024
f4fc997
feat: adapt auth script to use new tracker
koya0 Oct 12, 2024
9fff8f0
feat: new getters for new tracker
koya0 Oct 12, 2024
80a8955
chore: remove node-fetch
koya0 Oct 12, 2024
0e41a0f
feat: create tracking folder
koya0 Oct 12, 2024
0433ba4
feat: create cloudflare worker file
koya0 Oct 12, 2024
c3d5645
chore: update lock file using [email protected] to match yarn version of Clo…
koya0 Oct 13, 2024
ba5bfde
chore: bun install
koya0 Oct 13, 2024
2f52bbf
feat: implement Cloudflare Page
koya0 Oct 14, 2024
084200d
feat: changed tracker.ts to .js
koya0 Oct 14, 2024
adf4f16
feat: add CORS headers to tracker.js responses
koya0 Oct 14, 2024
c01ed2a
feat: change .js files to .ts
koya0 Oct 15, 2024
181d00f
style: fixed formatting
koya0 Oct 15, 2024
942ae09
chore: bun install
koya0 Oct 15, 2024
b0e1bef
feat: implement GitHub Auth for tracker
koya0 Oct 16, 2024
a37f0e9
feat: update CORS Headers
koya0 Oct 16, 2024
ae87f15
feat: added CORS Headers to devrel-tracker.ts request and method "OPT…
koya0 Oct 16, 2024
2c7a6a7
feat: remove CORS Headers from devrel-tracker.ts and types.ts
koya0 Oct 16, 2024
4667f12
feat: fixed githubUserId and added providerToken checker
koya0 Oct 16, 2024
c59954d
feat: change GitHubAccessToken to SupabaseSession token
koya0 Oct 16, 2024
691d6c3
feat: removed key and value parameters of POST request and added refe…
koya0 Oct 19, 2024
4f3691c
feat: create wrangler.toml
koya0 Oct 19, 2024
6b53a77
feat: update kv-namespace id
koya0 Oct 19, 2024
47a705b
feat: remove WORKER_URL
koya0 Oct 19, 2024
3a91e50
feat: change CustomRequest to Request from @cloudflare/workers-types
koya0 Oct 19, 2024
acf600c
feat: change Supabase Auth Object to Github Auth Token for tracker auth
koya0 Oct 19, 2024
55889a7
feat: change Github issues json
koya0 Oct 19, 2024
2802d52
feat: change SUPABASE vars
koya0 Oct 19, 2024
929d477
feat: remove ?ref= from URL after auth
koya0 Oct 19, 2024
48741f3
chore: fix fetch-issues-full.ts comment conflict
koya0 Oct 20, 2024
316bfd5
feat: change tracker.ts name to referral-manager
koya0 Oct 23, 2024
825b21a
chore: change vars to secrets
koya0 Oct 23, 2024
6f5fa3e
feat: remove support for old tracker
koya0 Oct 23, 2024
7388232
style: change githubUserId vars for gitHubUserId
koya0 Oct 25, 2024
287e9b5
feat: moved oldRefCode checker to functions
koya0 Oct 25, 2024
d8811d9
Merge branch 'development' of https://github.com/ubiquity/work.ubq.fi…
koya0 Oct 26, 2024
35ff1c4
feat: store refCode in localStorage
koya0 Oct 26, 2024
18f3779
chore: replace @cloudflare/wrangler to wrangler and change start comm…
koya0 Oct 26, 2024
1a6b52e
chore: bun install
koya0 Oct 26, 2024
845a453
chore: remove bun.lockb
koya0 Oct 26, 2024
d1698a6
chore: update yarn.lock to v1.22.22
koya0 Oct 26, 2024
ba0d259
Merge branch 'development' of https://github.com/ubiquity/work.ubq.fi…
koya0 Oct 26, 2024
1831918
chore: add YARN_VERSION to wrangler.toml
koya0 Oct 27, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading