feat(lst): added in basic authentication

This commit is contained in:
2025-02-17 20:01:04 -06:00
parent ca27264bb0
commit 5f7a3dd182
25 changed files with 810 additions and 154 deletions

View File

@@ -13,6 +13,7 @@
"@antfu/ni": "^23.3.1",
"@radix-ui/react-slot": "^1.1.2",
"@tailwindcss/vite": "^4.0.6",
"@tanstack/react-query": "^5.66.5",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.475.0",
@@ -21,7 +22,8 @@
"shadcn": "^2.4.0-canary.6",
"tailwind-merge": "^3.0.1",
"tailwindcss": "^4.0.6",
"tailwindcss-animate": "^1.0.7"
"tailwindcss-animate": "^1.0.7",
"zustand": "^5.0.3"
},
"devDependencies": {
"@eslint/js": "^9.19.0",

View File

@@ -1,13 +1,24 @@
import LoginForm from "./components/LoginForm";
import {useSession} from "./lib/hooks/useSession";
import "./styles.css";
import { funnyFunction } from "@shared/lib";
function App() {
funnyFunction();
return (
<>
<p>lstv2</p>
</>
);
const {session, status} = useSession();
if (!session || status === "error") {
return (
<p>
no session please login <LoginForm />
</p>
);
}
return (
<>
<p>Logged in user: {session.user.username}</p>
<p>Status: {JSON.stringify(status)}</p>
</>
);
}
export default App;

View File

@@ -0,0 +1,72 @@
import {useState} from "react";
import {useSessionStore} from "../lib/store/sessionStore";
import {useQueryClient} from "@tanstack/react-query";
const LoginForm = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const {setSession} = useSessionStore();
const queryClient = useQueryClient();
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
console.log("Form data", {username, password});
try {
const response = await fetch("/api/auth/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({username, password}),
});
console.log("Response", response);
// if (!response.ok) {
// throw new Error("Invalid credentials");
// }
const data = await response.json();
console.log("Response", data);
setSession(data.user, data.token);
// Refetch the session data to reflect the logged-in state
queryClient.invalidateQueries(["session"]);
setUsername("");
setPassword("");
} catch (err) {
setError("Invalid credentials");
}
};
return (
<form onSubmit={handleLogin}>
<div>
<label htmlFor="username">Username</label>
<input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
{error && <p>{error}</p>}
<button type="submit">Login</button>
</form>
);
};
export default LoginForm;

View File

@@ -0,0 +1,7 @@
import {QueryClient, QueryClientProvider} from "@tanstack/react-query";
const queryClient = new QueryClient();
export const SessionProvider = ({children}: {children: React.ReactNode}) => {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
};

View File

@@ -0,0 +1,35 @@
import {useQuery} from "@tanstack/react-query";
import {useSessionStore} from "../store/sessionStore";
import {useEffect} from "react";
const fetchSession = async () => {
const res = await fetch("/api/auth/session", {credentials: "include"});
if (!res.ok) {
throw new Error("Session not found");
}
return res.json();
};
export const useSession = () => {
const {setSession, clearSession} = useSessionStore();
const {data, status, error} = useQuery({
queryKey: ["session"],
queryFn: fetchSession,
staleTime: 5 * 60 * 1000, // 5 mins
gcTime: 10 * 60 * 1000, // 10 mins
refetchOnWindowFocus: true,
});
useEffect(() => {
if (data) {
setSession(data.user, data.token);
}
if (error) {
clearSession();
}
}, [data, error]);
return {session: data, status, error};
};

View File

@@ -0,0 +1,20 @@
import {create} from "zustand";
type User = {
id: number;
username: string;
};
type SessionState = {
user: User | null;
token: string | null;
setSession: (user: SessionState["user"], token: string) => void;
clearSession: () => void;
};
export const useSessionStore = create<SessionState>((set) => ({
user: null,
token: null,
setSession: (user, token) => set({user, token}),
clearSession: () => set({user: null}),
}));

View File

@@ -1,10 +1,13 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import {StrictMode} from "react";
import {createRoot} from "react-dom/client";
import "./styles.css";
import App from "./App.tsx";
import {SessionProvider} from "./components/providers/Providers.tsx";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
<StrictMode>
<SessionProvider>
<App />
</SessionProvider>
</StrictMode>
);

View File

@@ -1,23 +1,23 @@
import { defineConfig } from "vite";
import {defineConfig} from "vite";
import react from "@vitejs/plugin-react-swc";
import tailwindcss from "@tailwindcss/vite";
import path from "path";
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
build: {
outDir: path.resolve(__dirname, "../../dist/frontend/dist"),
emptyOutDir: true,
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
plugins: [react(), tailwindcss()],
// build: {
// outDir: path.resolve(__dirname, "../../dist/frontend/dist"),
// emptyOutDir: true,
// },
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
},
server: {
proxy: {
"/api": { target: "http://localhost:4000", changeOrigin: true },
server: {
proxy: {
"/api": {target: "http://localhost:4000", changeOrigin: true},
},
},
},
});

View File

@@ -1,14 +1,14 @@
import app from "./src/app";
const port = process.env.SERVER_PORT || 4000;
Bun.serve({
port,
fetch: app.fetch,
hostname: "0.0.0.0",
port,
fetch: app.fetch,
hostname: "0.0.0.0",
});
// await Bun.build({
// entrypoints: ["./index.js"],
// outdir: "../../dist/server",
// });
await Bun.build({
entrypoints: ["./index.js"],
outdir: "../../dist/server",
});
console.log(`server is running on port ${port}`);

