Skip to content

Commit

Permalink
chore: rate limit modal and auto login
Browse files Browse the repository at this point in the history
  • Loading branch information
Keyrxng committed Mar 3, 2024
1 parent b856343 commit 498c806
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 11 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
SUPABASE_URL=
SUPABASE_ANON_KEY=
SUPABASE_REF=
SUPABASE_ANON_KEY=
2 changes: 1 addition & 1 deletion build/esbuild-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const cssEntries = ["static/style/style.css"];
const entries = [...typescriptEntries, ...cssEntries, "static/manifest.json", "static/favicon.svg", "static/icon-512x512.png"];

export const esBuildContext: esbuild.BuildOptions = {
define: createEnvDefines(["SUPABASE_URL", "SUPABASE_ANON_KEY"]),
define: createEnvDefines(["SUPABASE_URL", "SUPABASE_ANON_KEY", "SUPABASE_REF"]),
plugins: [invertColors, pwaManifest],
sourcemap: true,
entryPoints: entries,
Expand Down
3 changes: 2 additions & 1 deletion cypress/e2e/devpool.cy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { RestEndpointMethodTypes } from "@octokit/rest";
import { OAuthToken } from "../../src/home/getters/get-github-access-token";
import { getSupabaseRef } from "../../src/home/rendering/render-github-login-button";

describe("DevPool", () => {
let issue1: RestEndpointMethodTypes["issues"]["get"]["response"]["data"];
Expand Down Expand Up @@ -139,7 +140,7 @@ describe("DevPool", () => {
statusCode: 200,
});
// Simulate login token
window.localStorage.setItem("sb-wfzpewmlyiozupulbuur-auth-token", JSON.stringify(loginToken));
window.localStorage.setItem(`sb-${getSupabaseRef()}-auth-token`, JSON.stringify(loginToken));
}).as("githubLogin");
cy.visit("/");
cy.get("#github-login-button").click();
Expand Down
29 changes: 25 additions & 4 deletions src/home/fetch-github/fetch-issues-preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import { GitHubIssue } from "../github-types";
import { taskManager } from "../home";
import { displayPopupMessage } from "../rendering/display-popup-modal";
import { TaskNoFull } from "./preview-to-full-mapping";
import { getGitHubUser } from "../getters/get-github-user";
import { gitHubLoginButtonHandler } from "../rendering/render-github-login-button";

export async function fetchIssuePreviews(): Promise<TaskNoFull[]> {
const octokit = new Octokit({ auth: getGitHubAccessToken() });
const user = await getGitHubUser();

let freshIssues: GitHubIssue[] = [];
try {
Expand All @@ -17,8 +20,23 @@ export async function fetchIssuePreviews(): Promise<TaskNoFull[]> {
if (403 === error.status) {
console.error(`GitHub API rate limit exceeded.`);
if (taskManager.getTasks().length == 0) {
// automatically login if there are no issues loaded
automaticLogin(error);
if (!user || user === null) {
// only show rate limit modal if there are no issues loaded and not logged in
rateLimitModal(error);
} else {
// otherwise we have a user and no issues loaded
// this happens processing the auth token it seems
// as it happens on auth callback and local auth token
await gitHubLoginButtonHandler().catch((error) => {
console.error(error);
});
}
} else if (user && user !== null) {
// Tasks loaded and logged in
rateLimitModal(error, `You have been rate limited. Please try again at `);
} else {
// tasks loaded but not logged in
rateLimitModal(error);
}
} else {
console.error(`Failed to fetch issue previews: ${error}`);
Expand All @@ -34,12 +52,15 @@ export async function fetchIssuePreviews(): Promise<TaskNoFull[]> {

return tasks;
}
function automaticLogin(error: unknown) {

function rateLimitModal(error: unknown, message?: string) {
const resetTime = error.response.headers["x-ratelimit-reset"];
const resetParsed = new Date(resetTime * 1000).toLocaleTimeString();

displayPopupMessage(
`GitHub API rate limit exceeded.`,
`You have been rate limited. Please log in to GitHub to increase your GitHub API limits, otherwise you can try again at ${resetParsed}.`
!message
? `You have been rate limited. Please log in to GitHub to increase your GitHub API limits, otherwise you can try again at ${resetParsed}.`
: message + `${resetParsed}.`
);
}
5 changes: 3 additions & 2 deletions src/home/getters/get-github-access-token.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { getSupabaseRef } from "../rendering/render-github-login-button";
import { getLocalStore } from "./get-local-store";

export function getGitHubAccessToken(): string | null {
const oauthToken = getLocalStore("sb-wfzpewmlyiozupulbuur-auth-token") as OAuthToken | null;
const oauthToken = getLocalStore(`sb-${getSupabaseRef()}-auth-token`) as OAuthToken | null;

const expiresAt = oauthToken?.expires_at;
if (expiresAt) {
if (expiresAt < Date.now() / 1000) {
localStorage.removeItem("sb-wfzpewmlyiozupulbuur-auth-token");
localStorage.removeItem(`sb-${getSupabaseRef()}-auth-token`);
return null;
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/home/getters/get-github-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Octokit } from "@octokit/rest";
import { GitHubUser, GitHubUserResponse } from "../github-types";
import { OAuthToken } from "./get-github-access-token";
import { getLocalStore } from "./get-local-store";
import { getSupabaseRef } from "../rendering/render-github-login-button";

export async function getGitHubUser(): Promise<GitHubUser | null> {
const activeSessionToken = await getSessionToken();
Expand All @@ -13,7 +14,7 @@ export async function getGitHubUser(): Promise<GitHubUser | null> {
}

async function getSessionToken(): Promise<string | null> {
const cachedSessionToken = getLocalStore("sb-wfzpewmlyiozupulbuur-auth-token") as OAuthToken | null;
const cachedSessionToken = getLocalStore(`sb-${getSupabaseRef()}-auth-token`) as OAuthToken | null;
if (cachedSessionToken) {
return cachedSessionToken.provider_token;
}
Expand Down
9 changes: 8 additions & 1 deletion src/home/rendering/render-github-login-button.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@ if (!supabaseUrl) throw new Error("SUPABASE_URL not found");
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY;
if (!supabaseAnonKey) throw new Error("SUPABASE_ANON_KEY not found");

export function getSupabaseRef(): string {
const supabaseRef = process.env.SUPABASE_REF;
if (!supabaseRef) throw new Error("SUPABASE_REF not found");

return supabaseRef;
}

const supabase = createClient(supabaseUrl, supabaseAnonKey);

export function getSupabase() {
return supabase;
}

async function gitHubLoginButtonHandler() {
export async function gitHubLoginButtonHandler() {
const { error } = await supabase.auth.signInWithOAuth({ provider: "github" });
if (error) {
console.error("Error logging in:", error);
Expand Down

0 comments on commit 498c806

Please sign in to comment.