From 3fcf780bbd7b6a837dbdcb3b91a6b643bb72c3a8 Mon Sep 17 00:00:00 2001 From: Noah Onyejese <129368606+noahonyejese@users.noreply.github.com> Date: Tue, 1 Oct 2024 09:08:36 +0200 Subject: [PATCH] refactore: only use body once --- app/api/slack/events/conversations/route.ts | 26 ++++++++++++++------- server/security.ts | 22 +---------------- 2 files changed, 19 insertions(+), 29 deletions(-) diff --git a/app/api/slack/events/conversations/route.ts b/app/api/slack/events/conversations/route.ts index e880326..9028bd7 100644 --- a/app/api/slack/events/conversations/route.ts +++ b/app/api/slack/events/conversations/route.ts @@ -1,21 +1,32 @@ +import { initializeFirebase } from '@/server/firebase/server'; +import { verifySlackRequest } from '@/server/security'; import { updateSlackMessage, updateSlackReaction, validateMessageSlackEvent, validateReactionSlackEvent, } from '@/server/slack/syncs'; -import { initializeFirebase } from '@/server/firebase/server'; -import { validateWebhookEntry } from '@/server/security'; -import { NextRequest } from 'next/server'; +import { createError } from '@/utils/error-handling'; +import { NextRequest, NextResponse } from 'next/server'; export const POST = async (req: NextRequest) => { try { - await validateWebhookEntry(req); - const rawBody = await req.text(); + if (!verifySlackRequest(rawBody, req)) { + throw createError({ + title: 'Invalid Slack signature', + message: 'The request signature is invalid', + }); + } + const body = JSON.parse(rawBody); - const { type, event } = body; + const { type, challenge, event } = body; + + // URL verification for Slack API + if (type === 'url_verification') { + return NextResponse.json({ challenge }); + } initializeFirebase(); @@ -38,8 +49,7 @@ export const POST = async (req: NextRequest) => { ); } catch (error) { if (error instanceof Error) { - - console.log(error.message) + console.log(error.message); return new Response(JSON.stringify({ success: false, error }), { status: 400, diff --git a/server/security.ts b/server/security.ts index ec40a30..0059e42 100644 --- a/server/security.ts +++ b/server/security.ts @@ -1,6 +1,5 @@ -import { createError } from '@/utils/error-handling'; import crypto from 'crypto'; -import { NextRequest, NextResponse } from 'next/server'; +import { NextRequest } from 'next/server'; export const verifySlackRequest = ( rawBody: string, @@ -25,22 +24,3 @@ export const verifySlackRequest = ( ) ); }; - -export const validateWebhookEntry = async (req: NextRequest) => { - const rawBody = await req.text(); - - if (!verifySlackRequest(rawBody, req)) { - throw createError({ - title: 'Invalid Slack signature', - message: 'The request signature is invalid', - }); - } - - const body = JSON.parse(rawBody); - const { type, challenge } = body; - - // URL verification for Slack API - if (type === 'url_verification') { - return NextResponse.json({ challenge }); - } -};