View File

@@ -1,13 +1,13 @@
{
"name": "lstv2-server",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"dev": "bun --watch index.ts",
"build": "bun build ./index.ts"
},
"devDependencies": {
"typescript": "^5.7.3"
}
"name": "lstv2-server",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"dev": "bun --watch ./index.ts",
"build": "bun build ./index.ts"
},
"devDependencies": {
"typescript": "^5.7.3"
}
}

View File

@@ -1,60 +1,49 @@
import { Hono } from "hono";
import { serveStatic } from "hono/bun";
import { logger } from "hono/logger";
import { ocmeService } from "./services/ocmeServer";
import { AuthConfig } from "@auth/core/types";
import { authHandler, initAuthConfig, verifyAuth } from "@hono/auth-js";
import Credentials from "@auth/core/providers/credentials";
import { authConfig } from "./auth/auth";
import {Hono} from "hono";
import {serveStatic} from "hono/bun";
import {logger} from "hono/logger";
import {ocmeService} from "./services/ocmeServer";
import {authMiddleware} from "lst-auth";
import {cors} from "hono/cors";
//import { expensesRoute } from "./routes/expenses";
import login from "./route/auth/login";
import session from "./route/auth/session";
const app = new Hono();
app.use("*", logger());
app.use(
"*",
cors({
origin: "http://localhost:5173",
allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"],
allowMethods: ["POST", "GET", "OPTIONS"],
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
maxAge: 600,
credentials: true,
})
);
// as we dont want to change ocme again well use a proxy to this
app.all("/ocme/*", async (c) => {
return ocmeService(c);
return ocmeService(c);
});
app.basePath("/api/auth").route("/login", login).route("/session", session);
//auth stuff
app.use("*", initAuthConfig(authConfig));
app.use("/api/auth/*", async (c, next) => {
const response = await authHandler()(c, next);
if (c.req.path === "/api/auth/callback/credentials") {
const setCookieHeader = response.headers.get("Set-Cookie");
if (setCookieHeader) {
const tokenMatch = setCookieHeader.match(/authjs\.session-token=([^;]+)/);
const jwt = tokenMatch ? tokenMatch[1] : null;
if (jwt) {
console.log("Extracted JWT:", jwt);
return c.json({ token: jwt });
}
}
}
return response;
});
app.get("/api/protected", verifyAuth(), (c) => {
const auth = c.get("authUser");
return c.json(auth);
app.get("/api/protected", authMiddleware, (c) => {
return c.json({success: true, message: "is authenticated"});
});
app.get("/api/test", (c) => {
const auth = c.get("authUser");
return c.json({ success: true, message: "hello from bun" });
return c.json({success: true, message: "hello from bun"});
});
// const authRoute = app.basePath("/api/auth").route("*", )
//const apiRoute = app.basePath("/api").route("/expenses", expensesRoute);
app.get("*", serveStatic({ root: "../frontend/dist" }));
app.get("*", serveStatic({ path: "../frontend/dist/index.html" }));
app.get("*", serveStatic({root: "../frontend/dist"}));
app.get("*", serveStatic({path: "../frontend/dist/index.html"}));
export default app;

View File

@@ -0,0 +1,28 @@
import {Hono} from "hono";
import {login} from "lst-auth";
const router = new Hono().post("/", async (c) => {
let body = {username: "", password: "", error: ""};
try {
body = await c.req.json();
} catch (error) {
return c.json({success: false, message: "Username and password required"}, 400);
}
if (!body?.username || !body?.password) {
return c.json({message: "Username and password required"}, 400);
}
try {
const {token, user} = login(body?.username, body?.password);
// Set the JWT as an HTTP-only cookie
c.header("Set-Cookie", `auth_token=${token}; HttpOnly; Secure; Path=/; SameSite=None; Max-Age=3600`);
return c.json({message: "Login successful", user});
} catch (err) {
// console.log(err);
return c.json({message: err}, 401);
}
});
export default router;

View File

@@ -0,0 +1,38 @@
import {Hono} from "hono";
import {verify} from "hono/jwt";
const app = new Hono();
const JWT_SECRET = "your-secret-key";
app.get("/", async (c) => {
const authHeader = c.req.header("Authorization");
const cookies = c.req.header("cookie");
if (authHeader?.includes("Basic")) {
//
return c.json({message: "You are a Basic user! Please login to get a token"}, 401);
}
if (!authHeader && !cookies) {
return c.json({error: "Unauthorized"}, 401);
}
// if (!cookies || !cookies.startsWith("Bearer ")) {
// return c.json({error: "Unauthorized"}, 401);
// }
// if (!authHeader || !authHeader.startsWith("Bearer ")) {
// return c.json({error: "Unauthorized"}, 401);
// }
const token = cookies?.split("auth_token=")[1].split(";")[0] || authHeader?.split("Bearer ")[1] || "";
try {
const payload = await verify(token, JWT_SECRET);
return c.json({user: {id: payload.userId, username: payload.username}, token});
} catch (err) {
return c.json({error: "Invalid or expired token"}, 401);
}
});
export default app;