From b92c8fab4bc455a4441b4c08568b09c188b6b8f1 Mon Sep 17 00:00:00 2001 From: multipleof4 Date: Sun, 15 Mar 2026 14:22:24 -0700 Subject: [PATCH] Feat: Add middleware to protect dashboard and API routes --- middleware.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 middleware.js diff --git a/middleware.js b/middleware.js new file mode 100644 index 0000000..1e6e98b --- /dev/null +++ b/middleware.js @@ -0,0 +1,29 @@ +import { NextResponse } from 'next/server'; +import { verifySession } from './lib/auth'; + +// Define which paths should trigger this middleware +export const config = { + matcher: [ + '/dashboard/:path*', + '/api/state', + '/api/trades' + ], +}; + +export async function middleware(req) { + const token = req.cookies.get('kalbot_session')?.value; + const isValid = await verifySession(token); + + if (!isValid) { + // If they are trying to hit an API endpoint without a session, return 401 + if (req.nextUrl.pathname.startsWith('/api/')) { + return NextResponse.json({ error: 'Unauthorized. Nice try!' }, { status: 401 }); + } + + // Otherwise, boot them back to the login page + return NextResponse.redirect(new URL('/', req.url)); + } + + // Session is valid, allow the request to proceed + return NextResponse.next(); +}