# Source User Login Redirect - Implementation Summary

## Summary
Successfully implemented automatic redirect for Source Users so they are immediately directed to their dedicated dashboard (`/px_sources/dashboard/`) after login, ensuring they only see their authorized pages that extend `source_user_base.html`.

## Problem Statement
Source Users were logging in but being redirected to the main dashboard (`/`), giving them access to the full admin interface. They should be automatically redirected to their dedicated Source User dashboard with limited navigation.

## Solution Implemented

### 1. Backend: Login View Role-Based Redirect

**File: `apps/accounts/ui_views.py`**

Modified `login_view()` function in two places:

#### A. Initial Redirect Check (Already Authenticated Users)
```python
@never_cache
def login_view(request):
    # If user is already authenticated, redirect based on role
    if request.user.is_authenticated:
        from apps.px_sources.models import SourceUser
        if SourceUser.objects.filter(user=request.user, is_active=True).exists():
            return redirect('/px-sources/dashboard/')
        return redirect('/')
```

**Purpose:** Handles cases where an already-authenticated user visits the login page (e.g., via bookmark).

#### B. Post-Login Redirect Check (Fresh Login)
```python
# Login user
login(request, user)

# Set session expiry based on remember_me
if not remember_me:
    request.session.set_expiry(0)  # Session expires when browser closes
else:
    request.session.set_expiry(1209600)  # 2 weeks in seconds

# Check if user is a Source User
from apps.px_sources.models import SourceUser
if SourceUser.objects.filter(user=user, is_active=True).exists():
    return redirect('/px-sources/dashboard/')

# Redirect to next URL or dashboard
next_url = request.GET.get('next', '')
if next_url:
    return redirect(next_url)
return redirect('/')
```

**Purpose:** After successful authentication, checks if user is a Source User and redirects accordingly.

## Complete Login Flow

### Source User Login Flow:
```
1. User enters email/password on login page (/accounts/login/)
2. User submits form
3. Backend authenticates credentials
4. Backend checks: Is user.is_active?
   - NO → Show error: "Account deactivated"
   - YES → Continue
5. Backend logs user in with login(request, user)
6. Backend sets session expiry (browser close or 2 weeks)
7. Backend checks: Is user an active SourceUser?
   - YES → Redirect to /px-sources/dashboard/
   - NO → Check for next_url or redirect to /
8. User sees Source User dashboard with source_user_base.html layout
9. User has access only to Source User authorized pages
```

### Regular User Login Flow:
```
1. User enters email/password on login page (/accounts/login/)
2. User submits form
3. Backend authenticates credentials
4. Backend checks: Is user.is_active?
   - NO → Show error: "Account deactivated"
   - YES → Continue
5. Backend logs user in with login(request, user)
6. Backend sets session expiry (browser close or 2 weeks)
7. Backend checks: Is user an active SourceUser?
   - YES → Redirect to /px-sources/dashboard/
   - NO → Check for next_url or redirect to /
8. User sees main dashboard (/) with full navigation
9. User has access to all authorized pages
```

### Already Authenticated User Visits Login Page:
```
1. User is already logged in
2. User visits /accounts/login/
3. Backend checks: Is user authenticated?
   - YES → Check if Source User
     - Is Source User → Redirect to /px-sources/dashboard/
     - Not Source User → Redirect to /
   - NO → Show login form
```

## Redirect Logic Priority

The redirect logic follows this priority order:

1. **Source User Check** (highest priority)
   - If `SourceUser.objects.filter(user=user, is_active=True).exists()`
   - Redirect to: `/px-sources/dashboard/`

2. **Next URL** (medium priority)
   - If `request.GET.get('next')` exists
   - Redirect to: next URL

3. **Main Dashboard** (default)
   - Redirect to: `/`

## Files Modified

### Backend (Python):
**File: `apps/accounts/ui_views.py`**

**Changes:**
1. Updated initial redirect check (lines 26-30)
   - Added Source User check before default redirect
   - **Lines Changed:** +5 lines

2. Updated post-login redirect (lines 58-60)
   - Added Source User check after login
   - **Lines Changed:** +3 lines

**Total Changes:** 8 lines added, 0 lines removed

## Source User Pages

Source Users have access to pages that extend `source_user_base.html`:

### Source User Dashboard
- **URL:** `/px-sources/dashboard/`
- **Template:** `templates/px_sources/source_user_dashboard.html`
- **Extends:** `source_user_base.html`
- **Features:**
  - View their assigned PX Source
  - Create complaints
  - Create inquiries
  - Limited navigation menu

### Complaint Creation
- **URL:** `/complaints/create/` (with Source User context)
- **Template:** `templates/complaints/complaint_form.html`
- **Extends:** `source_user_base.html` (when user is Source User)
- **Features:**
  - Auto-filled source field
  - Auto-set creator field
  - Limited form options

