diff --git a/apps/api/package.json b/apps/api/package.json index 25fa0e90e39..0a8f2abbd0d 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -5,7 +5,7 @@ "scripts": { "dev": "node src/server.js", "start": "node src/server.js", - "test": "node --test src/tests" + "test": "node --test src/tests/**/*.js" }, "dependencies": { "cors": "^2.8.5", diff --git a/apps/api/src/routes/paymentRoutes.js b/apps/api/src/routes/paymentRoutes.js index e6cebed50b2..ff40769632a 100644 --- a/apps/api/src/routes/paymentRoutes.js +++ b/apps/api/src/routes/paymentRoutes.js @@ -1,6 +1,7 @@ import { Router } from "express"; import { createPayment } from "../controllers/paymentController.js"; +import { authMiddleware } from "../middleware/auth.js"; export const paymentRoutes = Router(); -paymentRoutes.post("/", createPayment); +paymentRoutes.post("/", authMiddleware, createPayment); diff --git a/apps/api/src/tests/payments-auth.test.js b/apps/api/src/tests/payments-auth.test.js new file mode 100644 index 00000000000..79cfb56e46c --- /dev/null +++ b/apps/api/src/tests/payments-auth.test.js @@ -0,0 +1,48 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createApp } from "../app.js"; +import { signAccessToken } from "../utils/jwt.js"; + +async function withServer(run) { + const app = createApp(); + const server = app.listen(0); + await new Promise((resolve, reject) => { + server.once("listening", resolve); + server.once("error", reject); + }); + try { + await run(server.address().port); + } finally { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); + } +} + +test("POST /api/payments without auth returns 401", async () => { + await withServer(async (port) => { + const response = await fetch(`http://127.0.0.1:${port}/api/payments`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: "a@example.com" }) + }); + const payload = await response.json(); + assert.equal(response.status, 401); + assert.equal(payload.success, false); + }); +}); + +test("POST /api/payments with auth is not unauthorized", async () => { + await withServer(async (port) => { + const token = signAccessToken({ sub: "usr_test", role: "client" }); + const response = await fetch(`http://127.0.0.1:${port}/api/payments`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}` + }, + body: JSON.stringify({ email: "a@example.com", name: "payment" }) + }); + assert.notEqual(response.status, 401); + }); +});