debug: lägg till withAuth-loggning + middleware matcher för /api
This commit is contained in:
@@ -27,7 +27,11 @@ export function withAuth(
|
|||||||
) {
|
) {
|
||||||
return auth(async function (request: any, context: any) {
|
return auth(async function (request: any, context: any) {
|
||||||
const session = request.auth;
|
const session = request.auth;
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.log('[withAuth] request.auth:', JSON.stringify(session));
|
||||||
if (!session?.accessToken) {
|
if (!session?.accessToken) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.warn('[withAuth] No accessToken — returning 401');
|
||||||
return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
|
return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
|
||||||
}
|
}
|
||||||
return handler(request, session, context);
|
return handler(request, session, context);
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { auth } from './auth';
|
||||||
|
|
||||||
|
export default auth((req) => {
|
||||||
|
const { pathname } = req.nextUrl;
|
||||||
|
|
||||||
|
// Alltid tillgängliga sidor
|
||||||
|
const publicPaths = ['/login', '/register'];
|
||||||
|
if (publicPaths.some((p) => pathname.startsWith(p))) {
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Om ej inloggad, omdirigera till /login
|
||||||
|
if (!req.auth) {
|
||||||
|
const loginUrl = new URL('/login', req.url);
|
||||||
|
loginUrl.searchParams.set('callbackUrl', pathname);
|
||||||
|
return NextResponse.redirect(loginUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Admin-sidor kräver admin-roll
|
||||||
|
if (pathname.startsWith('/admin')) {
|
||||||
|
const role = (req.auth.user as any)?.role;
|
||||||
|
if (role !== 'admin') {
|
||||||
|
return NextResponse.redirect(new URL('/', req.url));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
});
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
|
||||||
|
};
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ['/((?!_next/static|_next/image|favicon.ico|api/auth).*)'],
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user