-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
49 lines (40 loc) · 1.53 KB
/
middleware.ts
File metadata and controls
49 lines (40 loc) · 1.53 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
import { NextResponse } from 'next/server';
import { auth } from '@/auth';
import { db } from '@/db';
import { appConfig, users } from '@/db/schema';
import { count } from 'drizzle-orm';
export default auth(async (req) => {
const isLoggedIn = !!req.auth;
const isOnLoginPage = req.nextUrl.pathname.startsWith('/login');
const isOnSetupPage = req.nextUrl.pathname.startsWith('/setup');
// Check if setup is needed by verifying users and config records
const [userCount, configCount] = await Promise.all([
db.select({ count: count() }).from(users),
db.select({ count: count() }).from(appConfig)
]);
const setupNeeded = userCount[0].count === 0 || configCount[0].count < 3;
// Allow access to setup page only if setup is needed
if (isOnSetupPage) {
if (!setupNeeded) {
return Response.redirect(new URL('/', req.nextUrl));
}
return NextResponse.next();
}
// Redirect to setup if needed and not on setup page
if (setupNeeded && !isOnSetupPage) {
return Response.redirect(new URL('/setup', req.nextUrl));
}
// Redirect to login if not authenticated and not on login page
if (!isLoggedIn && !isOnLoginPage) {
return Response.redirect(new URL('/login', req.nextUrl));
}
// Redirect to home if authenticated and on login page
if (isLoggedIn && isOnLoginPage) {
return Response.redirect(new URL('/', req.nextUrl));
}
return NextResponse.next();
});
// Optionally configure middleware matcher
export const config = {
matcher: ['/((?!api|_next/static|_next/image|images|favicon.ico).*)'],
};