Enable auth-service/api-gateway on production, build their images in CI
This commit is contained in:
+33
-2
@@ -1,5 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { jwtVerify } from "jose";
|
||||
import { SESSION_COOKIE } from "./app/api/auth/session";
|
||||
|
||||
/**
|
||||
* Rate limiting for the public API surface.
|
||||
@@ -96,7 +98,36 @@ function matchRules(pathname: string) {
|
||||
return RULES.find((entry) => pathname.startsWith(entry.prefix))?.rules;
|
||||
}
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
/** `/admin/**` (except the login page itself) requires a valid session
|
||||
* cookie carrying `role: "admin"`. Verified with the same `JWT_SECRET`
|
||||
* auth-service signs with — Edge middleware can't call out to auth-service
|
||||
* per request without adding real latency to every admin page load, and
|
||||
* `jose` (unlike `jsonwebtoken`) works in the Edge runtime this file runs
|
||||
* under, so local verification is both correct and the only option here. */
|
||||
async function guardAdmin(request: NextRequest): Promise<NextResponse | null> {
|
||||
const { pathname } = request.nextUrl;
|
||||
if (!pathname.startsWith("/admin") || pathname === "/admin/login") return null;
|
||||
|
||||
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
||||
const secret = process.env.JWT_SECRET;
|
||||
if (!token || !secret) {
|
||||
return NextResponse.redirect(new URL("/admin/login", request.url));
|
||||
}
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, new TextEncoder().encode(secret));
|
||||
if (payload.role !== "admin") {
|
||||
return NextResponse.redirect(new URL("/admin/login", request.url));
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return NextResponse.redirect(new URL("/admin/login", request.url));
|
||||
}
|
||||
}
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const adminRedirect = await guardAdmin(request);
|
||||
if (adminRedirect) return adminRedirect;
|
||||
|
||||
const rules = matchRules(request.nextUrl.pathname);
|
||||
if (!rules) return NextResponse.next();
|
||||
|
||||
@@ -146,5 +177,5 @@ export function middleware(request: NextRequest) {
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/api/:path*"],
|
||||
matcher: ["/api/:path*", "/admin/:path*"],
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user