Skip to content

SECURITY + AUTH: Secure auth system#236

Open
Ad1th wants to merge 3 commits into
GitMetricsLab:mainfrom
Ad1th:secure_auth_system
Open

SECURITY + AUTH: Secure auth system#236
Ad1th wants to merge 3 commits into
GitMetricsLab:mainfrom
Ad1th:secure_auth_system

Conversation

@Ad1th
Copy link
Copy Markdown

@Ad1th Ad1th commented May 14, 2026

Related Issue


Description

This pull request introduces a full-stack authentication system, implementing user login, signup, logout, and session persistence across both the backend and frontend. It also adds route protection and improves the user experience for authenticated flows. The most important changes are grouped below:

Backend Authentication & Session Management:

  • Added an isAuthenticated middleware in backend/middleware/authMiddleware.js to protect API routes.
  • Refactored backend/routes/auth.js to implement robust login logic (with error handling and user data return), a /me route for current user info, and integrated the new middleware.
  • Improved CORS configuration in backend/server.js to restrict API access to the frontend origin and updated session handling for secure authentication.

Frontend Authentication Context & Utilities:

  • Introduced AuthContext and AuthProvider in src/context/AuthContext.tsx to manage user state, authentication status, and provide login/signup/logout methods across the app.
  • Added useAuth hook in src/hooks/useAuth.ts for easy access to authentication context in components.
  • Wrapped the application in AuthProvider in src/main.tsx to enable global authentication state.

Route Protection & User Experience:

  • Created ProtectedRoute component in src/components/ProtectedRoute.tsx to restrict access to authenticated users and show a loading spinner during auth checks.
  • Updated routing in src/Routes/Router.tsx to protect the /track route using ProtectedRoute.
  • Enhanced Navbar (src/components/Navbar.tsx) to show user info and a logout button when authenticated, and handle logout logic with feedback. [1] [2] [3]

Login Flow Improvements:

  • Refactored the login page (src/pages/Login/Login.tsx) to use the new authentication context and handle navigation and error messages accordingly. [1] [2] [3]

Documentation Updates:

  • Expanded and clarified the authentication and testing setup in README.md, including backend testing instructions and contributor info. [1] [2] [3] [4] [5]

These changes collectively establish a secure, user-friendly authentication foundation for the app.

How Has This Been Tested?

Local, via postman


Type of Change

  • [This] Bug fix
  • [This]Security
  • New feature
  • Code style update
  • Breaking change
  • Documentation update

Summary by CodeRabbit

  • New Features

    • Implemented complete authentication system with login, signup, and logout functionality.
    • Added protected routes requiring user authentication to access certain pages.
    • Enhanced navigation bar with authentication-aware controls and user status display.
    • Added loading states and improved error messaging during authentication operations.
  • Documentation

    • Updated README with reorganized setup guide, expanded testing documentation, and updated contributor information.

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 14, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit 14b7a6a
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a0618b62900240007cf1386
😎 Deploy Preview https://deploy-preview-236--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

📝 Walkthrough

Walkthrough

This PR implements a complete authentication system for a full-stack application. The backend adds middleware-based request gating, refactored auth routes with structured responses, and CORS/session configuration. The frontend introduces a React context-based auth system with automatic session restoration, integrates login/signup pages with the context API, protects routes, and updates the navbar with authentication-aware UI controls.

Changes

Authentication System Implementation

