-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
70 lines (61 loc) · 2.57 KB
/
middleware.ts
File metadata and controls
70 lines (61 loc) · 2.57 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import {
verifyUserToken,
verifyAdminToken,
USER_SESSION_COOKIE,
ADMIN_SESSION_COOKIE,
} from './lib/session';
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const userToken = request.cookies.get(USER_SESSION_COOKIE)?.value;
const adminToken = request.cookies.get(ADMIN_SESSION_COOKIE)?.value;
// Verify each session independently — null if missing or invalid
const userSession = userToken ? await verifyUserToken(userToken) : null;
const adminSession = adminToken ? await verifyAdminToken(adminToken) : null;
const isUserRoute = pathname.startsWith('/dashboard') || pathname.startsWith('/create');
const isAdminRoute = pathname.startsWith('/admin') && pathname !== '/admin-login';
const isUserAuthPage = pathname === '/login' || pathname === '/signup';
const isAdminLoginPage = pathname === '/admin-login';
// ── USER-AUTHENTICATED rules ─────────────────────────────────────────────
if (userSession) {
// Redirect away from user login/signup pages
if (isUserAuthPage) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
// User must not access /admin/*
if (isAdminRoute) {
return NextResponse.redirect(new URL('/admin-login', request.url));
}
// /admin-login is fine to visit (separate system — no redirect)
}
// ── ADMIN-AUTHENTICATED rules ────────────────────────────────────────────
if (adminSession) {
// Redirect away from /admin-login
if (isAdminLoginPage) {
return NextResponse.redirect(new URL('/admin', request.url));
}
// Admin must not access user dashboard/create
if (isUserRoute) {
return NextResponse.redirect(new URL('/admin', request.url));
}
}
// ── UNAUTHENTICATED rules ────────────────────────────────────────────────
if (!userSession && isUserRoute) {
return NextResponse.redirect(new URL('/login', request.url));
}
if (!adminSession && isAdminRoute) {
return NextResponse.redirect(new URL('/admin-login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
'/dashboard/:path*',
'/create/:path*',
'/admin/:path*',
'/admin-login',
'/login',
'/signup',
],
};