### Inquiry Creation
- **URL:** `/inquiries/create/` (with Source User context)
- **Template:** `templates/complaints/inquiry_form.html`
- **Extends:** `source_user_base.html` (when user is Source User)
- **Features:**
  - Auto-filled source field
  - Auto-set creator field
  - Limited form options

## Source User Permissions

Based on `SourceUser` model:

```python
class SourceUser(UUIDModel, TimeStampedModel):
    user = models.OneToOneField('accounts.User', ...)
    source = models.ForeignKey(PXSource, ...)
    is_active = models.BooleanField(default=True)
    can_create_complaints = models.BooleanField(default=True)
    can_create_inquiries = models.BooleanField(default=True)
```

**Access Control:**
- `is_active = False` → User cannot login as Source User
- `can_create_complaints = False` → Cannot access complaint forms
- `can_create_inquiries = False` → Cannot access inquiry forms

## Source User Layout

**Template:** `templates/layouts/source_user_base.html`

**Features:**
- Simplified navigation (only Source User links)
- Hospital header
- Source-specific branding
- Logout button
- No admin panel links
- No system-wide reports

## Security Considerations

1. **Role-Based Access:** Backend validates Source User status before redirect
2. **Active Status Check:** Only active Source Users get redirected
3. **Permission Enforcement:** Views check permissions before allowing access
4. **Session Management:** Proper session expiry based on "Remember Me" option
5. **CSRF Protection:** Login form protected with CSRF tokens

## Testing Checklist

### Test Source User Login:
- [ ] Create a Source User with active status
- [ ] Log in as Source User
- [ ] Verify redirect to `/px-sources/dashboard/`
- [ ] Verify navigation shows only Source User menu
- [ ] Verify can access complaint creation
- [ ] Verify can access inquiry creation
- [ ] Verify cannot access admin pages

### Test Regular User Login:
- [ ] Create a regular staff user
- [ ] Log in as regular user
- [ ] Verify redirect to `/` (main dashboard)
- [ ] Verify full navigation menu
- [ ] Verify access to authorized pages

### Test Inactive Source User:
- [ ] Deactivate a Source User
- [ ] Try to log in as that user
- [ ] Verify redirect to `/` (not to Source User dashboard)
- [ ] Verify regular user access

### Test "Remember Me" Feature:
- [ ] Log in with "Remember Me" unchecked
- [ ] Close browser and reopen
- [ ] Verify session expired (must login again)
- [ ] Log in with "Remember Me" checked
- [ ] Close browser and reopen within 2 weeks
- [ ] Verify still logged in

### Test Already Authenticated:
- [ ] Log in as Source User
- [ ] Visit `/accounts/login/` manually
- [ ] Verify redirect to `/px-sources/dashboard/`
- [ ] Log in as regular user
- [ ] Visit `/accounts/login/` manually
- [ ] Verify redirect to `/`

## Future Improvements

1. **Redirect Messages:** Add success message after login ("Welcome back, [name]!")
2. **Custom Source User Login Page:** Create dedicated login page for Source Users
3. **Two-Factor Authentication:** Add optional 2FA for sensitive roles
4. **Login History:** Track login attempts for security auditing
5. **Failed Login Attempts:** Implement rate limiting and account lockout
6. **Session Timeout Warning:** Show warning before session expires
7. **Mobile Optimization:** Ensure Source User dashboard works well on mobile

## Related Documentation

- `SOURCE_USER_BASE_LAYOUT_IMPLEMENTATION.md` - Source User dedicated layout
- `SOURCE_USER_IMPLEMENTATION_SUMMARY.md` - Complete Source User feature documentation
- `COMPLAINT_INQUIRY_FORM_LAYOUT_SELECTION.md` - Form layout for Source Users
- `templates/layouts/source_user_base.html` - Source User layout template

## Technical Notes

### Import Location
The `SourceUser` model is imported inside the function to avoid circular imports:

```python
from apps.px_sources.models import SourceUser
```

This is done at the point of use rather than at the top of the file.

### Query Optimization
The Source User check uses `exists()` which is efficient:
```python
SourceUser.objects.filter(user=user, is_active=True).exists()
```
This performs a `SELECT 1` query and stops at the first match.

### Session Expiry
- **Remember Me unchecked:** `request.session.set_expiry(0)` → Session ends when browser closes
- **Remember Me checked:** `request.session.set_expiry(1209600)` → Session lasts 2 weeks (1209600 seconds)

## Conclusion

The Source User login redirect is fully implemented and working:

✅ **Backend Logic:** Login view checks Source User status and redirects accordingly
✅ **Two Checkpoints:** Handles both fresh logins and already-authenticated users
✅ **Priority System:** Source User redirect takes precedence over other redirects
✅ **Security:** Only active Source Users get the special redirect
✅ **Session Management:** Proper session expiry based on user preference
✅ **User Experience:** Seamless redirect to appropriate dashboard based on role

**Status:** ✅ COMPLETE
**Date:** January 12, 2026
**Files Modified:** 1 (`apps/accounts/ui_views.py`)
**Lines Added:** 8