Compare commits

..

No commits in common. "fe02a090d34cdf936eac919754fbfbdf83362ac2" and "8979ec0efc5a1dae8533558e5d7724317e9c330b" have entirely different histories.

15 changed files with 1619 additions and 2348 deletions

2
.gitignore vendored
View File

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

View File

@ -1,45 +1,39 @@
# Deno and React.js # React + TypeScript + Vite
## A dinosaur app built with React, Vite and TypeScript This template provides a minimal setup to get React working in Vite with HMR and
some ESLint rules.
This demo is a simple React app. It uses Vite as the local server, and is Currently, two official plugins are available:
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.
You can follow along with the tutorial on the - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md)
[Deno Docs](https://docs.deno.com/runtime/tutorials/how_to_with_npm/react/). 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
## Run the app ## Expanding the ESLint configuration
To run the app, you need to have [Deno](https://deno.land/) installed on your If you are developing a production application, we recommend updating the
machine. You can install Deno by running the following command, or following the configuration to enable type aware lint rules:
instructions in the [Deno docs](https://docs.deno.com/runtime/):
```bash - Configure the top-level `parserOptions` property like this:
curl -fsSL https://deno.land/install.sh | sh
```js
export default {
// other rules...
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
project: ["./tsconfig.json", "./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: __dirname,
},
};
``` ```
Once you have Deno installed, you can run the app with the following command: - Replace `plugin:@typescript-eslint/recommended` to
`plugin:@typescript-eslint/recommended-type-checked` or
```bash `plugin:@typescript-eslint/strict-type-checked`
deno task dev - Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
``` - Install
[eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and
## Build the app add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends`
list
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,80 +1,9 @@
/// <reference lib="deno.ns" /> import { Application, Router } from "@oak/oak";
import { oakCors } from "@tajpouria/cors";
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 data from "./data.json" with { type: "json" };
import routeStaticFilesFrom from "./util/routeStaticFilesFrom.ts"; import routeStaticFilesFrom from "./util/routeStaticFilesFrom.ts";
import SteamAuth from "https://deno.land/x/deno_steam_openid@0.0.1/mod.ts"; const router = new Router();
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) => { router.get("/api/dinosaurs", (context) => {
context.response.body = data; context.response.body = data;
@ -92,17 +21,8 @@ router.get("/api/dinosaurs/:dinosaur", (context) => {
context.response.body = dinosaur ? dinosaur : "No dinosaur found."; context.response.body = dinosaur ? dinosaur : "No dinosaur found.";
}); });
const store = new CookieStore(Deno.env.get("SESSION_COOKIE_KEY") as string, { const app = new Application();
sessionDataCookieName: "warbforums_sessionData",
cookieSetDeleteOptions: {
sameSite: "none",
secure: true,
},
});
const app = new Application<AppState>();
app.use(oakCors()); app.use(oakCors());
app.use(Session.initMiddleware(store) as any);
app.use(router.routes()); app.use(router.routes());
app.use(router.allowedMethods()); app.use(router.allowedMethods());
app.use(routeStaticFilesFrom([ app.use(routeStaticFilesFrom([
@ -110,8 +30,4 @@ app.use(routeStaticFilesFrom([
`${Deno.cwd()}/public`, `${Deno.cwd()}/public`,
])); ]));
app.addEventListener("error", (evt) => {
console.log(evt.error);
});
await app.listen({ port: 8000 }); await app.listen({ port: 8000 });

View File

@ -3,11 +3,5 @@
"@oak/oak": "jsr:@oak/oak@^17.0.0", "@oak/oak": "jsr:@oak/oak@^17.0.0",
"@tajpouria/cors": "jsr:@tajpouria/cors@^1.2.1", "@tajpouria/cors": "jsr:@tajpouria/cors@^1.2.1",
"react-router-dom": "npm:react-router-dom@^6.26.2" "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,48 +1,15 @@
import { createContext, useEffect, useState } from "react"; import { BrowserRouter, Route, Routes } from "react-router-dom";
import React, { BrowserRouter, Route, Routes } from "react-router-dom"; import Index from "./pages/index";
import Index from "./pages/index.tsx"; import Dinosaur from "./pages/Dinosaur";
import Dinosaur from "./pages/Dinosaur.tsx";
import "./App.css"; 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() { 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 ( return (
<BrowserRouter> <BrowserRouter>
<UserContext.Provider value={value}> <Routes>
<h1>Welcome to the Dinosaur App</h1> <Route path="/" element={<Index />} />
<Routes> <Route path="/:selectedDinosaur" element={<Dinosaur />} />
<Route path="/" element={<Index />} /> </Routes>
<Route path="/signedIn" element={<AuthSuccess />} />
<Route path="/users/:steamId" element={<Profile />} />
<Route path="/:selectedDinosaur" element={<Dinosaur />} />
</Routes>
</UserContext.Provider>
</BrowserRouter> </BrowserRouter>
); );
} }

View File

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

View File

@ -1,14 +0,0 @@
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 React, { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom"; import { Link, useParams } from "react-router-dom";
import { Dino } from "../types.ts"; import { Dino } from "../types";
export default function Dinosaur() { export default function Dinosaur() {
const { selectedDinosaur } = useParams(); const { selectedDinosaur } = useParams();

View File

@ -1,53 +0,0 @@
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,12 +1,9 @@
import React, { useContext, useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { Dino } from "../types.ts"; import { Dino } from "../types.ts";
import type { SteamUser } from "../../api/main.ts";
import { UserContext } from "../App.tsx";
export default function Index() { export default function Index() {
const [dinosaurs, setDinosaurs] = useState<Dino[]>([]); const [dinosaurs, setDinosaurs] = useState<Dino[]>([]);
const { user } = useContext(UserContext);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
@ -16,47 +13,10 @@ 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 ( return (
<main> <main>
<h1>Dinosaur Home</h1> <h1>Welcome to the Dinosaur app</h1>
<p>Click on a dinosaur below to learn more.</p> <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) => { {dinosaurs.map((dinosaur: Dino) => {
return ( return (
<Link <Link

27
tsconfig.app.json Normal file
View File

@ -0,0 +1,27 @@
{
"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"]
}

11
tsconfig.json Normal file
View File

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

13
tsconfig.node.json Normal file
View File

@ -0,0 +1,13 @@
{
"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,10 +10,6 @@ export default defineConfig({
target: "http://localhost:8000", target: "http://localhost:8000",
changeOrigin: true, changeOrigin: true,
}, },
"/auth": {
target: "http://localhost:8000",
changeOrigin: true,
},
}, },
}, },
}); });