Skip to content

Commit

Permalink
Merge pull request #46 from /issues/23
Browse files Browse the repository at this point in the history
Issues/23
  • Loading branch information
nasubi916 authored Jun 20, 2024
2 parents 782f4b0 + adcc893 commit c3fdcc9
Show file tree
Hide file tree
Showing 27 changed files with 2,046 additions and 60 deletions.
3 changes: 3 additions & 0 deletions .dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ESA_APP_CLIENT_ID = "xxxxxxxxxxxxxxxxxx"
ESA_APP_CLIENT_SECRET = "xxxxxxxxxxxxxxxxxx"
ESA_APP_REDIRECT_URI = "xxxxxxxxxxxxxxxxxx"
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
VITE_ESA_APP_CLIENT_ID=xxxxxxxxxxxxxxxxxx
VITE_ESA_APP_REDIRECT_URI=xxxxxxxxxxxxxxxxxx
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
vite.config.mts
src/vite-env.d.ts
functions/
3 changes: 0 additions & 3 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,6 @@
}
}
],
"react/function-component-definition": [
2
],
"unused-imports/no-unused-imports": "error",
"react-refresh/only-export-components": "warn"
}
Expand Down
24 changes: 16 additions & 8 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,26 @@ jobs:

- name: 🏗️ Build app
run: yarn run build
env:
VITE_CLIENT_ID: ${{ secrets.CLIENT_ID }}
VITE_REDIRECT_URI: ${{ secrets.REDIRECT_URI }}

- name: 🚀 Deploy to Cloudflare Pages
id: cloudflare_pages_deploy
uses: cloudflare/pages-action@v1.4.0
uses: cloudflare/wrangler-action@2.0.0
with:
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
projectName: esachievement
directory: ./dist
command: "pages deploy ./dist --project-name esachievement"
secrets: |
CLIENT_ID
SECRET_CLIENT_ID
REDIRECT_URI
env:
NODE_VERSION: 22
CLIENT_ID: ${{ secrets.CLIENT_ID }}
SECRET_CLIENT_ID: ${{ secrets.SECRET_CLIENT_ID }}
REDIRECT_URI: ${{ secrets.REDIRECT_URI }}

- name: 🚀 Deploy pages based on commit sha
uses: actions/github-script@v6
Expand All @@ -52,9 +60,9 @@ jobs:
await github.rest.repos.createCommitStatus({
owner: context.repo.owner,
repo: context.repo.repo,
context: 'cloudflare / build (push)',
description: 'Commit based deploy',
state: 'success',
context: "cloudflare / build (push)",
description: "Commit based deploy",
state: "success",
sha,
target_url: "${{ steps.cloudflare_pages_deploy.outputs.url }}",
target_url: "esachievement.pages.dev",
});
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,8 @@ dist-ssr
*.sw?
*.env
*.env.local
!.env.example
!.env.example

src/lib/services/esa.gen.ts
.wrangler/
.dev.vars
14 changes: 14 additions & 0 deletions functions/__lib/consts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export type Env = {
ESA_APP_CLIENT_ID: string;
ESA_APP_CLIENT_SECRET: string;
ESA_APP_REDIRECT_URI: string;
};

export function getEnv<T extends keyof Env>(env: Partial<Env>, key: T): Env[T] {
const value = env[key];
if (value == null) {
throw new Error(`Environment variable ${key} is not set`);
}

return value;
}
58 changes: 58 additions & 0 deletions functions/auth/token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { PagesFunction } from "@cloudflare/workers-types";
import { string, object } from "yup";
import { Env } from "../__lib/consts.js";

export const onRequestOptions: PagesFunction<Env> = async ({ env }) => {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": new URL(env.ESA_APP_REDIRECT_URI).origin,
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Max-Age": "86400",
},
});
};

export const onRequest: PagesFunction<Env> = async ({ request, env }) => {
if (request.method !== "POST") {
return new Response("Method not allowed.", { status: 405 });
}

const requestAccessTokenSchema = object().shape({
code: string(),
});

let code: string;
try {
code = (await requestAccessTokenSchema.validate(await request.json())).code;
} catch (err) {
return new Response(err, { status: 400 });
}

const res = await fetch("https://api.esa.io/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: env.ESA_APP_CLIENT_ID,
client_secret: env.ESA_APP_CLIENT_SECRET,
code: code,
grant_type: "authorization_code",
redirect_uri: env.ESA_APP_REDIRECT_URI,
}),
});

if (!res.ok) {
return new Response("Failed to request access token!", {
status: 500,
});
}

