Skip to content
This repository has been archived by the owner on Aug 14, 2024. It is now read-only.

Commit

Permalink
Add input validation for username and password in userAuth middleware…
Browse files Browse the repository at this point in the history
… and fix userRoutes endpoint paths
  • Loading branch information
nmcc1212 committed Feb 16, 2024
1 parent df23c93 commit 439972b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
6 changes: 6 additions & 0 deletions newAPI/src/middlewares/userAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
9 changes: 5 additions & 4 deletions newAPI/src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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" });
}
Expand Down Expand Up @@ -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) {
Expand All @@ -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" });
}
);

Expand Down

0 comments on commit 439972b

Please sign in to comment.