From cf93971b5fd9a9b90ce802eeaa33ff727268fa62 Mon Sep 17 00:00:00 2001 From: motatoes Date: Wed, 13 Nov 2024 11:01:27 +0000 Subject: [PATCH] also support session auth --- src/middleware/api.ts | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/src/middleware/api.ts b/src/middleware/api.ts index ef85a994..2280123b 100644 --- a/src/middleware/api.ts +++ b/src/middleware/api.ts @@ -1,5 +1,6 @@ // middleware/withApiAuth.ts +import { auth } from '@/auth'; import { headers } from 'next/headers'; import { NextRequest, NextResponse } from 'next/server'; import { validateM2MToken } from './m2m'; @@ -9,17 +10,34 @@ export function withApiAuth( ) { return async function (req: NextRequest) { // Check for M2M Bearer token - const headersList = headers(); - const authHeader = headersList.get('authorization'); + try { + const headersList = headers(); + const authHeader = headersList.get('authorization'); - if (authHeader?.startsWith('Bearer ')) { - const token = authHeader.split(' ')[1]; - const payload = await validateM2MToken(token); - if (payload) { - // Valid M2M token - return handler(req, payload.email); + if (authHeader?.startsWith('Bearer ')) { + const token = authHeader.split(' ')[1]; + const payload = await validateM2MToken(token); + if (payload) { + // Valid M2M token + return handler(req, payload.email); + } } + + // this part is to check if there is a cookie session available + // example if request is made from browser api + const session = await auth(); + if (!session) { + return new NextResponse('Unauthorized', { status: 401 }); + } + + if (!session?.user?.email) { + throw new Error('could not retrieve email from session'); + } + + return handler(req, session.user?.email); + } catch (error) { + console.error('Auth error:', error); + return new NextResponse('Internal Server Error', { status: 500 }); } - return new Response('Unauthorized', { status: 401 }); }; }