Skip to content

feat: initialize backend server with user authentication, MongoDB con… - #1

Merged
hemjaygfx merged 2 commits into
mainfrom
register
Jun 19, 2026
Merged

hemjaygfx merged 2 commits into
mainfrom
register

Conversation

@hemjaygfx

@hemjaygfx hemjaygfx commented Jun 19, 2026 •

Copy link
Copy Markdown
Owner

Overview

This pull request implements user registration functionality by setting up a MongoDB database connection, defining the User schema, creating helper utilities for JWT authentication, and introducing the register endpoint controller.

Key Changes

  • Database Connection (backend/src/lib/db.js & backend/src/server.js):

    • Created a helper module to manage the MongoDB database connection.
    • Updated the server start listener to call connectDB() when the Express application launches.
    • Added express.json() middleware to parse JSON payloads from incoming request bodies.
  • User Model (backend/src/models/user.model.js):

    • Designed the database schema for Users (including username, fullName, email, password, profilePic, and automatic timestamps).
  • Registration Logic & Validation (backend/src/controllers/auth.controller.js):

    • Added the register controller with comprehensive backend input validation:
      • Rejects requests if any required field is missing.
      • Rejects requests if the username or email already exists in the database.
      • Checks password strength (must be at least 6 characters).
      • Validates email format using regex.
    • Securely hashes passwords using bcryptjs before database persistence.
  • JWT Helper (backend/src/lib/utils.js):

    • Implemented generateToken() to sign a JSON Web Token and set it as an httpOnly, secure, sameSite: "strict" cookie for session management.
  • Routes (backend/src/routes/auth.route.js):

    • Replaced the placeholder GET /register stub route with a proper POST /register endpoint linked to the new registration controller.
    • Updated code comments and documented login/logout route placements.

Future Tasks / TODOs

  • Implement sending a welcome email to users after successful registration.
  • Complete controller implementations for /login and /logout endpoints.

How to Test

  1. Ensure your MongoDB connection string is set up in your .env file.
  2. Start the server (npm run dev).
  3. Send a POST request to http://localhost:3000/api/auth/register with a JSON payload, e.g.:
    {
      "username": "testuser",
      "fullName": "Test User",
      "email": "test@example.com",
      "password": "securepassword"
    }
    
    

Summary by CodeRabbit

New Features

  • User registration functionality now available—create accounts with username, full name, email, and password
  • Password minimum length requirement enforced during registration
  • Email format validation implemented
  • System prevents duplicate usernames and emails

@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR scaffolds the backend user registration flow: a Mongoose User model, a MongoDB connectDB helper wired into server.js startup, a generateToken JWT-cookie utility, and a full register controller with field validation, duplicate checks, bcrypt hashing, and a POST /register route.

Changes

User Registration Backend Foundation

Layer / File(s) Summary
User model and DB connection
backend/src/models/user.model.js, backend/src/lib/db.js
userSchema defines required/unique username and email, required password with minlength: 6, a profilePic default, and timestamps. connectDB connects via MONGO_URI, logs the host on success, and calls process.exit(1) on failure. A commented prior implementation is also present in db.js.
JWT utility and server startup wiring
backend/src/lib/utils.js, backend/src/server.js
generateToken signs a JWT with userId and JWT_SECRET (15-day expiry) and sets it as an httpOnly, strict same-site cookie. server.js gains express.json() middleware and calls connectDB() inside the app.listen callback.
Register controller and route wiring
backend/src/controllers/auth.controller.js, backend/src/routes/auth.route.js
register validates body fields, enforces email regex and password length, queries for duplicate username/email, hashes the password with bcryptjs, saves a new User, calls generateToken, and returns 201 with user fields. auth.route.js wires it to POST /register.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 A hop and a hash, a token set free,
The User schema blooms like a fresh burrow tree.
Registration flows through the Express express,
Cookies go httpOnly, bcrypt does the rest.
The database wakes with a MONGO_URI call—
NexTalk is rising, one register at all! 🌱

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: implementing backend server initialization with user authentication and MongoDB connection infrastructure.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch register

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (6)
backend/src/routes/auth.route.js (1)

