Skip to content

Commit

Permalink
refactore: only use body once
Browse files Browse the repository at this point in the history
  • Loading branch information
noahonyejese committed Oct 1, 2024
1 parent 66576df commit 3fcf780
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 29 deletions.
26 changes: 18 additions & 8 deletions app/api/slack/events/conversations/route.ts
Original file line number Diff line number Diff line change
@@ -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();

Expand All @@ -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,
Expand Down
22 changes: 1 addition & 21 deletions server/security.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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 });
}
};

0 comments on commit 3fcf780

Please sign in to comment.