feat: implement cors for all the routes

This commit is contained in:
Ephraim Atta-Duncan
2024-10-23 17:42:58 +00:00
parent 68c8f098b6
commit 979f898880
2 changed files with 44 additions and 12 deletions

View File

@@ -6,20 +6,38 @@ type RouteHandler<T = Record<string, string | string[]>> = (
ctx: { params: T },
) => Promise<Response> | Response;
const ALLOWED_ORIGINS = new Set(['documenso.com']);
const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};
function isAllowedOrigin(req: NextRequest): boolean {
const referer = req.headers.get('referer');
const host = req.headers.get('host');
if (referer && host) {
const refererUrl = new URL(referer);
return refererUrl.host === host;
}
if (host?.includes('localhost')) {
return true;
}
return false;
if (!referer || !host) {
return false;
}
try {
const refererUrl = new URL(referer);
const hostUrl = new URL(`http://${host}`);
const isRefererAllowed = ALLOWED_ORIGINS.has(refererUrl.host);
const isHostAllowed = ALLOWED_ORIGINS.has(hostUrl.host);
return isRefererAllowed || isHostAllowed;
} catch (error) {
console.error('Error parsing URLs:', error);
return false;
}
}
export function requestHandler<T = Record<string, string | string[]>>(
@@ -28,16 +46,31 @@ export function requestHandler<T = Record<string, string | string[]>>(
return async (req: NextRequest, ctx: { params: T }) => {
try {
if (!isAllowedOrigin(req)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
return NextResponse.json(
{ error: 'Forbidden' },
{
status: 403,
headers: CORS_HEADERS,
},
);
}
const result = await handler(req, ctx);
const response = await handler(req, ctx);
return result;
Object.entries(CORS_HEADERS).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
} catch (error) {
console.log(error);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
return NextResponse.json(
{ error: 'Internal Server Error' },
{
status: 500,
headers: CORS_HEADERS,
},
);
}
};
}

View File

@@ -9,7 +9,6 @@ export function GET(request: NextRequest) {
});
return NextResponse.json(apis, {
status: 200,
headers: {
// TODO: Update for marketing page
'Access-Control-Allow-Origin': '*',