Separate middleware routing from auth

This commit is contained in:
Sam Becker 2023-09-08 13:32:49 -05:00
parent 2061720994
commit b2b03aeae7
2 changed files with 17 additions and 9 deletions

View File

@ -1,7 +1,6 @@
import { isRouteProtected } from '@/site/routes';
import NextAuth, { User, type DefaultSession } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { NextResponse } from 'next/server';
declare module 'next-auth' {
interface Session {
@ -37,18 +36,12 @@ export const {
],
callbacks: {
authorized({ auth, request }) {
const url = new URL(request.url);
const { pathname } = url;
const { pathname } = request.nextUrl;
const isUrlProtected = isRouteProtected(pathname);
const isUserLoggedIn = !!auth?.user;
const isRequestAuthorized = !isUrlProtected || isUserLoggedIn;
if (pathname === '/admin') {
url.pathname = '/admin/photos';
return NextResponse.redirect(url);
}
return isRequestAuthorized;
},
},

View File

@ -1,4 +1,19 @@
export { auth as middleware } from './auth';
import { auth } from './auth';
import { NextRequest, NextResponse } from 'next/server';
import { NextApiRequest, NextApiResponse } from 'next';
export default function middleware(req: NextRequest, res:NextResponse) {
const pathname = req.nextUrl.pathname;
if (pathname === '/admin') {
return NextResponse.redirect(new URL('/admin/photos', req.url));
}
return auth(
req as unknown as NextApiRequest,
res as unknown as NextApiResponse,
);
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],