-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
42 lines (35 loc) · 1.23 KB
/
middleware.ts
File metadata and controls
42 lines (35 loc) · 1.23 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
import { auth } from "@/auth";
import { NextResponse } from "next/server";
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const userRole = req.auth?.user?.role;
const isOnAdminPage = nextUrl.pathname.startsWith("/admin");
const isOnLoginPage = nextUrl.pathname === "/admin/login";
const isOnSetupPage = nextUrl.pathname === "/admin/setup";
// Allow access to login and setup pages
if (isOnLoginPage || isOnSetupPage) {
// If already logged in as admin, redirect to admin dashboard
if (isLoggedIn && userRole === "admin" && isOnLoginPage) {
return NextResponse.redirect(new URL("/admin", nextUrl));
}
return NextResponse.next();
}
// Protect admin routes
if (isOnAdminPage) {
if (!isLoggedIn) {
// Redirect to login with callback URL
const loginUrl = new URL("/admin/login", nextUrl);
loginUrl.searchParams.set("callbackUrl", nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
if (userRole !== "admin") {
// Not an admin - redirect to home or show error
return NextResponse.redirect(new URL("/", nextUrl));
}
}
return NextResponse.next();
});
export const config = {
matcher: ["/admin/:path*"],
};