support json content-type

This commit is contained in:
notmd
2023-01-26 02:49:22 +07:00
parent 877aabfef1
commit d456cffc4a
3 changed files with 24 additions and 11 deletions
-4
View File
@@ -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) => {
+10 -5
View File
@@ -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(() => {
+14 -2
View File
@@ -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<Record<string, any> | 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;