Compare commits

..

5 Commits

Author SHA1 Message Date
ethanf
fe02a090d3 feat-wip: steam sign in provided by ctx 2024-10-11 01:15:56 -05:00
ethanf
8e77e76069 start new project 2024-10-03 04:13:52 -05:00
Jo Franchetti
74206e0eb6 Merge branch 'main' of https://github.com/denoland/tutorial-with-react 2024-09-26 18:57:28 +01:00
Jo Franchetti
49c2782b1d update readme 2024-09-26 18:57:17 +01:00
deno-deploy[bot]
ede4f0cf71
[Deno Deploy] Update .github/workflows/deploy.yml 2024-09-26 17:42:15 +00:00
15 changed files with 2348 additions and 1619 deletions

2
.gitignore vendored
View File

@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?
.env

View File

@ -1,39 +1,45 @@
# React + TypeScript + Vite
# Deno and React.js
This template provides a minimal setup to get React working in Vite with HMR and
some ESLint rules.
## A dinosaur app built with React, Vite and TypeScript
Currently, two official plugins are available:
This demo is a simple React app. It uses Vite as the local server, and is
written in TypeScript. The app is a simple dinosaur app that displays a list of
dinosaurs and allows the user to add a new dinosaur to the list.
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md)
uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc)
uses [SWC](https://swc.rs/) for Fast Refresh
You can follow along with the tutorial on the
[Deno Docs](https://docs.deno.com/runtime/tutorials/how_to_with_npm/react/).
## Expanding the ESLint configuration
## Run the app
If you are developing a production application, we recommend updating the
configuration to enable type aware lint rules:
To run the app, you need to have [Deno](https://deno.land/) installed on your
machine. You can install Deno by running the following command, or following the
instructions in the [Deno docs](https://docs.deno.com/runtime/):
- Configure the top-level `parserOptions` property like this:
```js
export default {
// other rules...
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
project: ["./tsconfig.json", "./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: __dirname,
},
};
```bash
curl -fsSL https://deno.land/install.sh | sh
```
- Replace `plugin:@typescript-eslint/recommended` to
`plugin:@typescript-eslint/recommended-type-checked` or
`plugin:@typescript-eslint/strict-type-checked`
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
- Install
[eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and
add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends`
list
Once you have Deno installed, you can run the app with the following command:
```bash
deno task dev
```
## Build the app
To build the app, you can run the following command:
```bash
deno task build
```
## Serve the app with Deno
To serve the app with Deno, you can run the following command:
```bash
deno task serve
```
![Deno logo](https://docs.deno.com/img/logo.svg)  💚
![Vue logo by Evan Yu](./src/assets/react.svg)

View File

@ -1,9 +1,80 @@
import { Application, Router } from "@oak/oak";
import { oakCors } from "@tajpouria/cors";
/// <reference lib="deno.ns" />
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";
import { CookieStore, Session } from "https://deno.land/x/oak_sessions/mod.ts";
import data from "./data.json" with { type: "json" };
import routeStaticFilesFrom from "./util/routeStaticFilesFrom.ts";
const router = new Router();
import SteamAuth from "https://deno.land/x/deno_steam_openid@0.0.1/mod.ts";
import "https://deno.land/x/dotenv/load.ts";
type AppState = {
session: Session;
};
const router = new Router<AppState>();
const hostname = "localhost";
const authPath = "/auth";
const port = 8000;
export interface SteamUser {
steamid: string;
personaname: string;
profileurl: string;
avatar: string;
avatarmedium: string;
avatarfull: string;
personastate: number;
communityvisibilitystate: number;
profilestate: number;
lastlogoff: number;
commentpermission: number;
realname: string;
primaryclanid: string;
timecreated: number;
personastateflags: number;
loccountrycode: string;
locstatecode: string;
loccityid: number;
}
export const Steam = new SteamAuth({
realm: `http://${hostname}:${port}`,
returnUrl: `http://${hostname}:${port}${authPath}/return`,
apiKey: Deno.env.get("STEAM_API_KEY"),
});
router.get(`${authPath}/login`, async (ctx) => {
try {
const redirectUrl = await Steam.getRedirectUrl() as string;
ctx.response.body = { url: redirectUrl };
} catch (e) {
ctx.response.body = `Error: ${e}`;
}
});
router.get(`${authPath}/return`, async (ctx) => {
try {
const user = await Steam.authenticate(ctx) as SteamUser;
ctx.state.session.set("steamid", user.steamid);
ctx.state.session.set("user", user);
ctx.response.redirect(`http://localhost:5173/signedIn`);
} catch (e) {
ctx.response.body = `Error: ${e}`;
}
});
router.get("/api/session", async (ctx) => {
if (ctx.state.session.has("user")) {
const user = await ctx.state.session.get("user") as SteamUser;
ctx.response.body = { user };
} else {
ctx.response.status = 401;
ctx.response.body = { error: "Not authenticated" };
}
});
router.get("/api/dinosaurs", (context) => {
context.response.body = data;
@ -21,8 +92,17 @@ router.get("/api/dinosaurs/:dinosaur", (context) => {
context.response.body = dinosaur ? dinosaur : "No dinosaur found.";
});
const app = new Application();
const store = new CookieStore(Deno.env.get("SESSION_COOKIE_KEY") as string, {
sessionDataCookieName: "warbforums_sessionData",
cookieSetDeleteOptions: {
sameSite: "none",
secure: true,
},
});
const app = new Application<AppState>();
app.use(oakCors());
app.use(Session.initMiddleware(store) as any);
app.use(router.routes());
app.use(router.allowedMethods());
app.use(routeStaticFilesFrom([
@ -30,4 +110,8 @@ app.use(routeStaticFilesFrom([
`${Deno.cwd()}/public`,
]));
app.addEventListener("error", (evt) => {
console.log(evt.error);
});
await app.listen({ port: 8000 });

View File

@ -3,5 +3,11 @@
"@oak/oak": "jsr:@oak/oak@^17.0.0",
"@tajpouria/cors": "jsr:@tajpouria/cors@^1.2.1",
"react-router-dom": "npm:react-router-dom@^6.26.2"
},
"compilerOptions": {
"jsx": "react",
"jsxFactory": "React.createElement",
"jsxFragmentFactory": "React.Fragment",
"lib": ["dom", "esnext"]
}
}

3579
deno.lock

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,48 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Index from "./pages/index";
import Dinosaur from "./pages/Dinosaur";
import { createContext, useEffect, useState } from "react";
import React, { BrowserRouter, Route, Routes } from "react-router-dom";
import Index from "./pages/index.tsx";
import Dinosaur from "./pages/Dinosaur.tsx";
import "./App.css";
import AuthSuccess from "./pages/AuthSuccess.tsx";
import type { SteamUser } from "../api/main.ts";
import Profile from "./pages/Profile.tsx";
export const UserContext = createContext<{
user: SteamUser | undefined;
setUser: any;
}>({ user: undefined, setUser: () => {} });
function App() {
const [user, setUser] = useState<SteamUser>();
const value = { user, setUser };
useEffect(() => {
(async () => {
try {
const response = await fetch("/api/session", {
credentials: "include",
});
const res = await response.json();
if (res.user && res.user.steamid) {
setUser(res.user as SteamUser);
}
} catch (error) {
console.error("Error fetching user:", error);
}
})();
}, []);
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Index />} />
<Route path="/:selectedDinosaur" element={<Dinosaur />} />
</Routes>
<UserContext.Provider value={value}>
<h1>Welcome to the Dinosaur App</h1>
<Routes>
<Route path="/" element={<Index />} />
<Route path="/signedIn" element={<AuthSuccess />} />
<Route path="/users/:steamId" element={<Profile />} />
<Route path="/:selectedDinosaur" element={<Dinosaur />} />
</Routes>
</UserContext.Provider>
</BrowserRouter>
);
}

View File

@ -1,5 +1,6 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import App from "./App.tsx";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(

14
src/pages/AuthSuccess.tsx Normal file
View File

@ -0,0 +1,14 @@
import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
const AuthSuccess = () => {
const nav = useNavigate();
useEffect(() => {
nav("/");
}, [nav]);
return <div>Signing you in...</div>;
};
export default AuthSuccess;

View File

@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { Dino } from "../types";
import { Dino } from "../types.ts";
export default function Dinosaur() {
const { selectedDinosaur } = useParams();

53
src/pages/Profile.tsx Normal file
View File

@ -0,0 +1,53 @@
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import type { SteamUser } from "../../api/main.ts";
const Profile = () => {
const [user, setUser] = useState<SteamUser>();
useEffect(() => {
(async () => {
try {
const response = await fetch("/api/session", {
credentials: "include",
});
const res = await response.json();
if (res.user && res.user.steamid) {
setUser(res.user as SteamUser);
}
} catch (error) {
console.error("Error fetching user:", error);
}
})();
}, []);
const printUser = async () => {
console.log(user);
};
const handleLogin = async () => {
try {
const response = await fetch("http://localhost:8000/auth/login");
if (!response.ok) {
throw new Error("Failed to fetch authorization URL");
}
const { url } = await response.json();
globalThis.location.href = url;
} catch (error) {
console.error("Error during login:", error);
}
};
return (
<main>
<h1>Profile</h1>
<button onClick={user ? printUser : handleLogin}>
Sign in with Steam
</button>
{user && <p>Welcome, {user.personaname}!</p>}
</main>
);
};
export default Profile;

View File

@ -1,9 +1,12 @@
import { useEffect, useState } from "react";
import React, { useContext, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Dino } from "../types.ts";
import type { SteamUser } from "../../api/main.ts";
import { UserContext } from "../App.tsx";
export default function Index() {
const [dinosaurs, setDinosaurs] = useState<Dino[]>([]);
const { user } = useContext(UserContext);
useEffect(() => {
(async () => {
@ -13,10 +16,47 @@ export default function Index() {
})();
}, []);
/*useEffect(() => {
(async () => {
try {
const response = await fetch("/api/session", {
credentials: "include",
});
const res = await response.json();
if (res.user && res.user.steamid) {
setUser(res.user as SteamUser);
}
} catch (error) {
console.error("Error fetching user:", error);
}
})();
}, []);*/
const printUser = async () => {
console.log(user);
};
const handleLogin = async () => {
try {
const response = await fetch("http://localhost:8000/auth/login");
if (!response.ok) {
throw new Error("Failed to fetch authorization URL");
}
const { url } = await response.json();
globalThis.location.href = url;
} catch (error) {
console.error("Error during login:", error);
}
};
return (
<main>
<h1>Welcome to the Dinosaur app</h1>
<h1>Dinosaur Home</h1>
<p>Click on a dinosaur below to learn more.</p>
<button onClick={user ? printUser : handleLogin}>
Sign in with Steam
</button>
{user && <p>Welcome, {user.personaname}!</p>}
{dinosaurs.map((dinosaur: Dino) => {
return (
<Link

View File

@ -1,27 +0,0 @@
{
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src", "tsconfig.json"]
}

View File

@ -1,11 +0,0 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.node.json"
}
]
}

View File

@ -1,13 +0,0 @@
{
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true,
"noEmit": true
},
"include": ["vite.config.ts"]
}

View File

@ -10,6 +10,10 @@ export default defineConfig({
target: "http://localhost:8000",
changeOrigin: true,
},
"/auth": {
target: "http://localhost:8000",
changeOrigin: true,
},
},
},
});