9-12: ⚡ Quick win

Login endpoint should use POST method.

GET /login exposes credentials in URL/query strings (visible in logs, browser history, referrer headers). This is a placeholder per PR objectives, but when implemented, it should be POST /login.

Suggested change for when login is implemented
 // Login endpoint
-router.get('/login', (req, res) => {
-    res.send('Login endpoint');
-});
+router.post('/login', (req, res) => {
+    res.send('Login endpoint');
+});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/routes/auth.route.js` around lines 9 - 12, The login endpoint is
currently using the GET HTTP method, which exposes credentials in the URL, query
strings, logs, and browser history, creating a security vulnerability. Change
the router.get() method call for the '/login' route to router.post() instead, so
that login credentials are transmitted in the request body rather than exposed
in the URL.
backend/src/server.js (1)

20-20: 💤 Low value

Consider adding a request body size limit.

express.json() without a limit option accepts arbitrarily large payloads by default (though Express has a 100kb default). Explicitly setting a limit protects against oversized request attacks.

Suggested change
-app.use(express.json()) // req.body
+app.use(express.json({ limit: '1mb' })) // req.body - adjust limit as needed
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/server.js` at line 20, The express.json() middleware call does
not specify a request body size limit, which can allow oversized payloads that
pose a security risk. Modify the express.json() middleware call by adding a
limit option (for example, limit: '10mb' or similar) to explicitly restrict the
maximum request body size that the server will accept. This protects against
potential denial-of-service attacks from excessively large payloads.
backend/src/controllers/auth.controller.js (1)

14-17: 💤 Low value

Consider combining duplicate-check queries.

Two separate database round-trips check for existing username and email. These can be combined into a single query for better performance.

Suggested optimization
-        // check if username is already exists 
-        const existingUserByUsername = await User.findOne({ username });
-        if (existingUserByUsername) {
-            return res.status(400).json({message: 'Username already exists'});
-        }
-
-        // check if password is less then 6 characters long 
-        if (password.length < 6) {
-            return res.status(400).json({message: 'Password must be at least 6 characters long'});
-        }
-
-        //check if emails valid or not: regex pattern for email   
-        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
-        if (!emailRegex.test(email)) {
-            return res.status(400).json({message: 'Invalid email format'});
-        }
-
-        const existingUserByEmail = await User.findOne({email});
-        if (existingUserByEmail) {
-            return res.status(400).json({message: 'Email already exists'});
-        }
+        // Validate password and email format first (no DB call needed)
+        if (password.length < 6) {
+            return res.status(400).json({message: 'Password must be at least 6 characters long'});
+        }
+
+        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+        if (!emailRegex.test(email)) {
+            return res.status(400).json({message: 'Invalid email format'});
+        }
+
+        // Check for existing username or email in one query
+        const existingUser = await User.findOne({ 
+            $or: [{ username }, { email }] 
+        });
+        if (existingUser) {
+            if (existingUser.username === username) {
+                return res.status(400).json({message: 'Username already exists'});
+            }
+            return res.status(400).json({message: 'Email already exists'});
+        }

