UNPKG

datacops-cms

Version:

A modern, extensible CMS built with Next.js and Prisma.

74 lines (64 loc) 2.14 kB
import { getToken } from 'next-auth/jwt' import type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' function isAppInstalled() { return process.env.IS_INSTALLED === 'true' } export async function middleware(request: NextRequest) { const isInstalled = isAppInstalled() const { pathname } = request.nextUrl // 1. Before install: only allow /install and static if (!isInstalled) { if ( pathname.startsWith('/install') || pathname.startsWith('/_next') || pathname.startsWith('/favicon.ico') ) { return NextResponse.next() } return NextResponse.redirect(new URL('/install', request.url)) } // 2. If authenticated and visiting /login, redirect home if (pathname.startsWith('/login')) { const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET }) if (token) { // User is already logged in, redirect to home return NextResponse.redirect(new URL('/', request.url)) } return NextResponse.next() } // 3. Allow public routes (api/auth, install, static) if ( pathname.startsWith('/api/auth') || pathname.startsWith('/api/content') || pathname.startsWith('/install') || pathname.startsWith('/_next') || pathname.startsWith('/favicon.ico') ) { return NextResponse.next() } // 4. Require authentication for all other routes const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET }) if (!token) { const shouldSkipCallback = pathname === '/' || pathname === '/login' || pathname === '/install' if (shouldSkipCallback) { return NextResponse.redirect(new URL('/login', request.url)) } // Otherwise, add callbackUrl const loginUrl = new URL('/login', request.url) loginUrl.searchParams.set('callbackUrl', pathname) return NextResponse.redirect(loginUrl) } // 5. User authenticated, allow access return NextResponse.next() } export const config = { matcher: [ '/((?!_next/static|_next/image|favicon.ico).*)', ], }