# Tasks: Multi-User Authentication and Authorization

**Feature Branch**: `016-multi-user-auth`
**Status**: Completed
**Feature Spec**: [`specs/016-multi-user-auth/spec.md`](spec.md)
**Implementation Plan**: [`specs/016-multi-user-auth/plan.md`](plan.md)

## Phase 1: Setup & Infrastructure (Blocking)

*Goal: Initialize the auth database, core dependencies, and backend infrastructure.*

- [x] T001 Install backend dependencies (Authlib, Passlib, PyJWT, SQLAlchemy) in `backend/requirements.txt`
- [x] T002 Implement core configuration for Auth and Database in `backend/src/core/auth/config.py`
- [x] T003 Implement database connection logic for `auth.db` in `backend/src/core/database.py`
- [x] T004 Create SQLAlchemy models for User, Role, Permission in `backend/src/models/auth.py`
- [x] T005 Create migration/init script to generate `auth.db` schema in `backend/src/scripts/init_auth_db.py`
- [x] T006 Implement password hashing utility using Passlib in `backend/src/core/auth/security.py`
- [x] T007 Implement JWT token generation and validation logic in `backend/src/core/auth/jwt.py`
- [x] T008 [P] Implement CLI tool for creating the initial admin user in `backend/src/scripts/create_admin.py`

## Phase 2: User Story 1 - Local User Authentication (Priority: P1)

*Goal: Enable users to log in with username/password and receive a JWT session.*

- [x] T009 [US1] Create Pydantic schemas for User, UserCreate, Token in `backend/src/schemas/auth.py`
- [x] T010 [US1] Implement `AuthRepository` for DB operations in `backend/src/core/auth/repository.py`
- [x] T011 [US1] Implement `AuthService` for login logic (verify password, create token) in `backend/src/services/auth_service.py`
- [x] T012 [US1] Create API endpoint `POST /api/auth/login` in `backend/src/api/auth.py`
- [x] T013 [US1] Implement `get_current_user` dependency for JWT verification in `backend/src/dependencies.py`
- [x] T014 [US1] Create API endpoint `GET /api/auth/me` to retrieve current user profile in `backend/src/api/auth.py`
- [x] T043 [US1] Implement session revocation (Logout) endpoint in `backend/src/api/auth.py`
- [x] T044 [US1] Implement account status check (`is_active`) in authentication flow in `backend/src/services/auth_service.py`
- [x] T015 [US1] Implement frontend auth store (Svelte store) in `frontend/src/lib/auth/store.ts`
- [x] T016 [US1] Implement Login Page UI using `src/lib/ui` and `src/lib/i18n` in `frontend/src/routes/login/+page.svelte`
- [x] T017 [US1] Integrate Login Page with Backend API in `frontend/src/routes/login/+page.svelte`
- [x] T018 [US1] Implement `ProtectedRoute` component to redirect unauthenticated users in `frontend/src/components/auth/ProtectedRoute.svelte`
- [x] T037 [US1] Implement password complexity validation logic in `backend/src/core/auth/security.py`

## Phase 3: User Story 2 - Plugin-Based Access Control (Priority: P1)

*Goal: Restrict access to plugins based on user roles and permissions.*

- [x] T019 [US2] Update `PluginBase` to include required permission strings in `backend/src/core/plugin_base.py`
- [x] T020 [US2] Implement `has_permission` dependency for route protection in `backend/src/dependencies.py`
- [x] T021 [US2] Protect existing plugin API routes using `has_permission` in `backend/src/api/routes/*.py`
- [x] T022 [US2] Implement `SystemAdminPlugin` inheriting from `PluginBase` for User/Role management in `backend/src/plugins/system_admin.py`
- [x] T023 [US2] Implement Admin API endpoints within `SystemAdminPlugin` in `backend/src/api/routes/admin.py`
- [x] T053 [US2] Extend Admin API with User Update/Delete and Role CRUD endpoints in `backend/src/api/routes/admin.py`
- [x] T054 [US2] Add Pydantic schemas for UserUpdate, RoleCreate, RoleUpdate in `backend/src/schemas/auth.py`
- [x] T051 [US2] Implement `adminService.js` for frontend API orchestration
- [x] T055 [US2] Update `adminService.js` with new CRUD methods
- [x] T024 [US2] Create Admin Dashboard UI using `src/lib/ui` and `src/lib/i18n` in `frontend/src/routes/admin/users/+page.svelte`
- [x] T056 [US2] Update Admin User Dashboard to support Edit/Delete operations in `frontend/src/routes/admin/users/+page.svelte`
- [x] T057 [US4] Create Role Management UI in `frontend/src/routes/admin/roles/+page.svelte`
- [x] T025 [US2] Update Navigation Bar to hide links and show user profile/logout using `src/lib/ui` in `frontend/src/components/Navbar.svelte`
- [x] T042 [US2] Implement `PermissionGuard` frontend component for granular UI element protection in `frontend/src/components/auth/PermissionGuard.svelte`
- [x] T045 [US2] Implement multi-role permission resolution logic (union of permissions) in `backend/src/services/auth_service.py`

