Skip to content

fix(web): resolve admin redirect and 401 errors, improve test coverag… - #42

Merged
pramodnarayana merged 2 commits into
developmentfrom
fix/admin-redirect-and-web-tests
Feb 1, 2026
Merged

pramodnarayana merged 2 commits into
developmentfrom
fix/admin-redirect-and-web-tests

Conversation

@pramodnarayana

@pramodnarayana pramodnarayana commented Jan 31, 2026 •

Copy link
Copy Markdown
Owner

…e configuration

Summary by CodeRabbit

  • New Features
    • Implemented email-based login functionality with enhanced session management and automatic token refresh.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 31, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The changes refactor the login authentication flow to use an email-based sign-in method via authClient.signIn.email, followed by fetching an enriched session from /auth/refresh-session. The API client signature is updated to support optional tokens and cookie credentials. Test infrastructure and environment variable handling are adjusted accordingly.

Changes

Cohort / File(s) Summary
Login Flow Updates
apps/web/src/modules/identity/pages/LoginPage.tsx, apps/web/src/modules/identity/pages/LoginPage.spec.tsx
Replaces login flow with two-step process: call authClient.signIn.email, then fetch enriched session from /auth/refresh-session. Validates enriched data and maps to AuthContext state. Tests updated with default mocks for authClient.signIn.email and assertions for both successful and failed login paths.
API Client Updates
apps/web/src/shared/lib/api.ts
Changes authorizedFetch signature from (token, endpoint, options) to (endpoint, options, token?), making token optional. Adds credentials: 'include', normalizes header handling, and includes production-only validation for API_URL.
Test Infrastructure
apps/web/src/setupTests.ts, apps/web/vitest.config.ts
Adds new test setup file importing testing-library/jest-dom. Updates vitest configuration to use jsdom environment, references new setupTests.ts, enables coverage reporting, and moves VITE_API_URL to test env block.
Configuration
apps/web/src/app/providers/data-provider.ts
Relaxes API_URL validation to default to empty string in non-production environments; only throws in production when API_URL is falsy.

Sequence Diagram

sequenceDiagram
    participant User
    participant LoginPage
    participant authClient
    participant API as /auth/refresh-session
    participant AuthContext

    User->>LoginPage: Enter email & password
    LoginPage->>authClient: authClient.signIn.email(email, password)
    authClient-->>LoginPage: {success, user?, session?}
    alt Email sign-in succeeds
        LoginPage->>API: fetch /auth/refresh-session<br/>(credentials: include)
        API-->>LoginPage: {user, session.token}
        LoginPage->>LoginPage: Validate enriched data
        LoginPage->>AuthContext: setAuthState({accessToken, user})
        LoginPage->>User: Navigate to /dashboard or admin
    else Email sign-in fails
        LoginPage->>User: Display error message
    end
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly Related PRs

Poem

🐰 A hop through auth's new golden door,
Email and session, enriched and more,
Token credentials now flow with grace,
Permissions guide us to our place,
Login's dance becomes clear! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title describes the main changes: fixing admin redirect and 401 errors, and improving test coverage. These align with the core modifications in LoginPage, auth flow refactoring, and test configuration updates.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/admin-redirect-and-web-tests

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

Caution

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

⚠️ Outside diff range comments (1)
apps/web/src/modules/identity/pages/LoginPage.spec.tsx (1)

31-33: ⚠️ Potential issue | 🟡 Minor

Move global fetch mock to beforeEach and clean up with vi.unstubAllGlobals().
The module-scoped globalThis.fetch = vi.fn() at line 32 lacks proper cleanup. Currently, vi.clearAllMocks() only clears call history but does not restore the global—it should be moved to beforeEach using vi.stubGlobal, with vi.unstubAllGlobals() in afterEach for proper isolation.

🔧 Suggested changes
-// Setup global fetch mock
-globalThis.fetch = vi.fn();
 beforeEach(() => {
     vi.clearAllMocks();
+    vi.stubGlobal('fetch', vi.fn());
     // Stub VITE_API_URL
     vi.stubEnv('VITE_API_URL', 'http://test-api.com');
 afterEach(() => {
     vi.unstubAllEnvs();
+    vi.unstubAllGlobals();
     Object.defineProperty(globalThis, 'location', {
         value: originalLocation,
         writable: true,
         configurable: true
     });
 });
🤖 Fix all issues with AI agents
In `@apps/web/src/modules/identity/pages/LoginPage.tsx`:
- Around line 87-89: In LoginPage remove the two client-side console.log calls
that print userPermissions and permission checks (the lines referencing
userPermissions and Resources.ADMIN_DASHBOARD / Actions.VIEW); instead either
delete them or replace with a non-client log path (e.g., send to a server-side
audit/log endpoint or use a dev-only logger gated by an explicit environment
flag). Update any tests or references expecting those console outputs. Ensure no
sensitive permission data is emitted to the browser console.
- Around line 74-90: Check enrichedData before setting auth state: verify
enrichedData.user exists and enrichedData.session?.token is present in the
LoginPage flow, and if either is missing fail fast (throw or return an error and
avoid calling setAuthState). Use guards around rawUser before accessing
rawUser.permissions (or default to an empty array) to prevent accessing
properties on undefined, and ensure the code path that calls hasPermission only
runs after these validations; include a clear error/log message and abort the
login continuation when validation fails.

In `@apps/web/src/shared/lib/api.ts`:
- Around line 12-15: The current spread of options.headers into the headers
Record is unsafe because RequestInit.headers can be Headers, string[][], or
Record<string,string>; replace that logic by normalizing headers into a Headers
instance (e.g., new Headers(options.headers)) and then ensure 'Content-Type':
'application/json' is set if not present; update the fetch call to pass this
Headers instance (or its plain object if needed) instead of the spread object.
Locate and change code around the headers variable and the fetch call that uses
options.headers so it constructs and uses the safe Headers object and preserves
all header forms.

In `@apps/web/vite.config.ts`:
- Around line 35-44: Remove the dead Vitest test/coverage configuration block
(the test: { ... } object) from vite.config.ts so Vitest loads only
vitest.config.ts; then fix vitest.config.ts by defining __dirname before it's
used (replace the raw __dirname usage with a computed value using
fileURLToPath(import.meta.url) and path.dirname) — use the same pattern as in
vite.config.ts (import or reference fileURLToPath and path, compute const
__filename = fileURLToPath(import.meta.url); const __dirname =
path.dirname(__filename)) to ensure __dirname is defined for the code that
references it.

Comment thread apps/web/src/modules/identity/pages/LoginPage.tsx
Comment thread apps/web/src/modules/identity/pages/LoginPage.tsx Outdated
Comment thread apps/web/src/shared/lib/api.ts Outdated
Comment thread apps/web/vite.config.ts Outdated
Comment on lines +35 to +44
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/setupTests.ts',
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
include: ['src/**/*.{ts,tsx}'],
exclude: ['src/**/*.spec.{ts,tsx}', 'src/setupTests.ts', 'src/**/index.ts', 'src/shared/components/ui/*.tsx'],
},

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find package.json and check test:cov script
echo "=== Finding package.json and test:cov script ==="
find . -name package.json -path "*/apps/web/*" | head -1 | while read pkg; do
  echo "Found: $pkg"
  grep -A2 -B2 'test:cov' "$pkg" || echo "No test:cov found"
done

echo -e "\n=== Checking for config files in apps/web ==="
fd -a '\(vite|vitest\)\.config\.' apps/web/

echo -e "\n=== Reading vite.config.ts ==="
if [ -f apps/web/vite.config.ts ]; then
  cat -n apps/web/vite.config.ts
fi

echo -e "\n=== Reading vitest.config.ts ==="
if [ -f apps/web/vitest.config.ts ]; then
  cat -n apps/web/vitest.config.ts
fi

Repository: pramodnarayana/nexiom

Length of output: 2869


🏁 Script executed:

#!/bin/bash
# Check if __dirname is defined in vitest.config.ts
echo "=== Checking vitest.config.ts for __dirname ==="
head -15 apps/web/vitest.config.ts | grep -E 'import|__dirname|__filename'

Repository: pramodnarayana/nexiom

Length of output: 276


Remove unused test config from vite.config.ts; fix missing __dirname in vitest.config.ts.

The test:cov command runs vitest run --coverage, which loads vitest.config.ts exclusively. The test/coverage block in vite.config.ts (lines 35-44) is dead code and should be removed. Additionally, vitest.config.ts uses __dirname on line 10 without defining it—in ES modules, you must define it using fileURLToPath(import.meta.url) and path.dirname(), as shown in vite.config.ts.

🤖 Prompt for AI Agents
In `@apps/web/vite.config.ts` around lines 35 - 44, Remove the dead Vitest
test/coverage configuration block (the test: { ... } object) from vite.config.ts
so Vitest loads only vitest.config.ts; then fix vitest.config.ts by defining
__dirname before it's used (replace the raw __dirname usage with a computed
value using fileURLToPath(import.meta.url) and path.dirname) — use the same
pattern as in vite.config.ts (import or reference fileURLToPath and path,
compute const __filename = fileURLToPath(import.meta.url); const __dirname =
path.dirname(__filename)) to ensure __dirname is defined for the code that
references it.

@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: 0

Caution

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

⚠️ Outside diff range comments (1)
apps/web/src/modules/identity/pages/LoginPage.tsx (1)

132-144: 🧹 Nitpick | 🔵 Trivial

Consider user feedback for social login errors.

The Google sign-in error handling logs to console and sets a generic error, but console.error on Line 141 exposes error details in the browser console. For consistency with the PR objective of removing console.logs, consider removing or replacing with structured error handling.

♻️ Suggested improvement
                         } catch (error) {
-                            console.error('Social login error', error);
                             setError('Failed to initiate Google login');
                         }

@pramodnarayana
pramodnarayana merged commit 0e9c6f6 into development Feb 1, 2026
2 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