Skip to content

Extend session TTL and refresh on access for dashboard - #78

Merged
willianpm merged 2 commits into
masterfrom
fix/76-user-session-timeout
May 18, 2026
Merged

Extend session TTL and refresh on access for dashboard#78
willianpm merged 2 commits into
masterfrom
fix/76-user-session-timeout

Conversation

@willianpm

@willianpm willianpm commented May 18, 2026

Copy link
Copy Markdown
Owner

This pull request introduces improved session management and observability for the dashboard authentication flow, along with enhanced error handling and configuration flexibility. The main focus is on allowing configurable session duration, providing clearer feedback to users when their session expires or access is revoked, and improving logging for authentication events. Documentation and test coverage have also been updated to reflect these changes.

Session management and configuration:

  • Added a new environment variable DASHBOARD_SESSION_MAX_AGE_DAYS to configure dashboard session duration (default: 30 days), updating all relevant .env example files and documentation to include this option. Session duration now affects both cookie expiration and Redis TTL, and is set as a rolling session. [1] [2] [3] [4] [5] [6] [7]

Authentication error handling and user feedback:

  • Improved backend error responses by adding a reason field to indicate specific session issues (e.g., expired, invalid_session, no_access, missing_session), and updated the frontend to display user-friendly messages based on these reasons. [1] [2] [3] [4] [5] [6]

Logging and observability:

  • Introduced structured logging for authentication events (login, logout, session refresh, permission denials) with contextual information such as IP, session ID, user ID, and guild ID, using a new logger utility and helper functions for formatting log messages. [1] [2] [3] [4] [5] [6]

Testing:

  • Enhanced test coverage for session expiry and touch behavior, including tests for missing or expired sessions and validation of session rolling updates. [1] [2] [3] [4]

Documentation and environment consistency:

  • Updated README.md and related documentation to clarify the new session duration variable and ensure environment variable tables are up to date and consistently formatted. [1] [2]

These changes improve the reliability, security, and transparency of dashboard authentication, making it easier to configure, debug, and use.

Summary by CodeRabbit

  • New Features

    • Dashboard sessions now support configurable maximum age (default 30 days) via environment configuration.
    • Enhanced session error reporting with specific error reasons and improved logging.
  • Documentation

    • Updated setup guides to document the new session configuration variable.

Review Change Stack

@willianpm willianpm self-assigned this May 18, 2026
@willianpm willianpm linked an issue May 18, 2026 that may be closed by this pull request
@coderabbitai

coderabbitai Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@willianpm has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 29 minutes and 4 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3b0140f6-1382-473e-8571-e1bb56df0c6c

📥 Commits

Reviewing files that changed from the base of the PR and between 0594fb7 and 95e7ee1.

📒 Files selected for processing (3)
  • dashboard/api/auth.js
  • dashboard/frontend/src/app/context/AuthContext.tsx
  • src/core/express-app.js
📝 Walkthrough

Walkthrough

This PR introduces configurable dashboard session lifetime via a new DASHBOARD_SESSION_MAX_AGE_DAYS environment variable (defaulting to 30 days), adds structured auth logging and reason-based error codes to the backend auth API, and updates the frontend to resolve session errors into user-facing messages based on specific failure reasons.

Changes

Dashboard Session Lifetime & Auth Error Handling

Layer / File(s) Summary
Session lifetime configuration and setup
src/core/express-app.js, .env.example, .env.staging.example, README.md, dashboard/README.md, docs/development/SETUP.md, docs/technical/setup-discord.md
New DASHBOARD_SESSION_MAX_AGE_DAYS environment variable is documented across all configuration examples and setup guides with a default of 30 days. Core express app adds a resolveDashboardSessionDays() helper to parse and validate the env var, then computes Redis TTL and Express cookie maxAge dynamically instead of using fixed values.
Backend auth API logging and reason codes
dashboard/api/auth.js
Dashboard auth API adds structured logging via logger utility. refreshDashboardAccess now classifies auth failures into specific reason codes (missing_session, expired, invalid_session, no_access), emits logger.warn entries, and calls req.session.touch() to refresh active sessions. Route handlers replace console.* logging with logger.*, and the /me endpoint response schema includes the new reason field alongside error and status.
Frontend auth context error resolution
dashboard/frontend/src/app/context/AuthContext.tsx
AuthContext introduces SESSION_ERROR_MESSAGES mapping and resolveSessionErrorMessage() helper to convert backend reason codes into user-facing toast messages. AuthProvider now tracks prior authentication state via useRef to conditionally display toasts. refreshAuth() invokes the new resolver and clears user state and auth status on session failure.
Auth tests and assertions
dashboard/tests/dashboard-auth.test.js
Test mocks now verify that session.touch() is called during successful /api/auth/me requests. Test assertions updated to check specific reason codes (missing_session, expired) instead of generic error truthy checks. New test case verifies the expired reason when a cookie is present but session is missing.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant AuthAPI as /api/auth/me
  participant SessionMgr as refreshDashboardAccess
  
  Client->>AuthAPI: GET /me
  AuthAPI->>SessionMgr: check session validity
  alt session valid
    SessionMgr->>SessionMgr: session.touch()
    SessionMgr-->>AuthAPI: ok: true
  else missing/expired
    SessionMgr->>SessionMgr: classify reason
    SessionMgr-->>AuthAPI: ok: false, reason code
  end
  AuthAPI-->>Client: response with reason
Loading
sequenceDiagram
  participant App
  participant AuthProvider
  participant ToastUI
  
  App->>AuthProvider: refreshAuth()
  AuthProvider->>AuthProvider: fetch /api/auth/me
  alt auth success
    AuthProvider->>AuthProvider: set wasAuthenticatedRef = true
    AuthProvider-->>App: status: authenticated
  else auth failure
    AuthProvider->>AuthProvider: resolveSessionErrorMessage
    alt message exists
      AuthProvider->>ToastUI: display error toast
    end
    AuthProvider->>AuthProvider: clear user state
    AuthProvider-->>App: status: unauthenticated
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • willianpm/LittleBoatPoll#54: Introduces initial /me and /logout endpoint coverage in dashboard auth tests that this PR extends with reason field assertions and session touch verification.

Poem

🐰 A session that lasts just as long as you say,
With reasons that tell what went wrong on the way,
No mystery errors to make users frown,
Just clear session tales, from the top of the town!
~CodeRabbit 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: implementing configurable, rolling dashboard sessions with extended TTL.
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
  • Commit unit tests in branch fix/76-user-session-timeout

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: 2

Caution

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

⚠️ Outside diff range comments (2)
dashboard/frontend/src/app/context/AuthContext.tsx (2)

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

Reset auth-history ref on explicit logout.

After Line 143-145, wasAuthenticatedRef.current remains true, which can trigger an incorrect "sessão expirou" toast on a later refresh after a deliberate logout.

Proposed fix
   const logout = useCallback(async () => {
     try {
       await fetch('/api/auth/logout', {
         method: 'POST',
         credentials: 'include',
         headers: {
           Accept: 'application/json',
         },
       });
     } finally {
       setUser(null);
       setStatus('unauthenticated');
+      wasAuthenticatedRef.current = false;
       navigate('/login', { replace: true });
     }
   }, [navigate]);
🤖 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 `@dashboard/frontend/src/app/context/AuthContext.tsx` around lines 133 - 146,
In the logout function (logout) reset the wasAuthenticatedRef current value to
false as part of the explicit logout flow so it doesn't later trigger the
"sessão expirou" toast; update wasAuthenticatedRef.current before calling
setUser, setStatus or navigate (i.e., on explicit logout set
wasAuthenticatedRef.current = false) so any subsequent refresh checks treat this
as an intentional logout rather than an expired session.

107-127: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle /api/auth/me request failures to avoid a stuck loading state.

Line 110 can throw on network/runtime fetch failures, and refreshAuth currently never recovers state in that path.

Proposed fix
   const refreshAuth = useCallback(async () => {
     setStatus('loading');
-
-    const payload = await fetchAuthSession();
-    if (payload.authenticated && payload.user) {
-      setUser(payload.user);
-      setStatus('authenticated');
-      wasAuthenticatedRef.current = true;
-      return true;
-    }
-
-    const sessionMessage = resolveSessionErrorMessage(payload, wasAuthenticatedRef.current);
-    if (sessionMessage) {
-      toast.error(sessionMessage);
-    }
-
-    setUser(null);
-    setStatus('unauthenticated');
-    wasAuthenticatedRef.current = false;
-    return false;
+    try {
+      const payload = await fetchAuthSession();
+      if (payload.authenticated && payload.user) {
+        setUser(payload.user);
+        setStatus('authenticated');
+        wasAuthenticatedRef.current = true;
+        return true;
+      }
+
+      const sessionMessage = resolveSessionErrorMessage(payload, wasAuthenticatedRef.current);
+      if (sessionMessage) {
+        toast.error(sessionMessage);
+      }
+    } catch {
+      if (wasAuthenticatedRef.current) {
+        toast.error('Não foi possível validar sua sessão. Tente novamente.');
+      }
+    }
+
+    setUser(null);
+    setStatus('unauthenticated');
+    wasAuthenticatedRef.current = false;
+    return false;
   }, []);
🤖 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 `@dashboard/frontend/src/app/context/AuthContext.tsx` around lines 107 - 127,
refreshAuth currently awaits fetchAuthSession() without error handling, so
network/runtime exceptions can leave the component stuck in 'loading'; wrap the
fetchAuthSession call in a try/catch (or add a finally) inside refreshAuth to
catch any thrown errors, log or toast the error, ensure setUser(null),
setStatus('unauthenticated'), wasAuthenticatedRef.current = false are executed
on error, and return false so callers don't remain waiting; update references
inside the catch/finally to the existing functions/refs (refreshAuth,
fetchAuthSession, setUser, setStatus, wasAuthenticatedRef,
resolveSessionErrorMessage, toast.error).
🤖 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 `@dashboard/api/auth.js`:
- Around line 21-24: The current hasDashboardCookie helper (and any other checks
using cookieHeader.includes('dashboard.sid=')) can false-positive; instead parse
the cookie header into semicolon-separated pairs, trim each pair, split on the
first '=' and compare the cookie name exactly to 'dashboard.sid' (return true if
any match, false otherwise), handling missing headers safely; update
hasDashboardCookie and the other occurrence that uses includes('dashboard.sid=')
to use this exact-key parsing logic.

In `@src/core/express-app.js`:
- Around line 18-27: The parsing currently allows arbitrary floats (rawValue ->
parsed) which can become tiny fractions and lead to maxAge 0; change the
normalization to coerce to a safe positive integer by computing const days =
Math.floor(Number(rawValue)) (or Number.isFinite(parsed) && Math.floor(parsed)),
then enforce days >= 1 and return DEFAULT_DASHBOARD_SESSION_DAYS if not valid;
also update the code path that derives maxAge milliseconds (where
DASHBOARD_SESSION_MAX_AGE_DAYS is used to compute maxAge) to multiply by this
integer days value so you never get 0 ms from tiny floats; reference symbols:
rawValue, parsed (replace with days), DEFAULT_DASHBOARD_SESSION_DAYS, and the
maxAge computation that uses DASHBOARD_SESSION_MAX_AGE_DAYS.

---

Outside diff comments:
In `@dashboard/frontend/src/app/context/AuthContext.tsx`:
- Around line 133-146: In the logout function (logout) reset the
wasAuthenticatedRef current value to false as part of the explicit logout flow
so it doesn't later trigger the "sessão expirou" toast; update
wasAuthenticatedRef.current before calling setUser, setStatus or navigate (i.e.,
on explicit logout set wasAuthenticatedRef.current = false) so any subsequent
refresh checks treat this as an intentional logout rather than an expired
session.
- Around line 107-127: refreshAuth currently awaits fetchAuthSession() without
error handling, so network/runtime exceptions can leave the component stuck in
'loading'; wrap the fetchAuthSession call in a try/catch (or add a finally)
inside refreshAuth to catch any thrown errors, log or toast the error, ensure
setUser(null), setStatus('unauthenticated'), wasAuthenticatedRef.current = false
are executed on error, and return false so callers don't remain waiting; update
references inside the catch/finally to the existing functions/refs (refreshAuth,
fetchAuthSession, setUser, setStatus, wasAuthenticatedRef,
resolveSessionErrorMessage, toast.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: 84b3bf60-c716-42a8-a921-f58d38f09491

📥 Commits

Reviewing files that changed from the base of the PR and between c87172e and 0594fb7.

📒 Files selected for processing (10)
  • .env.example
  • .env.staging.example
  • README.md
  • dashboard/README.md
  • dashboard/api/auth.js
  • dashboard/frontend/src/app/context/AuthContext.tsx
  • dashboard/tests/dashboard-auth.test.js
  • docs/development/SETUP.md
  • docs/technical/setup-discord.md
  • src/core/express-app.js

Comment thread dashboard/api/auth.js
Comment thread src/core/express-app.js
@willianpm
willianpm merged commit 06a3a8d into master May 18, 2026
4 checks passed
@willianpm
willianpm deleted the fix/76-user-session-timeout branch May 18, 2026 19:49
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.

Bug: users are being logged out after some time

1 participant