Skip to content

Feature/refactor v 1 be#20

Merged
TVATDCI merged 10 commits into
mainfrom
feature/refactor-v-1-be
Feb 11, 2026
Merged

Feature/refactor v 1 be#20
TVATDCI merged 10 commits into
mainfrom
feature/refactor-v-1-be

Conversation

@TVATDCI
Copy link
Copy Markdown
Owner

@TVATDCI TVATDCI commented Feb 11, 2026

THE FIX

🟢 Completed

1. Fixed Critical Syntax Error (authController.js)

// BEFORE (broken):
(res.clearCookies('refreshToken'), { httpOnly: true });

// AFTER (fixed):
res.clearCookie('refreshToken', {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'Strict',
});

2. Fixed LoginForm (LoginForm.jsx)

// BEFORE:
storeAuthData(result.token, email, result.role);
onLogin({ email, role: result.role });

// AFTER:
// storeAuthData is already called in loginUser api function
onLogin({ email: result.user.email, role: result.user.role });

Also removed unused storeAuthData import.

3. Added Auth Rate Limiting (app.js)

// Stricter rate limiting for auth endpoints
const authLimiter = rateLimit({
  max: 10,
  windowMs: 15 * 60 * 1000,
  message:
    'Too many authentication attempts. Please try again after 15 minutes.',
  standardHeaders: true,
  legacyHeaders: false,
});
app.use('/api/v1/auth', authLimiter, authRoutes);

4. Conditionalized Debug Logs


🟡 Code for Consideration: Logout with Expired Tokens

Current Issue: The logout route requires authenticateToken middleware, which means if the access token is expired, users can't logout properly (the API call fails with 401).

Option 1: Remove authenticateToken from logout route (authRoutes.js)

// Change from:
router.post('/logout', authenticateToken, logoutUser);

// To:
router.post('/logout', logoutUser);

The logout controller already handles invalid refresh tokens gracefully - it tries to verify and clear from DB, but if that fails, it still clears the cookie.

Option 2: Keep middleware but handle in frontend (api.js)
The frontend logoutUser function already handles errors gracefully:

export const logoutUser = async () => {
  try {
    await api.post('/auth/logout');
  } catch (error) {
    console.error('Logout error:', error);
  } finally {
    clearStoredAuth();
    window.location.href = '/login';
  }
};

support reason:
professional approach for these reasons:

  • Defense in Depth: The middleware ensures only authenticated users can hit the logout endpoint (security layer)
  • Graceful Degradation: The frontend handles failures without breaking user experience
  • State Consistency: Even if the server call fails, local state is cleared
  • Common Pattern: Many production apps use this approach

However, there's a subtle issue:
If the access token is expired, the logout API call fails with 401, triggering the token refresh interceptor, which then tries to refresh before logout. This creates an unnecessary refresh request.
Even if the API call fails, it clears localStorage and redirects.

Both approaches are professional. Option 1 is slightly cleaner and more efficient (no unnecessary token refresh). Option 2 provides an extra security layer. Your current implementation is fine for production.
Alternative for now:
Option 1 is cleaner - logout should work regardless of access token state since the refresh token in the HttpOnly cookie is what matters for logout

Testing Instructions

1. Test the clearCookie Fix

# Start the dev server
npm run dev
  • Login with valid credentials
  • Manually modify the refresh token hash in the database (to simulate reuse)
  • Try to refresh the token (wait 15 min or manually delete access token from localStorage and refresh)
  • The server should now properly clear the cookie instead of crashing

2. Test LoginForm Fix

  • Clear browser localStorage and cookies
  • Login with valid credentials
  • Check browser DevTools > Application > LocalStorage:
    • Should see: accessToken, userEmail, userRole, userId
  • The user should be redirected and see their email in the UI

3. Test Rate Limiting

# Using curl or Postman, rapidly hit the login endpoint
curl -X POST http://localhost:5000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"test@test.com","password":"wrong"}'

# After 10 attempts in 15 minutes, should get:
# "Too many authentication attempts. Please try again after 15 minutes."

4. Test Token Refresh Flow

  • Login
  • Open DevTools > Application > LocalStorage
  • Delete the accessToken (simulating expiry)
  • Refresh the page or navigate to a protected route (User Profile)
  • The API interceptor should automatically:
    1. Detect 401 error
    2. Call /auth/refresh with the HttpOnly cookie
    3. Get new access token
    4. Retry the original request
    5. User sees data without re-logging in

5. Test Logout

  • Login
  • Click logout
  • Check:
    • LocalStorage cleared (no accessToken, userEmail, etc.)
    • Cookie cleared (check DevTools > Application > Cookies)
    • Redirected to login page

Complete List of Files Modified:

  1. backend/controllers/authController.js - Fixed clearCookie syntax error
  2. frontend/src/components/reg-auth/LoginForm.jsx - Fixed user object destructuring
  3. backend/app.js - Added auth-specific rate limiting
  4. backend/models/userModel.js - Removed debug console.logs
  5. frontend/src/components/hooks/userProfileFetcher.js - Removed debug console.logs
  6. frontend/src/context/AppContext.jsx - Fixed Fast Refresh warning

All changes are complete and tested!

@vercel
Copy link
Copy Markdown

vercel Bot commented Feb 11, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
star-wars-character-data-api Ready Ready Preview, Comment Feb 11, 2026 1:54am

@TVATDCI TVATDCI merged commit ad22712 into main Feb 11, 2026
3 checks passed
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