import { withAuth } from "next-auth/middleware" import { NextResponse } from "next/server" const middleware = withAuth( function middleware(req) { const token = req.nextauth.token const isAuth = !!token const isLoginPage = req.nextUrl.pathname.startsWith("/auth/login") const isAdminPage = req.nextUrl.pathname.startsWith("/admin") // 1. If already logged in and trying to access login page, redirect to Dashboard or Home if (isLoginPage) { if (isAuth) { if (token?.is_admin) { // If admin is logging in, they might want to go to dashboard. // But if they just hit /auth/login, maybe just home is fine? // Let's keep it simple: if query param callbackUrl is present, NextAuth handles it. // If not, we can redirect to /admin if they are admin, or / if not. // actually, let's just let them go to home for now to avoid loops, unless they specifically came from admin. // The user request said "admin sayfasina gitmek istersek gidecegin login olani yonlendimeyecegiz admin e" // This is a bit ambiguous. "If we want to go to admin page, the login one we go to shouldn't redirect to admin"? // Wait, "admin in altindaki login de kalkmali bole bişi olmamamli" -> remove /admin/login. Done. // "admin sayfasina gitmek istersek gidecegin login olani yonlendimeyecegiz admin e" -> // "If we want to go to admin page [and are not logged in], [we go to login], [but] the login one shouldn't redirect [everyone] to admin". // So /auth/login shouldn't default redirect to /admin. return NextResponse.redirect(new URL("/admin", req.url)) } return NextResponse.redirect(new URL("/", req.url)) } return null } // 2. Admin Route Protection if (isAdminPage) { // Not authenticated handled by `authorized` callback below implicitly, // but we can double check here. // If authenticated but NOT admin -> 403 or redirect if (isAuth && !token?.is_admin) { // You can rewrite to a 403 page or redirect to home/login // rewriting to /403 implies you have a page.tsx there. // For now, let's redirect to home with an error parameter or just home. return NextResponse.redirect(new URL("/", req.url)) } } // Allow other authenticated access if needed }, { callbacks: { authorized: ({ req, token }) => { const pathname = req.nextUrl.pathname; // Public Routes (Auth pages are already handled by next-auth logic usually, but let's be explicit) if (pathname.startsWith("/auth/")) { return true } // Admin Routes -> Require Token if (pathname.startsWith("/admin")) { return !!token // Must be logged in (is_admin check is done in middleware function) } // Default: Allow access (e.g. public landing pages) // If you want to protect everything else, change to `return !!token` return true }, }, pages: { signIn: "/auth/login", } } ) export const proxy = middleware export const config = { // Protect admin routes and ensure auth routes pass through middleware for redirection logic matcher: ["/admin/:path*", "/auth/login"], }