Skip to content

Commit

Permalink
also support session auth
Browse files Browse the repository at this point in the history
  • Loading branch information
motatoes committed Nov 13, 2024
1 parent 201d344 commit cf93971
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions src/middleware/api.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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 });
};
}

0 comments on commit cf93971

Please sign in to comment.