import { getToken } from "next-auth/jwt"; import { NextResponse } from "next/server"; export async function middleware(req) { const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET }); const nowInSeconds = Math.floor(Date.now() / 1000); const isTokenValid = token && token.exp && token.exp > nowInSeconds; const isAuth = !!token && isTokenValid; const currentPath = req.nextUrl.pathname; const isLoginPage = ["/", "/login"].includes(currentPath); // ❌ Tidak login atau token kadaluarsa → redirect ke /login if (!isAuth && !isLoginPage) { return NextResponse.redirect(new URL("/login", req.url)); } // ✅ Sudah login tapi buka / atau /login → redirect ke /beranda if (isAuth && isLoginPage) { return NextResponse.redirect(new URL("/beranda", req.url)); } // 🔁 Sudah check-in → redirect dari /check-in if (currentPath === "/check-in") { const hasCheckedIn = req.cookies.get("hasCheckedIn")?.value; if (hasCheckedIn === "true") { return NextResponse.redirect(new URL("/", req.url)); } } // 🔁 Sudah check-out → redirect dari /check-out if (currentPath === "/check-out") { const hasCheckedOut = req.cookies.get("hasCheckedOut")?.value; if (hasCheckedOut === "true") { return NextResponse.redirect(new URL("/", req.url)); } } if (currentPath === "/check-out") { const hasAbsen = req.cookies.get("hasAbsen")?.value; if (hasAbsen === "true") { return NextResponse.redirect(new URL("/", req.url)); } } return NextResponse.next(); } export const config = { matcher: [ "/", "/login", "/beranda/:path*", "/profile/:path*", "/attendance/:path*", "/check-in", "/check-out", ], };