-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
72 lines (63 loc) · 2.17 KB
/
middleware.ts
File metadata and controls
72 lines (63 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { refreshSessionCookie, verifyJwtToken } from "@/lib/auth/auth";
// export { auth as middleware } from "@/auth";
export async function middleware(request: NextRequest) {
// Paths that don't require authentication
const publicPaths = [
"/",
"/auth/login",
"/auth/register",
"/auth/forgot-password",
"/api/auth/login",
"/api/auth/register",
];
const isPublicPath = publicPaths.some((path) =>
request.nextUrl.pathname === path ||
request.nextUrl.pathname.startsWith("/api/auth/") ||
request.nextUrl.pathname.startsWith("/_next/")
);
// Check if path is the static files
if (
request.nextUrl.pathname.includes("/_next/") ||
request.nextUrl.pathname.includes("/api/auth/") ||
request.nextUrl.pathname.includes("/favicon.ico") ||
request.nextUrl.pathname.includes(".svg") ||
request.nextUrl.pathname.includes(".png") ||
request.nextUrl.pathname.includes(".jpg") ||
request.nextUrl.pathname.includes(".jpeg") ||
request.nextUrl.pathname.includes(".gif")
) {
return NextResponse.next();
}
// Get session cookie
const sessionCookie = request.cookies.get("session");
// Check if user is authenticated
const isAuthenticated = sessionCookie ?
!!(await verifyJwtToken(sessionCookie.value)) :
false;
// If the path requires authentication and user is not authenticated
if (!isPublicPath && !isAuthenticated) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
// If the path doesn't require authentication and user is authenticated
if (
(request.nextUrl.pathname === "/auth/login" ||
request.nextUrl.pathname === "/auth/register") &&
isAuthenticated
) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
// Refresh session cookie if needed
return await refreshSessionCookie(request);
}
export const config = {
matcher: [
// Match all paths except for:
// - API routes that don't start with /api/auth
// - Static files
// - favicon.ico
"/((?!api/(?!auth)|_next/static|_next/image|favicon.ico).*)",
],
};