59 lines
1.8 KiB
TypeScript
59 lines
1.8 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
|
|
/**
|
|
* Middleware برای احراز هویت و حفاظت routes
|
|
*
|
|
* این middleware:
|
|
* 1. بررسی توکن از HTTP-only cookie
|
|
* 2. کاربران بدون توکن را به /login تغییر مسیر میدهد
|
|
* 3. کاربران لاگینشده که به /login میروند را به / تغییر مسیر میدهد
|
|
*/
|
|
|
|
const publicRoutes = ["/login", "/register", "/"];
|
|
const protectedRoutes = ["/(protected)", "/dashboard", "/profile"];
|
|
|
|
export function middleware(request: NextRequest) {
|
|
const pathname = request.nextUrl.pathname;
|
|
const token = request.cookies.get("token")?.value;
|
|
|
|
// بررسی اینکه آیا route protected است
|
|
const isProtectedRoute = protectedRoutes.some(
|
|
(route) => pathname.startsWith(route) || pathname === route
|
|
);
|
|
|
|
// بررسی اینکه آیا route public است
|
|
const isPublicRoute = publicRoutes.some(
|
|
(route) => pathname.startsWith(route) || pathname === route
|
|
);
|
|
|
|
// اگر کاربر토کن ندارد و سعی میکند به protected route برود
|
|
if (isProtectedRoute && !token) {
|
|
return NextResponse.redirect(new URL("/login", request.url));
|
|
}
|
|
|
|
// اگر کاربر توکن دارد و سعی میکند به auth routes برود
|
|
if (token && (pathname === "/login" || pathname === "/register")) {
|
|
return NextResponse.redirect(new URL("/", request.url));
|
|
}
|
|
|
|
// ادامه رفتن درخواست
|
|
return NextResponse.next();
|
|
}
|
|
|
|
/**
|
|
* Matcher برای مسیرهایی که middleware برای آنها اجرا شود
|
|
*/
|
|
export const config = {
|
|
matcher: [
|
|
// Protected routes
|
|
"/(protected)/:path*",
|
|
"/dashboard/:path*",
|
|
"/profile/:path*",
|
|
|
|
// Auth routes
|
|
"/login",
|
|
"/register",
|
|
],
|
|
};
|