From 439972b934148310f4513a10bd182216f2200aba Mon Sep 17 00:00:00 2001 From: Nial <48334675+nmcc1212@users.noreply.github.com> Date: Fri, 16 Feb 2024 14:25:14 +0000 Subject: [PATCH] Add input validation for username and password in userAuth middleware and fix userRoutes endpoint paths --- newAPI/src/middlewares/userAuth.ts | 6 ++++++ newAPI/src/routes/userRoutes.ts | 9 +++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/newAPI/src/middlewares/userAuth.ts b/newAPI/src/middlewares/userAuth.ts index 865bd47..da67a0b 100644 --- a/newAPI/src/middlewares/userAuth.ts +++ b/newAPI/src/middlewares/userAuth.ts @@ -14,7 +14,13 @@ async function authenticateUser( } try { const username = req.body.auth.username; + if (!username) { + return res.status(400).json({ message: "Username is required" }); + } const password = req.body.auth.password; + if (!password) { + return res.status(400).json({ message: "Password is required" }); + } const user = await User.findOne({ username }); if (!user) { diff --git a/newAPI/src/routes/userRoutes.ts b/newAPI/src/routes/userRoutes.ts index 8f0070d..2ec1ba3 100644 --- a/newAPI/src/routes/userRoutes.ts +++ b/newAPI/src/routes/userRoutes.ts @@ -31,7 +31,8 @@ userRouter.post("/", async (req: Request, res: Response) => { if (emailExists) { return res.status(400).json({ message: "email already exists" }); } - const newID = (await User.find({}).sort([["userID", -1]]))[0]; + const newID = (await User.find({}).sort([["id", "desc"]]))[0].id + 1; + console.log("newID: ", newID); const user = new User({ id: newID, username: username, @@ -72,7 +73,7 @@ userRouter.get("/", async (req: Request, res: Response) => { } }); // can take email, username or password in body, must username and password in auth -userRouter.patch("/", authenticateUser, async (req: Request, res: Response) => { +userRouter.patch("/:id", authenticateUser, async (req: Request, res: Response) => { if (!req.user) { return res.status(401).json({ message: "Unauthorized" }); } @@ -103,7 +104,7 @@ userRouter.patch("/", authenticateUser, async (req: Request, res: Response) => { // must have username and password in auth userRouter.delete( - "/", + "/:id", authenticateUser, async (req: Request, res: Response) => { if (!req.user) { @@ -114,7 +115,7 @@ userRouter.delete( return res.status(404).json({ message: "User not found" }); } await user.deleteOne(); - res.json({ message: "Post deleted" }); + res.json({ message: "User deleted" }); } );