Also applies to: 30-33

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/controllers/auth.controller.js` around lines 14 - 17, The code
performs two separate database queries to check for existing username and email,
which results in unnecessary round-trips. Combine these duplicate-check queries
into a single User.findOne() call by using the MongoDB $or operator to check for
both username and email existence in one database operation. After receiving the
result, verify which field (username or email) already exists and return the
appropriate error message to the client.
backend/src/models/user.model.js (2)

3-7: 💤 Low value

Consider adding trim and removing redundant minlength.

  1. The minlength: 6 on password is ineffective because the controller stores the bcrypt hash (which is always ~60 chars). Validation happens in the controller before hashing.
  2. Adding trim: true to username prevents whitespace-only variations from bypassing uniqueness (e.g., " john" vs "john").
Suggested changes
     username: {
         type: String,
         required: true,
         unique: true,
+        trim: true,
     },
     password: {
         type: String,
         required: true,
-        minlength: 6,
     },

Also applies to: 17-21

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/models/user.model.js` around lines 3 - 7, Add the `trim: true`
option to the username field definition to prevent whitespace-only variations
from bypassing the unique constraint, ensuring that values like " john" and
"john" are treated identically. Additionally, remove the `minlength: 6`
constraint from the password field definition since validation occurs in the
controller before the password is hashed, and this constraint is ineffective
when applied to the bcrypt hash stored in the database.

12-16: ⚡ Quick win

Consider normalizing email to lowercase.

The unique constraint on email is case-sensitive in MongoDB by default. This means User@Example.com and user@example.com would be treated as different emails, potentially allowing duplicate accounts.