## Phase 4: User Story 3 - ADFS Integration (Priority: P2)

*Goal: Enable corporate SSO login via ADFS and JIT provisioning.*

- [x] T026 [US3] Configure Authlib for ADFS OIDC in `backend/src/core/auth/oauth.py`
- [x] T027 [US3] Create `ADGroupMapping` model in `backend/src/models/auth.py` and update DB init script
- [x] T028 [US3] Implement JIT provisioning logic (create user if maps to group) in `backend/src/services/auth_service.py`
- [x] T029 [US3] Create API endpoints `GET /api/auth/login/adfs` and `GET /api/auth/callback/adfs` in `backend/src/api/auth.py`
- [x] T030 [US3] Update Login Page to include "Login with ADFS" button using `src/lib/ui` in `frontend/src/routes/login/+page.svelte`
- [x] T031 [US3] Implement Admin UI for configuring AD Group Mappings in `frontend/src/routes/admin/settings/+page.svelte`
- [x] T052 [US3] Extend Admin API with AD mapping endpoints in `backend/src/api/routes/admin.py`
- [x] T041 [US3] Create ADFS mock provider for local testing and CI in `backend/tests/auth/mock_adfs.py`
- [x] T046 [US3] Implement token refresh logic for ADFS OIDC tokens in `backend/src/core/auth/jwt.py`

## Phase 5: Polish & Security Hardening

*Goal: Ensure security best practices and smooth UX.*

- [x] T032 Ensure all cookies are set with `HttpOnly` and `Secure` flags in `backend/src/api/auth.py`
- [x] T033 Implement rate limiting and account lockout policy in `backend/src/api/auth.py`
- [x] T034 Verify error messages are generic (no username enumeration) across all auth endpoints
- [x] T035 Add "Session Expired" handling in frontend interceptor in `frontend/src/lib/api/client.ts`
- [x] T036 Final manual test of switching between Local and ADFS login flows
- [x] T040 Add confirmation dialogs for destructive admin actions using `src/lib/ui` in `frontend/src/routes/admin/users/+page.svelte`
- [x] T047 Implement audit logging for security events (login, logout, permission changes) in `backend/src/core/auth/logger.py`
- [x] T048 Perform UI accessibility audit (keyboard nav, ARIA alerts) for all auth components
- [x] T049 Implement unit and integration tests for Local Auth and RBAC in `backend/tests/auth/`
- [x] T050 Implement E2E tests for ADFS flow using mock provider in `tests/e2e/auth.spec.ts`

## Dependencies

1.  **Phase 1** must be completed before any User Stories.
2.  **Phase 2 (Local Auth)** is the foundation for authentication and session management.
3.  **Phase 3 (RBAC)** depends on Phase 2 (needs authenticated users to check permissions).
4.  **Phase 4 (ADFS)** depends on Phase 2 (uses same session mechanism) and Phase 3 (needs roles for JIT).

## Implementation Strategy

-   **MVP**: Complete Phases 1 and 2. This gives a working auth system with local users.
-   **Increment 1**: Complete Phase 3. This adds the critical security controls (RBAC).
-   **Increment 2**: Complete Phase 4. This adds corporate SSO convenience.

## Post-Delivery RBAC Navigation Hardening (2026-03-06)

- [x] D055 Investigate frontend navigation visibility mismatch (menu items shown despite backend 403 RBAC) in `frontend/src/lib/components/layout/Sidebar.svelte` and `frontend/src/lib/components/layout/TopNavbar.svelte`
- [x] D056 Implement shared frontend permission utilities and route-level permission enforcement in `frontend/src/lib/auth/permissions.js` and `frontend/src/components/auth/ProtectedRoute.svelte`
- [x] D057 Implement RBAC-aware sidebar navigation builder and integrate permission-filtered categories in `frontend/src/lib/components/layout/sidebarNavigation.js` and `frontend/src/lib/components/layout/Sidebar.svelte`
- [x] D058 Add automated frontend tests for permission normalization/checking and sidebar visibility matrix in `frontend/src/lib/auth/__tests__/permissions.test.js` and `frontend/src/lib/components/layout/__tests__/sidebarNavigation.test.js`
- [x] D059 Execute targeted frontend test verification for RBAC navigation filtering (`npm run test -- src/lib/auth/__tests__/permissions.test.js src/lib/components/layout/__tests__/sidebarNavigation.test.js`)

## Post-Delivery RBAC Permission Catalog Sync (2026-03-06)

- [x] D060 Implement automatic RBAC permission discovery/synchronization service for admin role settings permission catalog in `backend/src/services/rbac_permission_catalog.py`
- [x] D061 Integrate permission catalog synchronization into `GET /api/admin/permissions` flow in `backend/src/api/routes/admin.py`
- [x] D062 Add unit tests for permission discovery and idempotent sync behavior in `backend/src/services/__tests__/test_rbac_permission_catalog.py`
- [x] D063 Execute targeted backend test verification for RBAC catalog sync (`cd backend && .venv/bin/python3 -m pytest src/services/__tests__/test_rbac_permission_catalog.py`)