Skip to content

fix(ui): handle auth/session errors using HTTP semantics - #339

Open
VarshiniGunti wants to merge 4 commits into
PSMRI:mainfrom
VarshiniGunti:issue-114-api-status-ui-handling
Open

fix(ui): handle auth/session errors using HTTP semantics#339
VarshiniGunti wants to merge 4 commits into
PSMRI:mainfrom
VarshiniGunti:issue-114-api-status-ui-handling

Conversation

@VarshiniGunti

@VarshiniGunti VarshiniGunti commented May 5, 2026

Copy link
Copy Markdown
Contributor

📋 Description

JIRA ID: N/A (GitHub issue #114)

This PR updates MMU-UI to correctly consume REST-style HTTP error responses (4xx/5xx) instead of relying on side-effect navigation or opaque error objects.

What changed

  1. Auth guard behavior corrected
  • Updated AuthGuard.canActivate() to return explicit router-compatible values:
    • true for valid session response
    • UrlTree('/login') for invalid/expired session
  • Replaced side-effect-based router.navigate() flow with map(...) return logic.
  • Added catchError(...) fallback to route to login via UrlTree on HTTP errors.
  1. Login error handling aligned with HTTP semantics
  • Updated login error callback to process HttpErrorResponse.
  • Added status-based error message mapping for:
    • 400, 401, 403, 404, 409, 500
  • Preserved API-provided errorMessage when available.
  • Ensures users get consistent, meaningful feedback for real HTTP failures.

Motivation

Issue #114 requires UI to handle real HTTP status codes once backend endpoints stop returning 200 for all outcomes.
This PR makes authentication/session and login flows robust against 4xx/5xx semantics and removes route activation race behavior.


✅ Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • New feature (non-breaking change which adds functionality)
  • 🔥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 🛠 Refactor (change that is neither a fix nor a new feature)
  • ⚙️ Config change (configuration file or build script updates)
  • 📚 Documentation (updates to docs or readme)
  • 🧪 Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • 🚀 Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Validation performed

  • Verified canActivate now returns boolean | UrlTree and no longer depends on router.navigate() side effects.
  • Verified login flow handles HttpErrorResponse and displays status-aware messages.
  • Confirmed session-invalid/error paths redirect to /login consistently through guard return values.
  • Kept changes intentionally scoped to auth/session and login flow to reduce regression risk.

Linked scope

  • This PR is the MMU-UI half of issue #114 and pairs with the MMU-API PR that introduces proper backend HTTP status responses.

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of session validation errors by redirecting to the login screen when validation fails.
    • Improved login error messages by showing a clear, relevant message instead of raw error details.
    • Added a fallback message when no specific error information is available.

@coderabbitai

coderabbitai Bot commented May 5, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

AuthGuard now redirects session-validation errors to /login. The login component now displays a usable nested or top-level error message, with a fallback when no message exists.

Changes

Authentication Error Handling

Layer / File(s) Summary
Session validation redirect
src/app/app-modules/core/services/auth-guard.service.ts
The authentication guard catches session-validation errors and returns a router URL tree for /login.
Login error message selection
src/app/app-modules/login/login.component.ts
The login component selects err.error.errorMessage or err.message, then uses a fallback message when neither exists.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: snehar-nd

🚥 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 and concisely describes the authentication and session error-handling changes in the pull request.
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.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


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.

@sonarqubecloud

sonarqubecloud Bot commented May 5, 2026

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@src/app/app-modules/core/services/auth-guard.service.ts`:
- Line 42: Update the AuthGuard session-validation flow around catchError and
LoginComponent.ngOnInit so failed or expired session credentials do not remain
marked as authenticated and trigger repeated validation errors. Handle
validation errors in the login initialization path or clear
sessionStorage.isAuthenticated only for confirmed invalid/expired sessions,
while preserving the flag for transient server failures.

In `@src/app/app-modules/login/login.component.ts`:
- Around line 206-212: Update the login error handler’s message selection around
confirmationService.alert to prioritize err?.error?.errorMessage, then map
err.status for HTTP 400, 401, 403, 404, 409, and 500 to the corresponding
product messages, preserving err?.message as appropriate. Use the existing
generic fallback only when no API or status-specific message applies, including
unmapped and network errors.
🪄 Autofix

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cccc5798-0926-4cd9-b50d-4fdf15f8bea6

📥 Commits

Reviewing files that changed from the base of the PR and between e81ec5f and 08c325f.

📒 Files selected for processing (2)
  • src/app/app-modules/core/services/auth-guard.service.ts
  • src/app/app-modules/login/login.component.ts

: this.router.createUrlTree(['/login'])
)
),
catchError(() => of(this.router.createUrlTree(['/login'])))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate files =="
git ls-files | rg '(^|/)src/app/(app-modules/core/services/auth-guard.service.ts|login/login.component.ts|.*login.*)\.ts$|(^|/)src/app/.*guard.*\.ts$' || true

echo "== auth guard outline and relevant contents =="
if [ -f src/app/app-modules/core/services/auth-guard.service.ts ]; then
  ast-grep outline src/app/app-modules/core/services/auth-guard.service.ts --view expanded || true
  wc -l src/app/app-modules/core/services/auth-guard.service.ts
  cat -n src/app/app-modules/core/services/auth-guard.service.ts
fi

echo "== login component references =="
rg -n "validateSessionKey|isAuthenticated|authenticationToken|Subscription|Error|CatchError|catchError|ngOnInit" src/app -g '*.ts' || true

echo "== service validation details =="
rg -n "validateSessionKey|isAuthenticated|authenticationToken|isAuthenticated" src/app/src app Common-UI -g '*.ts' 2>/dev/null || true

Repository: PSMRI/MMU-UI

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== login component =="
wc -l src/app/app-modules/login/login.component.ts
sed -n '1,180p' src/app/app-modules/login/login.component.ts

echo "== login spec relevant lines =="
sed -n '1,180p' src/app/app-modules/login/login.component.spec.ts

echo "== focused auth/session references =="
rg -n "validateSessionKey|isAuthenticated|authenticationToken|catchError|Subscription|error" src/app/app-modules/login -g '*.ts' || true
rg -n "validateSessionKey" src/app -g '*.ts' || true

echo "== auth service files =="
git ls-files src/app | rg '(^|/)auth\.service\.ts$|auth-session|session|Auth' || true
for f in $(git ls-files src/app | rg 'auth\.service\.ts$|auth-session|session|Auth'); do
  echo "--- $f"
  wc -l "$f"
  rg -n "validateSessionKey|isAuthenticated|authenticationToken" "$f" -C 4 || true
done

Repository: PSMRI/MMU-UI

Length of output: 10916


Handle session validation errors on login.

AuthGuard redirects to /login on validation failures while sessionStorage.isAuthenticated remains set. LoginComponent.ngOnInit() then subscribes to validateSessionKey() with no error handler, so the invalid session repeats the failing request and propagates an unhandled RxJS error. Clear the stale isAuthenticated state for failed/expired sessions, or handle the validation error in LoginComponent; do not clear credentials for transient server errors.

🤖 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/app/app-modules/core/services/auth-guard.service.ts` at line 42, Update
the AuthGuard session-validation flow around catchError and
LoginComponent.ngOnInit so failed or expired session credentials do not remain
marked as authenticated and trigger repeated validation errors. Handle
validation errors in the login initialization path or clear
sessionStorage.isAuthenticated only for confirmed invalid/expired sessions,
while preserving the flag for transient server failures.

Comment on lines +206 to +212
const message = [err?.error?.errorMessage, err?.message].find(
msg => !!msg
);
this.confirmationService.alert(
message || 'Login request failed. Please try again.',
'error'
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repository files around login component:"
git ls-files | grep -E '(^|/)login\.component\.ts$|package\.json$|src/app/app-modules/login' | head -100

echo
echo "Login component excerpt:"
if [ -f src/app/app-modules/login/login.component.ts ]; then
  nl -ba src/app/app-modules/login/login.component.ts | sed -n '1,280p'
else
  echo "login.component.ts not found"
fi

echo
echo "Search for status-specific login message handling:"
rg -n "400|401|403|404|409|500|HttpErrorResponse|errorMessage|confirmationService\.alert|Login request failed" src/app/app-modules/login src || true

Repository: PSMRI/MMU-UI

Length of output: 459


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Login component excerpt (wc + sed):"
wc -l src/app/app-modules/login/login.component.ts
sed -n '1,280p' src/app/app-modules/login/login.component.ts

echo
echo "Search for status-specific login handling:"
rg -n "400|401|403|404|409|500|HttpErrorResponse|errorMessage|confirmationService\.alert|Login request failed|status" src/app/app-modules/login src || true

echo
echo "Package script hints:"
python3 -c "
import json
from pathlib import Path
p=Path('package.json')
if p.exists():
    d=json.loads(p.read_text())
    for k,v in d.get('scripts',{}).items():
        if 'lint' in k or 'test' in k or 'build' in k:
            print(f'{k}: {v}')
"

Repository: PSMRI/MMU-UI

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
p = Path('src/app/app-modules/login/login.component.ts')
text = p.read_text()
print(f'file_exists={p.exists()} lines={text.count(chr(10))+1}')
for start,end in [(1,80),(180,230)]:
    print(f'\n--- {start}-{end} ---')
    for i,line in enumerate(text.splitlines(),1):
        if start <= i <= end:
            print(f'{i:4}: {line}')

print('\n--- targeted occurrences in login component ---')
for needle in ['confirmationService.alert', 'Login request failed', 'errorMessage', 'HttpErrorResponse', 'status', '400', '401', '403', '404', '409', '500']:
    matches = []
    for i,line in enumerate(text.splitlines(),1):
        if needle in line:
            matches.append(i)
    print(f'{needle}: {matches[:40]}' if len(matches)<=40 else f'{needle}: {matches[:40]} ... count={len(matches)}')
PY

echo
echo "Login spec status/message snippets:"
python3 - <<'PY'
from pathlib import Path
p = Path('src/app/app-modules/login/login.component.spec.ts')
text = p.read_text()
for needle in ['Login request failed', 'errorMessage', 'HttpErrorResponse', 'status', '400', '401', '403', '404', '409', '500', 'confirmationService.alert']:
    matches = [i for i,line in enumerate(text.splitlines(),1) if needle in line]
    print(f'{needle}: first {matches[:10]} count={len(matches)} total_lines={text.count(chr(10))+1}')
PY

Repository: PSMRI/MMU-UI

Length of output: 6101


Map HttpErrorResponse.status in the login error handler.

The error block at src/app/app-modules/login/login.component.ts:206-212 only reads err?.error?.errorMessage and err?.message. This means HTTP 400/401/403/404/409/500 login failures do not use status-specific product messages unless the API provides them in err.error.errorMessage. Keep any API-provided message first, then select messages by err.status, and use the generic fallback only for unmapped or network errors.

🤖 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/app/app-modules/login/login.component.ts` around lines 206 - 212, Update
the login error handler’s message selection around confirmationService.alert to
prioritize err?.error?.errorMessage, then map err.status for HTTP 400, 401, 403,
404, 409, and 500 to the corresponding product messages, preserving err?.message
as appropriate. Use the existing generic fallback only when no API or
status-specific message applies, including unmapped and network errors.

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.

2 participants