Suggested fix
     email: {
         type: String,
         required: true,
         unique: true,
+        lowercase: true,
     },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/models/user.model.js` around lines 12 - 16, The email field in
the user model has a case-sensitive unique constraint, which allows duplicate
accounts with different email capitalizations (e.g., User@Example.com and
user@example.com are treated as different). Normalize the email to lowercase by
adding either a lowercase option to the email field definition in the schema, or
implement a pre-save middleware hook that converts the email to lowercase before
the document is saved. This ensures the unique constraint works correctly and
prevents duplicate accounts regardless of email case variations.
backend/src/lib/db.js (1)

1-15: ⚡ Quick win

Remove commented-out dead code.

The commented block contains an older implementation that is no longer used. Leaving it in clutters the codebase. If needed for reference, version control history preserves it.

Suggested fix
-/* import dotenv from "dotenv";
-dotenv.config();
-import mongoose from "mongoose";
-
-async function connectDB() {
-  try {
-    await mongoose.connect(process.env.MONGO_URI);
-    console.log("MongoDB connected");
-  } catch (error) {
-    console.error("Error connecting to MongoDB:", error);
-  }
-}
-
-export default connectDB;
- */
-
 import mongoose from "mongoose";
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/lib/db.js` around lines 1 - 15, Remove the entire commented-out
code block that contains the previous implementation of the connectDB function
and its associated imports (dotenv, mongoose). Delete all lines starting from
the opening comment through the closing comment, keeping only the active
implementation if one exists below. This will clean up the codebase by removing
dead code that is already preserved in version control history.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/src/controllers/auth.controller.js`:
- Line 47: The if (newUser) check and its corresponding else block are redundant
because the new User() constructor always returns a Mongoose document instance
and never returns a falsy value. Remove the if (newUser) conditional statement
and the unreachable else block (the dead code), keeping only the logic that
should execute after creating the User instance. The code inside the if block
should be executed unconditionally since newUser will always be truthy.
- Around line 47-56: The token is being generated before the user is persisted
to the database, creating a security issue where the client receives a valid JWT
for a user that may not exist in the database if the save operation fails. Move
the generateToken(newUser._id, res) call to execute after the await
newUser.save() statement completes successfully. This ensures the JWT token is
only issued if the user was successfully saved to the database.

In `@backend/src/lib/utils.js`:
- Line 14: The `secure` flag logic in the cookie configuration is inverted,
causing cookies to be sent over plain HTTP in production (insecure) and HTTPS in
development. In the ternary operator on line 14, swap the boolean values so that
`secure` is set to true when NODE_ENV is not "development" (production) and
false when it is "development". Alternatively, simplify the logic to
`process.env.NODE_ENV !== "development"` to achieve the correct behavior of only
sending cookies over HTTPS in production.

In `@backend/src/server.js`:
- Around line 34-37: The server starts accepting HTTP requests before the
database connection is established because connectDB() is called inside the
app.listen callback instead of being awaited first. Move the connectDB()
invocation outside and before app.listen() by wrapping both in an async IIFE
pattern, ensuring that connectDB() is fully awaited before the app.listen()
callback executes. This guarantees the database connection is ready before the
server begins accepting requests.

---

Nitpick comments:
In `@backend/src/controllers/auth.controller.js`:
- Around line 14-17: The code performs two separate database queries to check
for existing username and email, which results in unnecessary round-trips.
Combine these duplicate-check queries into a single User.findOne() call by using
the MongoDB $or operator to check for both username and email existence in one
database operation. After receiving the result, verify which field (username or
email) already exists and return the appropriate error message to the client.

In `@backend/src/lib/db.js`:
- Around line 1-15: Remove the entire commented-out code block that contains the
previous implementation of the connectDB function and its associated imports
(dotenv, mongoose). Delete all lines starting from the opening comment through
the closing comment, keeping only the active implementation if one exists below.
This will clean up the codebase by removing dead code that is already preserved
in version control history.

In `@backend/src/models/user.model.js`:
- Around line 3-7: Add the `trim: true` option to the username field definition
to prevent whitespace-only variations from bypassing the unique constraint,
ensuring that values like " john" and "john" are treated identically.
Additionally, remove the `minlength: 6` constraint from the password field
definition since validation occurs in the controller before the password is
hashed, and this constraint is ineffective when applied to the bcrypt hash
stored in the database.
- Around line 12-16: The email field in the user model has a case-sensitive
unique constraint, which allows duplicate accounts with different email
capitalizations (e.g., User@Example.com and user@example.com are treated as
different). Normalize the email to lowercase by adding either a lowercase option
to the email field definition in the schema, or implement a pre-save middleware
hook that converts the email to lowercase before the document is saved. This
ensures the unique constraint works correctly and prevents duplicate accounts
regardless of email case variations.

In `@backend/src/routes/auth.route.js`:
- Around line 9-12: The login endpoint is currently using the GET HTTP method,
which exposes credentials in the URL, query strings, logs, and browser history,
creating a security vulnerability. Change the router.get() method call for the
'/login' route to router.post() instead, so that login credentials are
transmitted in the request body rather than exposed in the URL.

In `@backend/src/server.js`:
- Line 20: The express.json() middleware call does not specify a request body
size limit, which can allow oversized payloads that pose a security risk. Modify
the express.json() middleware call by adding a limit option (for example, limit:
'10mb' or similar) to explicitly restrict the maximum request body size that the
server will accept. This protects against potential denial-of-service attacks
from excessively large payloads.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 648f0fe0-77c0-4bd7-a6ef-a3f1ec501c24

📥 Commits

Reviewing files that changed from the base of the PR and between 16229e3 and 1ce3152.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • backend/package.json
  • backend/src/controllers/auth.controller.js
  • backend/src/lib/db.js
  • backend/src/lib/utils.js
  • backend/src/models/user.model.js
  • backend/src/routes/auth.route.js
  • backend/src/server.js

password: hashedPassword
});

if (newUser) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Redundant null check—new User() always returns an object.

The if (newUser) check on line 47 and the corresponding else block are unreachable. The new User({...}) constructor always returns a Mongoose document instance; it never returns a falsy value. The else branch (lines 59-61) is dead code.

Also applies to: 59-61

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/controllers/auth.controller.js` at line 47, The if (newUser)
check and its corresponding else block are redundant because the new User()
constructor always returns a Mongoose document instance and never returns a
falsy value. Remove the if (newUser) conditional statement and the unreachable
else block (the dead code), keeping only the logic that should execute after
creating the User instance. The code inside the if block should be executed
unconditionally since newUser will always be truthy.

