54 lines
1.2 KiB
TypeScript
54 lines
1.2 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
import { jwtVerify } from "jose";
|
|
|
|
const SESSION_COOKIE = "moped_session";
|
|
|
|
const PUBLIC_PATHS = ["/login", "/kiosk"];
|
|
|
|
async function hasValidSession(request: NextRequest): Promise<boolean> {
|
|
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
|
|
|
if (!token) {
|
|
return false;
|
|
}
|
|
|
|
const secret = process.env.AUTH_SECRET;
|
|
|
|
if (!secret) {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
await jwtVerify(token, new TextEncoder().encode(secret));
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
|
|
if (
|
|
pathname.startsWith("/_next") ||
|
|
pathname.startsWith("/favicon") ||
|
|
pathname.startsWith("/api/auth")
|
|
) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
const isPublic = PUBLIC_PATHS.some((path) => pathname.startsWith(path));
|
|
const validSession = await hasValidSession(request);
|
|
|
|
if (!validSession && !isPublic) {
|
|
return NextResponse.redirect(new URL("/login", request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/((?!.*\\..*).*)"],
|
|
};
|