-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
50 lines (44 loc) · 1.54 KB
/
Copy pathmiddleware.ts
File metadata and controls
50 lines (44 loc) · 1.54 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
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth(
function middleware(req) {
const token = req.nextauth.token;
const pathname = req.nextUrl.pathname;
// Check if accessing user-specific routes like /[userId]/dashboard
const userRouteMatch = pathname.match(
/^\/([^\/]+)\/(dashboard|profile|logs|onboard)/
);
if (userRouteMatch) {
const urlUserId = userRouteMatch[1];
const sessionUserId = token?.sub;
// If userId in URL doesn't match session user, redirect to their own dashboard
if (sessionUserId && urlUserId !== sessionUserId) {
return NextResponse.redirect(
new URL(`/${sessionUserId}/dashboard`, req.url)
);
}
}
return NextResponse.next();
},
{
callbacks: {
authorized: ({ token }) => !!token,
},
}
);
export const config = {
matcher: [
// Protect user-specific routes
"/:userId((?!api|_next|login|register|onboard|terms|privacy|favicon)[^/]+)/dashboard/:path*",
"/:userId((?!api|_next|login|register|onboard|terms|privacy|favicon)[^/]+)/profile/:path*",
"/:userId((?!api|_next|login|register|onboard|terms|privacy|favicon)[^/]+)/logs/:path*",
"/:userId((?!api|_next|login|register|onboard|terms|privacy|favicon)[^/]+)/onboard/:path*",
// Protect API routes (except auth)
"/api/((?!auth).*)",
// Keep legacy routes protected (redirect to new structure)
"/dashboard/:path*",
"/profile/:path*",
"/logs/:path*",
"/onboard/:path*",
],
};