Fix Authentication issues for Webhook API (#622)

This commit is contained in:
Matti Nannt
2023-07-31 14:10:28 +02:00
committed by GitHub
parent 000fcf8b02
commit 288fc79366
3 changed files with 33 additions and 17 deletions

View File

@@ -18,6 +18,9 @@ export async function GET(_: Request, { params }: { params: { webhookId: string
if (!webhook) {
return responses.notFoundResponse("Webhook", params.webhookId);
}
if (webhook.environmentId !== apiKeyData.environmentId) {
return responses.unauthorizedResponse();
}
return responses.successResponse(webhook);
}
@@ -31,7 +34,16 @@ export async function DELETE(_: Request, { params }: { params: { webhookId: stri
return responses.notAuthenticatedResponse();
}
// add webhook to database
// check if webhook exists
const webhook = await getWebhook(params.webhookId);
if (!webhook) {
return responses.notFoundResponse("Webhook", params.webhookId);
}
if (webhook.environmentId !== apiKeyData.environmentId) {
return responses.unauthorizedResponse();
}
// delete webhook from database
try {
const webhook = await deleteWebhook(params.webhookId);
return responses.successResponse(webhook);

View File

@@ -101,6 +101,19 @@ const notAuthenticatedResponse = (cors: boolean = false) =>
}
);
const unauthorizedResponse = (cors: boolean = false) =>
NextResponse.json(
{
code: "unauthorized",
message: "You are not authorized to access this resource",
details: {},
} as ApiErrorResponse,
{
status: 401,
...(cors && { headers: corsHeaders }),
}
);
const successResponse = (data: Object, cors: boolean = false) =>
NextResponse.json(
{
@@ -131,6 +144,7 @@ export const responses = {
missingFieldResponse,
methodNotAllowedResponse,
notAuthenticatedResponse,
unauthorizedResponse,
notFoundResponse,
successResponse,
};

View File

@@ -16,22 +16,12 @@ export const getWebhooks = async (environmentId: string): Promise<TWebhook[]> =>
};
export const getWebhook = async (id: string): Promise<TWebhook | null> => {
try {
const webhook = await prisma.webhook.findUnique({
where: {
id,
},
});
if (!webhook) {
throw new ResourceNotFoundError("Webhook", id);
}
return webhook;
} catch (error) {
if (!(error instanceof ResourceNotFoundError)) {
throw new DatabaseError(`Database error when fetching webhook with ID ${id}`);
}
throw error;
}
const webhook = await prisma.webhook.findUnique({
where: {
id,
},
});
return webhook;
};
export const createWebhook = async (