summaryrefslogtreecommitdiff
path: root/src/lib/server/cookie.ts
blob: 32894b9114c0afaf620094b9f9d6bd9ab85b9e85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import cookie from "cookie";
import db from "../db";
import type { Middleware } from "waku/config";

const cookieMiddleware: Middleware = () => {
  return async (ctx, next) => {
    // Parse incoming cookies
    const cookies = cookie.parse(ctx.req.headers.cookie || "");
    const coki = cookies.sorlang;
    
    // If cookie exists, fetch user data and set in context
    if (coki) {
      const userRow = db.fetchCookie(coki);
      if (userRow) {
        ctx.data.user = { id: userRow.id, name: userRow.name };
        console.log("User authenticated:", userRow.name);
      }
    }
    
    // Uncomment to enable redirection for unauthenticated users
    /*
    if (!ctx.data.user && ctx.req.url.pathname !== "/login") {
      ctx.res.status = 302;
      ctx.res.headers = {
        Location: "/login",
      };
      return;
    }
    */
    
    await next();
    
    // Cookie setting is now handled by setCookieMiddleware
  };
};

export default cookieMiddleware;