/ opencodehub / src / middleware.ts
swadhinbiswas Fix listFiles logic, add 2FA endpoints, add repositories page, improve settings · 12/11/2025
b75deaa
87 lines · 2.4 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { getDatabase, schema } from "@/db";
import { verifyToken } from "@/lib/auth";
import { initTracing } from "@/lib/tracing";
import { defineMiddleware } from "astro:middleware";
import { eq } from "drizzle-orm";

// Initialize tracing
initTracing();

export const onRequest = defineMiddleware(async (context, next) => {
  const token = context.cookies.get("och_session")?.value;

  if (token) {
    try {
      const payload = await verifyToken(token);

      if (payload && payload.userId) {
        const db = getDatabase();

        // Verify session in database
        // If sessionId is present in payload, use it. Otherwise fall back to token check (legacy/fallback)
        const session = payload.sessionId
          ? await db.query.sessions.findFirst({
            where: eq(schema.sessions.id, payload.sessionId),
          })
          : await db.query.sessions.findFirst({
            where: eq(schema.sessions.token, token),
          });

        if (session && new Date(session.expiresAt) > new Date()) {
          // Fetch user
          const user = await db.query.users.findFirst({
            where: eq(schema.users.id, payload.userId),
          });

          if (user) {
            context.locals.user = user;
            context.locals.session = session;
          }
        }
      }
    } catch (e) {
      // Invalid token or session
      context.cookies.delete("och_session", { path: "/" });
    }
  }

  // Protected routes logic
  const protectedRoutes = ["/dashboard", "/settings", "/new"];
  const isProtectedRoute = protectedRoutes.some((route) =>
    context.url.pathname.startsWith(route)
  );

  if (isProtectedRoute && !context.locals.user) {
    return context.redirect("/login");
  }

  /*
  // 2FA Enforcement for Admins
  if (context.locals.user?.isAdmin && !context.locals.user.twoFactorEnabled) {
    const allowedPaths = [
      "/settings/security",
      "/api/auth/2fa",
      "/api/auth/logout",
      "/_astro",
      "/favicon.ico",
    ];

    const isAllowed = allowedPaths.some((path) =>
      context.url.pathname.startsWith(path)
    );

    if (!isAllowed) {
      return context.redirect("/settings/security");
    }
  }
  */

  // Redirect logged-in users away from auth pages
  const authRoutes = ["/login", "/register"];
  if (authRoutes.includes(context.url.pathname) && context.locals.user) {
    return context.redirect("/dashboard");
  }

  return next();
});