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

@@ -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;