feat(api): add auth middleware to protect game endpoints

- Add requireAuth middleware using Better Auth session validation
- Apply to all game routes (start, answer)
- Unauthenticated requests return 401
This commit is contained in:
lila 2026-04-12 13:38:32 +02:00
parent 91a3112d8b
commit a3685a9e68
13 changed files with 196 additions and 24 deletions

View file

@ -13,9 +13,11 @@
"@glossa/db": "workspace:*",
"@glossa/shared": "workspace:*",
"better-auth": "^1.6.2",
"cors": "^2.8.6",
"express": "^5.2.1"
},
"devDependencies": {
"@types/cors": "^2.8.19",
"@types/express": "^5.0.6",
"@types/supertest": "^7.2.0",
"supertest": "^7.2.2",

View file

@ -4,10 +4,12 @@ import { toNodeHandler } from "better-auth/node";
import { auth } from "./lib/auth.js";
import { apiRouter } from "./routes/apiRouter.js";
import { errorHandler } from "./middleware/errorHandler.js";
import cors from "cors";
export function createApp() {
const app: Express = express();
app.use(cors({ origin: "http://localhost:5173", credentials: true }));
app.all("/api/auth/*splat", toNodeHandler(auth));
app.use(express.json());
app.use("/api/v1", apiRouter);

View file

@ -1,9 +1,11 @@
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db } from "@glossa/db";
import * as schema from "@glossa/db/schema";
export const auth = betterAuth({
database: drizzleAdapter(db, { provider: "pg" }),
database: drizzleAdapter(db, { provider: "pg", schema }),
trustedOrigins: ["http://localhost:5173"],
socialProviders: {
google: {
clientId: process.env["GOOGLE_CLIENT_ID"] as string,

View file

@ -0,0 +1,20 @@
import type { Request, Response, NextFunction } from "express";
import { fromNodeHeaders } from "better-auth/node";
import { auth } from "../lib/auth.js";
export const requireAuth = async (
req: Request,
res: Response,
next: NextFunction,
) => {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});
if (!session) {
res.status(401).json({ success: false, error: "Unauthorized" });
return;
}
next();
};

View file

@ -1,8 +1,10 @@
import express from "express";
import type { Router } from "express";
import { createGame, submitAnswer } from "../controllers/gameController.js";
import { requireAuth } from "../middleware/authMiddleware.js";
export const gameRouter: Router = express.Router();
gameRouter.use(requireAuth);
gameRouter.post("/start", createGame);
gameRouter.post("/answer", submitAnswer);