Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 32 additions & 27 deletions backend/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,44 @@ const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
});

UserSchema.pre('save', async function (next) {
username: {
type: String,
required: [true, "Username is required"],
unique: true,
trim: true,
},
email: {
type: String,
required: [true, "Email is required"],
unique: true,
trim: true,
lowercase: true,
match: [/.+\@.+\..+/, "Please enter a valid email address"],
},
password: {
type: String,
required: [true, "Password is required"],
minlength: [6, "Password must be at least 6 characters long"],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider strengthening password requirements.

The current minimum length of 6 characters might be insufficient for security. Consider adding complexity requirements.

Enhance password validation:

   password: {
     type: String,
     required: [true, "Password is required"],
-    minlength: [6, "Password must be at least 6 characters long"],
+    minlength: [8, "Password must be at least 8 characters long"],
+    validate: {
+      validator: function(password) {
+        return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/.test(password);
+      },
+      message: "Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character"
+    }
   },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
minlength: [6, "Password must be at least 6 characters long"],
password: {
type: String,
required: [true, "Password is required"],
minlength: [8, "Password must be at least 8 characters long"],
validate: {
validator: function(password) {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/.test(password);
},
message: "Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character"
}
},
🤖 Prompt for AI Agents
In backend/models/User.js at line 22, the password validation only enforces a
minimum length of 6 characters, which is weak for security. Enhance the password
validation by adding complexity requirements such as including uppercase
letters, lowercase letters, numbers, and special characters using a custom
validator or regex pattern in the schema definition.

},
}, { timestamps: true });

if (!this.isModified('password'))
return next();
// Pre-save password hash
UserSchema.pre("save", async function (next) {
if (!this.isModified("password")) return next();

try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
next();
} catch (err) {
return next(err);
}
try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
return next();
} catch (err) {
console.error("Password Hashing Error:", err.message);
return next(err);
}
});

// Compare passwords during login
UserSchema.methods.comparePassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
return await bcrypt.compare(enteredPassword, this.password);
};

module.exports = mongoose.model("User", UserSchema);
53 changes: 38 additions & 15 deletions backend/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,60 @@ const router = express.Router();

// Signup route
router.post("/signup", async (req, res) => {

const { username, email, password } = req.body;
const { username, email, password } = req.body;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding input validation before processing.

The route directly destructures req.body without validating the presence or format of required fields. This could lead to unexpected behavior if any field is missing or malformed.

Add input validation before processing:

 router.post("/signup", async (req, res) => {
     const { username, email, password } = req.body;
+
+    // Validate required fields
+    if (!username || !email || !password) {
+        return res.status(400).json({ message: 'All fields are required' });
+    }
 
     try {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { username, email, password } = req.body;
router.post("/signup", async (req, res) => {
const { username, email, password } = req.body;
// Validate required fields
if (!username || !email || !password) {
return res.status(400).json({ message: 'All fields are required' });
}
try {
// … existing signup logic …
} catch (err) {
// … existing error handling …
}
});
🤖 Prompt for AI Agents
In backend/routes/auth.js at line 8, the code destructures username, email, and
password from req.body without validating their presence or format. Add input
validation before this line to check that all required fields exist and meet
expected formats, returning an error response if validation fails to prevent
processing invalid or incomplete data.


try {
const existingUser = await User.findOne( {email} );
const existingUser = await User.findOne({ email });

if (existingUser)
return res.status(400).json( {message: 'User already exists'} );
if (existingUser) {
return res.status(400).json({ message: 'User already exists' });
}

const newUser = new User( {username, email, password} );
const newUser = new User({ username, email, password });
await newUser.save();
res.status(201).json( {message: 'User created successfully'} );

return res.status(201).json({ message: 'User created successfully' });
} catch (err) {
res.status(500).json({ message: 'Error creating user', error: err.message });
console.error("Signup Error:", err.message);
return res.status(500).json({
message: 'Error creating user',
error: err.message
});
}
Comment on lines +22 to 27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security concern: Exposing internal error messages.

The error response includes err.message which might expose sensitive information about the database structure or internal implementation details to clients.

Consider sanitizing error messages for client responses:

     } catch (err) {
         console.error("Signup Error:", err.message);
         return res.status(500).json({
-            message: 'Error creating user',
-            error: err.message
+            message: 'Error creating user'
         });
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.error("Signup Error:", err.message);
return res.status(500).json({
message: 'Error creating user',
error: err.message
});
}
} catch (err) {
console.error("Signup Error:", err.message);
return res.status(500).json({
message: 'Error creating user'
});
}
🤖 Prompt for AI Agents
In backend/routes/auth.js around lines 22 to 27, the error response sends
err.message directly to the client, which can expose sensitive internal details.
Modify the code to send a generic error message to the client instead of
err.message, while logging the detailed error internally using console.error or
a logger. This prevents leaking sensitive information while still allowing
debugging.

});

// Login route
router.post("/login", passport.authenticate('local'), (req, res) => {
res.status(200).json( { message: 'Login successful', user: req.user } );
router.post("/login", (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) {
console.error("Login Error:", err.message);
return res.status(500).json({ message: 'Internal Server Error', error: err.message });
}

if (!user) {
return res.status(401).json({ message: 'Invalid credentials', error: info?.message || 'Authentication failed' });
}

req.logIn(user, (err) => {
if (err) {
console.error("Session Error:", err.message);
return res.status(500).json({ message: 'Login failed', error: err.message });
}

return res.status(200).json({ message: 'Login successful', user });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security concern: Exposing user object in response.

Returning the entire user object might expose sensitive information like hashed passwords or internal fields.

Consider returning only safe user fields:

-            return res.status(200).json({ message: 'Login successful', user });
+            return res.status(200).json({ 
+                message: 'Login successful', 
+                user: { id: user._id, username: user.username, email: user.email }
+            });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return res.status(200).json({ message: 'Login successful', user });
return res.status(200).json({
message: 'Login successful',
user: { id: user._id, username: user.username, email: user.email }
});
🤖 Prompt for AI Agents
In backend/routes/auth.js at line 48, the code returns the entire user object in
the response, which may expose sensitive data. Modify the response to include
only safe, non-sensitive user fields such as username, email, or user ID.
Extract these safe fields from the user object and return them instead of the
full user object in the JSON response.

});
})(req, res, next);
});

