From d456cffc4a4d0bc8dbeebc3f708902301a250c36 Mon Sep 17 00:00:00 2001 From: notmd Date: Thu, 26 Jan 2023 02:49:22 +0700 Subject: [PATCH] support json content-type --- website/cypress/e2e/auth/signin.cy.ts | 4 ---- website/cypress/support/commands.ts | 15 ++++++++++----- website/src/middleware.ts | 16 ++++++++++++++-- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/website/cypress/e2e/auth/signin.cy.ts b/website/cypress/e2e/auth/signin.cy.ts index 04a042cf..9d6e63e1 100644 --- a/website/cypress/e2e/auth/signin.cy.ts +++ b/website/cypress/e2e/auth/signin.cy.ts @@ -15,7 +15,6 @@ describe("signin flow", () => { .then((response) => { const csrfToken = response.body.csrfToken; cy.request({ - form: true, method: "POST", url: "/api/auth/signin/email", body: { @@ -25,9 +24,6 @@ describe("signin flow", () => { json: "true", captcha: "XXXX.DUMMY.TOKEN.XXXX", }, - headers: { - "content-type": "application/x-www-form-urlencoded", - }, }); }) .then((response) => { diff --git a/website/cypress/support/commands.ts b/website/cypress/support/commands.ts index 096720d0..3939c685 100644 --- a/website/cypress/support/commands.ts +++ b/website/cypress/support/commands.ts @@ -58,11 +58,16 @@ Cypress.Commands.add("signInWithEmail", (emailAddress) => { cy.request("GET", "/api/auth/csrf") .then((response) => { const csrfToken = response.body.csrfToken; - cy.request("POST", "/api/auth/signin/email", { - callbackUrl: "/", - email: emailAddress, - csrfToken, - json: "true", + cy.request({ + method: "POST", + url: "/api/auth/signin/email", + body: { + callbackUrl: "/", + email: emailAddress, + csrfToken, + json: "true", + captcha: "XXXX.DUMMY.TOKEN.XXXX", + }, }); }) .then(() => { diff --git a/website/src/middleware.ts b/website/src/middleware.ts index 0bfb4527..4c85d3ac 100644 --- a/website/src/middleware.ts +++ b/website/src/middleware.ts @@ -22,8 +22,8 @@ export const config = { const middleware = async (req: NextRequestWithAuth) => { if (req.method === "POST" && req.nextUrl.pathname === "/api/auth/signin/email") { - const data = await req.formData(); - const res = await checkCaptcha(data.get("captcha")?.toString(), req.ip); + const data = await getBody(req); + const res = await checkCaptcha(data?.captcha, req.ip); if (res.success) { return NextResponse.next(); @@ -38,4 +38,16 @@ const middleware = async (req: NextRequestWithAuth) => { return withAuth(req); }; +async function getBody(req: Request): Promise | undefined> { + if (!("body" in req) || !req.body || req.method !== "POST") return; + + const contentType = req.headers.get("content-type"); + if (contentType?.includes("application/json")) { + return await req.json(); + } else if (contentType?.includes("application/x-www-form-urlencoded")) { + const params = new URLSearchParams(await req.text()); + return Object.fromEntries(params); + } +} + export default middleware;