return new Response(await res.text(), {
headers: {
"Content-Type": "application/json",
},
});
};
13 changes: 13 additions & 0 deletions functions/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "esnext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": [
"esnext"
],
"types": [
"@cloudflare/workers-types"
]
}
}
22 changes: 18 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"prepare": "npm run gen:esa-type",
"dev": "vite",
"build": "tsc && vite build",
"dev:workers": "wrangler pages dev -- yarn dev",
"build": "tsc && vite build && cpx \"functions/**\" dist/functions",
"preview": "vite preview",
"fmt": "prettier --write ./src/",
"lint": "eslint --ext .ts,.tsx ./src"
"lint": "eslint --ext .ts,.tsx ./src",
"gen:esa-type": "openapi-typescript https://raw.githubusercontent.com/suin/esa-openapi/main/esa-api.json -o ./src/lib/services/esa.gen.ts"
},
"engines": {
"node": "22"
Expand All @@ -17,20 +20,29 @@
"@fontsource-variable/noto-sans-jp": "^5.0.19",
"@generouted/react-router": "^1.19.3",
"@iconify/react": "^4.1.1",
"@nanostores/persistent": "^0.10.1",
"@nanostores/react": "^0.7.2",
"@radix-ui/themes": "^3.0.5",
"nanostores": "^0.10.3",
"openapi-fetch": "^0.9.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.1",
"styled-components": "^6.1.11",
"the-new-css-reset": "^1.11.2"
"swr": "^2.2.5",
"the-new-css-reset": "^1.11.2",
"ts-pattern": "^5.2.0",
"yup": "^1.4.0"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20240614.0",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
"@vitejs/plugin-react-swc": "^3.5.0",
"@vitest/ui": "^1.5.0",
"cpx": "^1.5.0",
"eslint": "^8.57.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^18.0.0",
Expand All @@ -44,9 +56,11 @@
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"eslint-plugin-unused-imports": "^3.1.0",
"openapi-typescript": "^6.7.6",
"prettier": "^3.2.5",
"typescript": "^5.4.5",
"vite": "^5.2.0",
"vite-tsconfig-paths": "^4.3.2"
"vite-tsconfig-paths": "^4.3.2",
"wrangler": "^3.61.0"
}
}
19 changes: 19 additions & 0 deletions src/api/esa.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@


export const useEsa = () => {
const getAchievement = async (access_token: string, team_name: string) => {
console.log(access_token);
console.log(team_name);
const data = await fetch(`https://api.esa.io/v1/teams/${team_name}/members`, {
method: "GET",
mode: "cors",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
});
return await data.json();
}
return { getAchievement };
}
9 changes: 9 additions & 0 deletions src/components/Center.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import styled from "styled-components";

export const Center = styled.div`
height: 100%;
width: 100%;
display: grid;
place-items: center;
place-content: center;
`;
10 changes: 9 additions & 1 deletion src/components/Redirects.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { type ReactNode } from "react";
import { useLocation } from "react-router-dom";
import { $hasAuthenticated } from "@/lib/stores/auth";
import { redirect } from "@/router";

export function Redirects({ children }: { children: ReactNode }): ReactNode {
// const { pathname } = useLocation();
const { pathname } = useLocation();

const isInPublicPaths = pathname === "/" || pathname.startsWith("/auth");
if (!$hasAuthenticated.get() && !isInPublicPaths) {
redirect("/auth/login");
}

return children;
}
28 changes: 28 additions & 0 deletions src/lib/consts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { P } from "ts-pattern";
import { type Env } from "@/types/env";

export async function waitMs(ms: number): Promise<void> {
await new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

export function getEnv(key: keyof Env): string {
const value = import.meta.env[key];
if (value == null) {
throw new Error(`Environment variable ${key} is not set`);
}
return value;
}

export const S = {
Error: { error: P.not(undefined) },
Loading: { isLoading: true },
Success: { data: P.not(undefined) },
};

export const APP_NAME = "esachievement";
export const LOCAL_STORAGE_VERSION = "1";
export function getLocalStorageKey(key: string, trailingColon = false): string {
return `${APP_NAME}.v${LOCAL_STORAGE_VERSION}.${key}${trailingColon ? ":" : ""}`;
}
50 changes: 50 additions & 0 deletions src/lib/services/esa.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import createClient from "openapi-fetch";
import { type paths } from "./esa.gen";
import { getEnv } from "@/lib/consts";
import { $accessTokenData } from "@/lib/stores/auth";
import { type AccessTokenData } from "@/types/auth";

export function getAuthorizePageUrl(): string {
const query = new URLSearchParams({
client_id: getEnv("VITE_ESA_APP_CLIENT_ID"),
redirect_uri: getEnv("VITE_ESA_APP_REDIRECT_URI"),
response_type: "code",
scope: "read write",
});

return `https://api.esa.io/oauth/authorize?${query.toString()}`;
}

export async function requestAccessTokenData(
code: string,
): Promise<AccessTokenData> {
const res = await fetch("/auth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ code }),
});

if (!res.ok) {
throw new Error(
`Failed to request access token!: ${res.status} ${res.statusText}`,
);
}

return await res.json();
}

export const esaClient = createClient<paths>({
baseUrl: "https://api.esa.io/v1",
});

esaClient.use({
onRequest: async (req) => {
const token = $accessTokenData.get();
if (token == null) throw new Error("Access token has not been set");

req.headers.set("Authorization", `Bearer ${token.access_token}`);
return req;
},
});
19 changes: 19 additions & 0 deletions src/lib/stores/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { persistentAtom } from "@nanostores/persistent";
import { computed } from "nanostores";
import { getLocalStorageKey } from "@/lib/consts";
import { type AccessTokenData } from "@/types/auth";
import { type Nullable } from "@/types/utils";

export const $accessTokenData = persistentAtom<Nullable<AccessTokenData>>(
getLocalStorageKey("accessTokenData"),
undefined,
{
encode: JSON.stringify,
decode: JSON.parse,
},
);

export const $hasAuthenticated = computed(
$accessTokenData,
(data) => data != null,
);
Loading

0 comments on commit c3fdcc9

Please sign in to comment.