// Logout route
router.get("/logout", (req, res) => {

req.logout((err) => {

if (err)
if (err) {
console.error("Logout Error:", err.message);
return res.status(500).json({ message: 'Logout failed', error: err.message });
else
res.status(200).json({ message: 'Logged out successfully' });
}

return res.status(200).json({ message: 'Logged out successfully' });
});
});

Expand Down
44 changes: 33 additions & 11 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,51 @@ require('./config/passportConfig');

const app = express();

// CORS configuration
app.use(cors('*'));
// ✅ CORS configuration (recommended)
app.use(cors({
origin: '*', // You can replace * with specific domains in production
credentials: true,
}));
Comment on lines +15 to +18
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security risk: Overly permissive CORS configuration.

Setting origin: '*' with credentials: true is a security vulnerability that allows any origin to make credentialed requests to your API.

Configure CORS more securely:

 app.use(cors({
-    origin: '*', // You can replace * with specific domains in production
+    origin: process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:3000'],
     credentials: true,
 }));

Add ALLOWED_ORIGINS=http://localhost:3000,https://yourdomain.com to your environment variables.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
app.use(cors({
origin: '*', // You can replace * with specific domains in production
credentials: true,
}));
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:3000'],
credentials: true,
}));
🤖 Prompt for AI Agents
In backend/server.js around lines 15 to 18, the CORS configuration uses origin:
'*' with credentials: true, which is insecure. To fix this, replace the wildcard
origin with a function that checks the request origin against a whitelist of
allowed origins defined in an environment variable ALLOWED_ORIGINS (e.g.,
'http://localhost:3000,https://yourdomain.com'). Only allow requests from these
origins and keep credentials: true. This ensures only trusted domains can make
credentialed requests.


// Middleware
// Middleware
app.use(bodyParser.json());

app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
}));

app.use(passport.initialize());
app.use(passport.session());

// Routes
// Routes
const authRoutes = require('./routes/auth');
app.use('/api/auth', authRoutes);

// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, {}).then(() => {
console.log('Connected to MongoDB');
app.listen(process.env.PORT, () => {
console.log(`Server running on port ${process.env.PORT}`);
// ✅ Fallback route for 404 Not Found
app.use((req, res, next) => {
res.status(404).json({ message: 'Route not found' });
});

// ✅ Global error-handling middleware
app.use((err, req, res, next) => {
console.error('Unhandled Error:', err.stack);
res.status(err.status || 500).json({
message: err.message || 'Internal Server Error',
error: process.env.NODE_ENV === 'production' ? undefined : err.stack,
});
}).catch((err) => {
console.log('MongoDB connection error:', err);
});

// ✅ Connect to MongoDB and start server
mongoose.connect(process.env.MONGO_URI, {})
.then(() => {
console.log('Connected to MongoDB');
app.listen(process.env.PORT, () => {
console.log(`Server running on port ${process.env.PORT}`);
});
})
.catch((err) => {
console.error('MongoDB connection error:', err);
process.exit(1); // exit the process on DB failure
});