Layer / File(s) Summary
Backend auth middleware
backend/middleware/authMiddleware.js
Express middleware that checks req.isAuthenticated() and returns HTTP 401 with { message: 'Unauthorized - Please log in' } for unauthenticated requests.
Backend auth route handlers
backend/routes/auth.js
Signup route pre-checks email uniqueness and returns 400/500 errors; login uses custom passport callback to handle authentication failures (500), invalid credentials (401), and session errors (500); new GET /me endpoint returns authenticated user; logout uses consistent JSON response flow.
Server initialization with secure CORS
backend/server.js
CORS now restricted to FRONTEND_URL environment variable (defaulting to http://localhost:5173) with credentials enabled; session middleware reformatted with consistent option handling.
Frontend auth context, hooks, and API client
src/utils/axiosConfig.ts, src/context/AuthContext.tsx, src/hooks/useAuth.ts, src/main.tsx
Axios client configured with credentials and VITE_BACKEND_URL; React context provides user, isAuthenticated, isLoading state and async login(), signup() (auto-logs in), logout(), and checkAuth() methods called on provider mount; useAuth hook enforces provider presence and returns typed context.
Login and Signup page integration
src/pages/Login/Login.tsx, src/pages/Signup/Signup.tsx
Pages now use useAuth hook instead of direct axios calls; Login and Signup include try/catch/finally error handling, success messaging, delayed navigation to /track, and loading state management; Signup form element updated with proper onSubmit binding and submit button reflects loading state.
Protected routes and authentication UI
src/components/ProtectedRoute.tsx, src/Routes/Router.tsx, src/components/Navbar.tsx
ProtectedRoute component gates children rendering with loading indicator and redirects unauthenticated users to /login; Router wraps /track in ProtectedRoute; Navbar conditionally renders username/logout button (authenticated) or login link (unauthenticated) with async logout handler that clears menu state and navigates home; both desktop and mobile menu sections updated.
Documentation updates
README.md
Setup guide reorganized into numbered steps with fenced command blocks; Jasmine testing section restructured with explicit coverage list, dedicated prerequisites/installation/running subsections, and test files list; contributors section updated to reference GitMetricsLab/github_tracker with new contrib.rocks image URL.

Sequence Diagrams

sequenceDiagram
  participant User as User
  participant Login as Login Page
  participant AuthContext as AuthContext
  participant Backend as Backend API
  participant ProtectedRoute as ProtectedRoute

  User->>Login: Enter credentials & submit
  Login->>AuthContext: login(email, password)
  AuthContext->>Backend: POST /api/auth/login
  Backend->>AuthContext: { user, isAuthenticated: true }
  AuthContext->>Login: Success message
  Login->>User: Navigate to /track
  
  User->>ProtectedRoute: Access /track
  ProtectedRoute->>AuthContext: Read isAuthenticated & isLoading
  alt Still loading
    ProtectedRoute->>User: Show loading screen
  else Unauthenticated
    ProtectedRoute->>User: Redirect to /login
  else Authenticated
    ProtectedRoute->>User: Render Tracker component
  end
Loading
sequenceDiagram
  participant Navbar as Navbar
  participant User as User
  participant AuthContext as AuthContext
  participant Backend as Backend API

  Navbar->>AuthContext: Read isAuthenticated & user
  
  alt Authenticated
    Navbar->>User: Show "Logged in as: username"
    Navbar->>User: Show logout button
    User->>Navbar: Click logout
    Navbar->>AuthContext: logout()
    AuthContext->>Backend: GET /api/auth/logout
    Backend->>AuthContext: Success
    AuthContext->>Navbar: Clear user & isAuthenticated
    Navbar->>User: Navigate to home
  else Unauthenticated
    Navbar->>User: Show login link
  end
Loading

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

gssoc25, level2

🐰 A fluffy auth system now guards the track,
With context and hooks, we've got your back,
Login and logout flow smooth as can be,
Protected routes keep treasures safe—here's the key!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'SECURITY + AUTH: Secure auth system' directly corresponds to the PR's main objective of implementing a comprehensive authentication system with security improvements.
Description check ✅ Passed The description covers all required template sections and provides comprehensive details about backend auth, frontend context, route protection, login flow, and documentation updates with specific file references.
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 unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

Copy link
Copy Markdown

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

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

🎉 Thank you @Ad1th for your contribution. Please make sure your PR follows https://github.com/GitMetricsLab/github_tracker/blob/main/CONTRIBUTING.md#-pull-request-guidelines

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/pages/Login/Login.tsx (1)

133-135: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix success-state message comparison mismatch.

Line 34 sets "Login successful!", but this check compares "Login successful"; success feedback will use the error style.

Suggested change
-              message === "Login successful"
+              message === "Login successful!"
🤖 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 `@src/pages/Login/Login.tsx` around lines 133 - 135, The success/error styling
conditional in Login.tsx compares message === "Login successful" but elsewhere
the component sets the message to "Login successful!" (with an exclamation),
causing successful logins to render the error style; update the comparison in
the ternary that builds the CSS class (the expression using message === "Login
successful") to match the actual success string (e.g., "Login successful!") or,
better, switch to a boolean success flag (e.g., isSuccess) used by the login
handler and evaluate that flag instead so the styling reliably reflects success
vs error.
README.md (1)

48-70: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove shell prompt prefixes in command blocks.

The command snippets include $ prefixes without output, which triggers markdownlint MD014 and hurts copy/paste usability.

Proposed fix
- $ git clone https://github.com/yourusername/github-tracker.git
+ git clone https://github.com/yourusername/github-tracker.git
...
- $ cd github-tracker
+ cd github-tracker
...
- $ npm i
- $ npm run dev
+ npm i
+ npm run dev
...
- $ npm i
- $ npm start
+ npm i
+ npm start
🤖 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 `@README.md` around lines 48 - 70, Remove the shell prompt prefixes from the
command code blocks in README.md so commands are plain and copy/paste friendly;
specifically update the git clone, cd github-tracker, npm i / npm run dev
(frontend) and npm i / npm start (backend) blocks to remove the leading "$"
characters in each line so markdownlint MD014 is satisfied and users can copy
commands directly.
🤖 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/routes/auth.js`:
- Around line 21-24: Replace all direct exposure of err.message in
backend/routes/auth.js (the res.status(500).json(...) calls that currently
include err.message) with a generic client-safe message like "Internal server
error" and move the detailed error into a server-side log (e.g.,
console.error(err) or your app logger) immediately before sending the response;
update each occurrence (the res.status(500).json(...) blocks at the shown
locations and the similar blocks around lines 31-34, 42-45, 60-63) so clients
never receive internal error text while full error details remain logged for
debugging.
- Around line 57-64: Change the logout route from a GET to a POST to avoid
state-changing operations over GET: replace router.get("/logout", ...) with
router.post("/logout", ...) and keep the existing req.logout callback logic (the
handler that checks err and returns 500 or 200). Also update any client-side
code or tests that call GET /logout to POST /logout and ensure any CSRF
middleware or authentication checks that apply to POST are applied to this route
(refer to the router.post("/logout") handler and the req.logout callback).

In `@backend/server.js`:
- Around line 27-31: The session middleware is too permissive: ensure
process.env.SESSION_SECRET is required (throw or exit early if missing) and
harden the session cookie in the session({...}) config by adding an explicit
cookie object with secure: true (only in production), httpOnly: true, sameSite:
'lax' or 'strict' as appropriate, and a sensible maxAge; also set
rolling/session expiration behavior if needed (e.g., rolling: true or
cookie.maxAge) and keep resave/saveUninitialized as false. Update the code
around session(...) and the SESSION_SECRET check so the app fails fast when
SESSION_SECRET is absent and the session() call includes the cookie security
options.

In `@README.md`:
- Around line 142-144: The contributors image in the README (<img
src="https://contrib.rocks/image?repo=GitMetricsLab/github_tracker" />) lacks
alt text; update the <img> tag to include a meaningful alt attribute (e.g.,
alt="Contributors to GitMetricsLab/github_tracker") so the image is accessible
and fixes MD045.

---

Outside diff comments:
In `@README.md`:
- Around line 48-70: Remove the shell prompt prefixes from the command code
blocks in README.md so commands are plain and copy/paste friendly; specifically
update the git clone, cd github-tracker, npm i / npm run dev (frontend) and npm
i / npm start (backend) blocks to remove the leading "$" characters in each line
so markdownlint MD014 is satisfied and users can copy commands directly.

In `@src/pages/Login/Login.tsx`:
- Around line 133-135: The success/error styling conditional in Login.tsx
compares message === "Login successful" but elsewhere the component sets the
message to "Login successful!" (with an exclamation), causing successful logins
to render the error style; update the comparison in the ternary that builds the
CSS class (the expression using message === "Login successful") to match the
actual success string (e.g., "Login successful!") or, better, switch to a
boolean success flag (e.g., isSuccess) used by the login handler and evaluate
that flag instead so the styling reliably reflects success vs error.
🪄 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: a06857f5-4334-4207-b7e0-4402bc56eab3

📥 Commits

Reviewing files that changed from the base of the PR and between 56e17a3 and 14b7a6a.

📒 Files selected for processing (13)
  • README.md
  • backend/middleware/authMiddleware.js
  • backend/routes/auth.js
  • backend/server.js
  • src/Routes/Router.tsx
  • src/components/Navbar.tsx
  • src/components/ProtectedRoute.tsx
  • src/context/AuthContext.tsx
  • src/hooks/useAuth.ts
  • src/main.tsx
  • src/pages/Login/Login.tsx
  • src/pages/Signup/Signup.tsx
  • src/utils/axiosConfig.ts

Comment thread backend/routes/auth.js
Comment on lines +21 to +24
res
.status(500)
.json({ message: "Error creating user", error: err.message });
}
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

Avoid returning raw internal error messages to clients.

These responses expose err.message, which can leak backend internals. Return a generic client message and log details server-side.

Suggested change
-    res
-      .status(500)
-      .json({ message: "Error creating user", error: err.message });
+    console.error("Signup error:", err);
+    res.status(500).json({ message: "Error creating user" });
-      return res
-        .status(500)
-        .json({ message: "Login error", error: err.message });
+      console.error("Login error:", err);
+      return res.status(500).json({ message: "Login error" });
-        return res
-          .status(500)
-          .json({ message: "Session error", error: err.message });
+        console.error("Session error:", err);
+        return res.status(500).json({ message: "Session error" });
-      return res
-        .status(500)
-        .json({ message: "Logout failed", error: err.message });
+      console.error("Logout error:", err);
+      return res.status(500).json({ message: "Logout failed" });

Also applies to: 31-34, 42-45, 60-63

🤖 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/routes/auth.js` around lines 21 - 24, Replace all direct exposure of
err.message in backend/routes/auth.js (the res.status(500).json(...) calls that
currently include err.message) with a generic client-safe message like "Internal
server error" and move the detailed error into a server-side log (e.g.,
console.error(err) or your app logger) immediately before sending the response;
update each occurrence (the res.status(500).json(...) blocks at the shown
locations and the similar blocks around lines 31-34, 42-45, 60-63) so clients
never receive internal error text while full error details remain logged for
debugging.

Comment thread backend/routes/auth.js
Comment on lines 57 to +64
router.get("/logout", (req, res) => {

req.logout((err) => {

if (err)
return res.status(500).json({ message: 'Logout failed', error: err.message });
else
res.status(200).json({ message: 'Logged out successfully' });
});
req.logout((err) => {
if (err)
return res
.status(500)
.json({ message: "Logout failed", error: err.message });
else res.status(200).json({ message: "Logged out successfully" });
});
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

Use POST /logout instead of GET /logout.

Logout mutates server session state and should not be a GET endpoint. Keeping it as GET makes cross-site triggering easier and weakens CSRF posture.

Suggested change
-router.get("/logout", (req, res) => {
+router.post("/logout", (req, res) => {
   req.logout((err) => {
🤖 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/routes/auth.js` around lines 57 - 64, Change the logout route from a
GET to a POST to avoid state-changing operations over GET: replace
router.get("/logout", ...) with router.post("/logout", ...) and keep the
existing req.logout callback logic (the handler that checks err and returns 500
or 200). Also update any client-side code or tests that call GET /logout to POST
/logout and ensure any CSRF middleware or authentication checks that apply to
POST are applied to this route (refer to the router.post("/logout") handler and
the req.logout callback).

Comment thread backend/server.js
Comment on lines +27 to +31
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
}));
}),
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

Harden session configuration for authenticated deployments.

Add explicit cookie security settings and fail fast when SESSION_SECRET is missing; current config is too permissive for a security-focused auth flow.

Suggested change
+if (!process.env.SESSION_SECRET) {
+  throw new Error("SESSION_SECRET is required");
+}
+
 app.use(
   session({
     secret: process.env.SESSION_SECRET,
     resave: false,
     saveUninitialized: false,
+    cookie: {
+      httpOnly: true,
+      sameSite: "lax",
+      secure: process.env.NODE_ENV === "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
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
}));
}),
if (!process.env.SESSION_SECRET) {
throw new Error("SESSION_SECRET is required");
}
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "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/server.js` around lines 27 - 31, The session middleware is too
permissive: ensure process.env.SESSION_SECRET is required (throw or exit early
if missing) and harden the session cookie in the session({...}) config by adding
an explicit cookie object with secure: true (only in production), httpOnly:
true, sameSite: 'lax' or 'strict' as appropriate, and a sensible maxAge; also
set rolling/session expiration behavior if needed (e.g., rolling: true or
cookie.maxAge) and keep resave/saveUninitialized as false. Update the code
around session(...) and the SESSION_SECRET check so the app fails fast when
SESSION_SECRET is absent and the session() call includes the cookie security
options.

Comment thread README.md
Comment on lines +142 to +144
<a href="https://github.com/GitMetricsLab/github_tracker/graphs/contributors">
<img src="https://contrib.rocks/image?repo=GitMetricsLab/github_tracker" />
</a>
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

Add alt text to the contributors image.

The image is missing alt text (MD045), which is an accessibility gap in documentation.

Proposed fix
-  <img src="https://contrib.rocks/image?repo=GitMetricsLab/github_tracker" />
+  <img
+    src="https://contrib.rocks/image?repo=GitMetricsLab/github_tracker"
+    alt="Contributors to GitMetricsLab/github_tracker"
+  />
📝 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
<a href="https://github.com/GitMetricsLab/github_tracker/graphs/contributors">
<img src="https://contrib.rocks/image?repo=GitMetricsLab/github_tracker" />
</a>
<a href="https://github.com/GitMetricsLab/github_tracker/graphs/contributors">
<img
src="https://contrib.rocks/image?repo=GitMetricsLab/github_tracker"
alt="Contributors to GitMetricsLab/github_tracker"
/>
</a>
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)

[warning] 143-143: Images should have alternate text (alt text)

(MD045, no-alt-text)

🤖 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 `@README.md` around lines 142 - 144, The contributors image in the README (<img
src="https://contrib.rocks/image?repo=GitMetricsLab/github_tracker" />) lacks
alt text; update the <img> tag to include a meaningful alt attribute (e.g.,
alt="Contributors to GitMetricsLab/github_tracker") so the image is accessible
and fixes MD045.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant