| 42 | } |
| 43 | |
| 44 | function handleUnauthenticated(request: NextRequest, pathname: string): NextResponse { |
| 45 | if (pathname.startsWith("/api/")) { |
| 46 | middlewareLogger.warn("Unauthorized API access", { pathname }) |
| 47 | |
| 48 | return NextResponse.json( |
| 49 | { |
| 50 | error: "Unauthorized", |
| 51 | message: "Authentication required", |
| 52 | }, |
| 53 | { status: 401 }, |
| 54 | ) |
| 55 | } else { |
| 56 | const redirectUrl = encodeURIComponent(pathname) |
| 57 | middlewareLogger.warn("Redirecting unauthenticated user to login", { pathname }) |
| 58 | const loginUrl = new URL(`/login?from=${redirectUrl}`, request.url) |
| 59 | |
| 60 | return NextResponse.redirect(loginUrl) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | function getPathnameWithoutLocale(pathname: string): string { |
| 65 | // 移除语言前缀 (如 /zh, /en) |