change our current auth system for NextAuth.js (now Auth.js): This is th
This commit is contained in:
+17
-10
@@ -1,18 +1,25 @@
|
||||
|
||||
import {NextResponse} from 'next/server';
|
||||
import type {NextRequest} from 'next/server';
|
||||
import { auth } from '@/app/api/auth/[...nextauth]/route';
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const session = request.cookies.get('session');
|
||||
export async function middleware(request: NextRequest) {
|
||||
const session = await auth();
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
// Redirect to login if trying to access /admin without a session
|
||||
if (request.nextUrl.pathname.startsWith('/admin') && !session) {
|
||||
return NextResponse.redirect(new URL('/login', request.url));
|
||||
const isAuthPage = pathname === '/login';
|
||||
|
||||
if (isAuthPage) {
|
||||
if (session) {
|
||||
return NextResponse.redirect(new URL('/admin', request.url));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Redirect to admin if trying to access /login with a session
|
||||
if (request.nextUrl.pathname === '/login' && session) {
|
||||
return NextResponse.redirect(new URL('/admin', request.url));
|
||||
if (!session && pathname.startsWith('/admin')) {
|
||||
const signInUrl = new URL('/login', request.url);
|
||||
signInUrl.searchParams.set('callbackUrl', pathname);
|
||||
return NextResponse.redirect(signInUrl);
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
|
||||
Reference in New Issue
Block a user