-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
35 lines (27 loc) · 979 Bytes
/
middleware.ts
File metadata and controls
35 lines (27 loc) · 979 Bytes
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
/**
* middleware.ts
* Protects /dashboard/* routes — unauthenticated users are redirected to /auth/login.
*/
import { auth } from "@/lib/auth";
import { NextResponse } from "next/server";
export default auth((req) => {
const { pathname } = req.nextUrl;
// If the user is not authenticated and trying to access a protected route
if (!req.auth) {
const loginUrl = new URL("/auth/login", req.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
// Role-based route protection
const role = req.auth.user?.role;
if (pathname.startsWith("/dashboard/org") && role !== "organization") {
return NextResponse.redirect(new URL("/dashboard/donor", req.url));
}
if (pathname.startsWith("/dashboard/donor") && role !== "donor") {
return NextResponse.redirect(new URL("/dashboard/org", req.url));
}
return NextResponse.next();
});
export const config = {
matcher: ["/dashboard/:path*"],
};