Comment on lines +47 to +56
if (newUser) {
generateToken(newUser._id, res);
await newUser.save();
res.status(201).json({
_id: newUser._id,
username: newUser.username,
fullName: newUser.fullName,
email: newUser.email,
profilePic: newUser.profilePic
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Token is generated before user is saved—if save() fails, client receives an invalid JWT.

generateToken() sets the JWT cookie at line 48, but newUser.save() happens at line 49. If the save fails (unique constraint violation at DB level, validation error, network issue), the client already has a cookie containing a userId that doesn't exist in the database.

Move token generation after successful save.

Proposed fix
-        if (newUser) {
-            generateToken(newUser._id, res);
-            await newUser.save();
-             res.status(201).json({
+        await newUser.save();
+        generateToken(newUser._id, res);
+        
+        res.status(201).json({
                 _id: newUser._id,
                 username: newUser.username, 
                 fullName: newUser.fullName,
                 email: newUser.email,
                 profilePic: newUser.profilePic
             });
             
             // Todo: send a welcome email to user after successful registration
-        } else {
-             res.status(400).json({message: 'Failed to create user'});
-        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/controllers/auth.controller.js` around lines 47 - 56, The token
is being generated before the user is persisted to the database, creating a
security issue where the client receives a valid JWT for a user that may not
exist in the database if the save operation fails. Move the
generateToken(newUser._id, res) call to execute after the await newUser.save()
statement completes successfully. This ensures the JWT token is only issued if
the user was successfully saved to the database.

Comment thread backend/src/lib/utils.js
maxAge: 15 * 24 * 60 * 60 * 1000, // 15 days in milliseconds
httpOnly: true, // prevent client side js from accessing the cookie - cross-site scripting attacks
sameSite: "strict", // prevent CSRF attacks - cross-site request forgery attacks
secure: process.env.NODE_ENV !== "development" ? false : true, // only send cookie over https in production

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Critical: secure flag logic is inverted.

The current logic sets secure: false in production and secure: true in development—the opposite of what's intended. In production, the cookie will be transmitted over plain HTTP, exposing the JWT to interception.

The condition process.env.NODE_ENV !== "development" ? false : true evaluates to:

  • Production (NODE_ENV !== "development"): false ❌
  • Development (NODE_ENV === "development"): true ❌
Proposed fix
-        secure: process.env.NODE_ENV !== "development" ? false : true, // only send cookie over https in production
+        secure: process.env.NODE_ENV === "production", // only send cookie over https in production
📝 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
secure: process.env.NODE_ENV !== "development" ? false : true, // only send cookie over https in production
secure: process.env.NODE_ENV === "production", // only send cookie over https in production
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/lib/utils.js` at line 14, The `secure` flag logic in the cookie
configuration is inverted, causing cookies to be sent over plain HTTP in
production (insecure) and HTTPS in development. In the ternary operator on line
14, swap the boolean values so that `secure` is set to true when NODE_ENV is not
"development" (production) and false when it is "development". Alternatively,
simplify the logic to `process.env.NODE_ENV !== "development"` to achieve the
correct behavior of only sending cookies over HTTPS in production.

Comment thread backend/src/server.js
Comment on lines +34 to +37
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
connectDB();
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Server accepts requests before database is connected.

connectDB() is called inside the app.listen callback, meaning the server starts accepting HTTP requests before the MongoDB connection is established. Early requests could fail with database errors.

Proposed fix: Connect to DB before starting server
-app.listen(PORT, () => {
-    console.log(`Server is running on port ${PORT}`);
-    connectDB();
-});
+connectDB().then(() => {
+    app.listen(PORT, () => {
+        console.log(`Server is running on port ${PORT}`);
+    });
+});

Or using an async IIFE:

(async () => {
    await connectDB();
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
})();
📝 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.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
connectDB();
});
connectDB().then(() => {
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/server.js` around lines 34 - 37, The server starts accepting HTTP
requests before the database connection is established because connectDB() is
called inside the app.listen callback instead of being awaited first. Move the
connectDB() invocation outside and before app.listen() by wrapping both in an
async IIFE pattern, ensuring that connectDB() is fully awaited before the
app.listen() callback executes. This guarantees the database connection is ready
before the server begins accepting requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant