Skip to content

Commit da6ba85

Browse files
feat(auth): add input validation for registration and login using Zod
1 parent be94f37 commit da6ba85

File tree

4 files changed

+32
-2
lines changed

4 files changed

+32
-2
lines changed

server/controllers/authController.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
const bcrypt = require("bcrypt");
22
const jwt = require("jsonwebtoken");
33
const User = require("../models/User");
4+
const registerSchema = require("../validations/authValidate").registerSchema;
45

56
const tokenBlacklist = [];
67

78
const JWT_SECRET = process.env.JWT_SECRET || "your_jwt_secret";
89
const JWT_EXPIRES_IN = "1h";
910

1011
exports.registerUser = async (req, res) => {
12+
const validation = registerSchema.safeParse({ body: req.body });
13+
if (!validation.success) {
14+
return res.status(400).json({ message: "Invalid input", errors: validation.error.errors });
15+
}
1116
try {
1217
console.log("Register body:", req.body);
1318
const { email, password } = req.body;
@@ -33,6 +38,10 @@ exports.registerUser = async (req, res) => {
3338
};
3439

3540
exports.loginUser = async (req, res) => {
41+
const validation = registerSchema.safeParse({ body: req.body });
42+
if (!validation.success) {
43+
return res.status(400).json({ message: "Invalid input", errors: validation.error.errors });
44+
}
3645
try {
3746
console.log("Login body:", req.body);
3847
const { email, password } = req.body;

server/package-lock.json

Lines changed: 11 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

server/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
"jsonwebtoken": "^9.0.2",
1919
"mongodb": "^6.20.0",
2020
"mongoose": "^8.19.2",
21-
"socket.io": "^4.8.1"
21+
"socket.io": "^4.8.1",
22+
"zod": "^4.1.12"
2223
},
2324
"devDependencies": {
2425
"nodemon": "^3.1.10"

server/validations/authValidate.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const zod = require("zod");
2+
3+
const registerSchema = zod.object({
4+
body: zod.object({
5+
email: zod.string().email(),
6+
password: zod.string().min(6).max(100),
7+
})
8+
});
9+
10+
module.exports = { registerSchema };

0 commit comments

Comments
 (0)