Skip to content

Commit cc94b0b

Browse files
committed
refactor(auth): improve signup validation, optimize user retrieval, and update docs
1 parent 223df34 commit cc94b0b

4 files changed

Lines changed: 32 additions & 12 deletions

File tree

backend/controllers/userAuth.controller.js

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,16 @@ const jwt = require('jsonwebtoken');
22
const bcrypt = require('bcryptjs');
33
const { z } = require('zod');
44
const mongoose = require('mongoose');
5-
const { loginSchema, signupSchema } = require('../utils/input.validation');
5+
const { loginSchema, userSignupSchema } = require('../utils/input.validation');
66

77
module.exports.signup = async (req, res) => {
88
try {
99
const project = req.project;
1010

11+
const data = userSignupSchema.parse(req.body);
12+
1113
// Zod Validation (Prevents NoSQL Injection too)
12-
const { email, password, username, ...otherData } = signupSchema.parse(req.body);
14+
const { email, password, username, ...otherData } = userSignupSchema.parse(req.body);
1315

1416
const collectionName = `${project._id}_users`;
1517
const collection = mongoose.connection.db.collection(collectionName);
@@ -26,6 +28,7 @@ module.exports.signup = async (req, res) => {
2628
username,
2729
email,
2830
password: hashedPassword,
31+
...otherData,
2932
createdAt: new Date()
3033
};
3134

@@ -45,6 +48,7 @@ module.exports.signup = async (req, res) => {
4548
} catch (err) {
4649
if (err instanceof z.ZodError) return res.status(400).json({ error: err.errors });
4750
res.status(500).json({ error: err.message }); // Fixed: .json()
51+
console.log(err)
4852
}
4953
}
5054

@@ -90,17 +94,17 @@ module.exports.me = async (req, res) => {
9094
const collectionName = `${project._id}_users`;
9195
const collection = mongoose.connection.db.collection(collectionName);
9296

93-
const user = await collection.findOne({
94-
_id: new mongoose.Types.ObjectId(decoded.userId)
95-
});
97+
const user = await collection.findOne(
98+
{ _id: new mongoose.Types.ObjectId(decoded.userId) },
99+
{ projection: { password: 0 } }
100+
);
96101

97102
if (!user) return res.status(404).json({ error: "User not found" });
98103

99-
const { password, ...userData } = user;
100-
res.json(userData);
104+
res.json(user);
101105

102106
} catch (err) {
103-
return res.status(400).json({ error: "Invalid or Expired Token" });
107+
return res.status(401).json({ error: "Invalid or Expired Token" });
104108
}
105109

106110
} catch (err) {

backend/middleware/verifyApiKey.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ module.exports = async (req, res, next) => {
2828
databaseLimit
2929
databaseUsed
3030
storageLimit
31-
storageUsed
31+
storageUsed,
32+
jwtSecret
3233
`)
3334
.populate('owner', 'isVerified')
3435
.lean();

backend/utils/input.validation.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,4 +90,19 @@ module.exports.updateExternalConfigSchema = z.object({
9090
return !!(data.dbUri || (data.storageUrl && data.storageKey));
9191
}, {
9292
message: "Provide either a DB URI or a complete Storage config (URL + Key)."
93-
});
93+
});
94+
95+
module.exports.userSignupSchema = z.object({
96+
username: z.string()
97+
.min(3, { message: "Username must be at least 3 characters." })
98+
.max(30, { message: "Username is too long." }).optional(),
99+
100+
email: z.string()
101+
.min(1, { message: "Email is required." })
102+
.email({ message: "Invalid email format." })
103+
.max(100, { message: "Email is too long." }),
104+
105+
password: z.string()
106+
.min(6, { message: "Password must be at least 6 characters." })
107+
.max(100, { message: "Password is too long." })
108+
}).passthrough();

frontend/src/pages/Docs.jsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ console.log(data);
238238
<CodeBlock
239239
method="POST"
240240
url="/api/userAuth/signup"
241-
body={{ email: "user@example.com", password: "securePassword123", name: "John Doe" }}
241+
body={{ email: "user@example.com", password: "securePassword123", username: "John Doe" }}
242242
comment="Register a new user"
243243
/>
244244

@@ -297,7 +297,7 @@ console.log(data);
297297
body={{ name: "MacBook Pro", price: 1299, inStock: true }}
298298
comment="Add a new item"
299299
/>
300-
<TryItPanel endpoint="/api/data/:collectionName" method="POST" />
300+
<TryItPanel endpoint="/api/data/:collectionName" method="POST" />
301301

302302

303303
<h3 style={{ fontSize: '1.1rem', marginTop: '2rem' }}>3. Get / Update / Delete by ID</h3>

0 commit comments

Comments
 (0)