Commit Graph

140 Commits

Author SHA1 Message Date
Felipe Cardoso
532577f36c Mark Phase 2 as completed in AUTH_CONTEXT_MIGRATION_PLAN.md
- Updated the plan to reflect the completion of Phase 2 tasks, including the migration of Core Auth Components (`AuthGuard`, `Header`).
- Added detailed verification results, success criteria, and status for Task 2.1, 2.2, and 2.3.
- Highlighted the next steps for Phase 3 (migrating Auth hooks for testability).
2025-11-03 13:16:44 +01:00
Felipe Cardoso
9843cf8218 Refactor auth hooks and add database existence check during migrations
- Consolidated `useAuthStore` into the unified `useAuth` hook for cleaner imports and consistency across frontend components.
- Enhanced database management in Alembic migrations by introducing `ensure_database_exists` to automatically create the database if missing.
2025-11-03 13:16:34 +01:00
Felipe Cardoso
2ee48bf3fa Document common pitfalls for the frontend and enhance architecture guidelines
- Added `COMMON_PITFALLS.md` to document frequent mistakes and best practices in frontend development, focusing on React Hooks, Context API, Zustand patterns, TypeScript type safety, and more.
- Updated `ARCHITECTURE.md` with detailed insights on the `AuthContext` dependency injection pattern, including usage examples, provider tree structure, polymorphic hooks, and testing strategies.
- Emphasized compliance with React Rules of Hooks, performance optimizations, and separation of concerns in component design.
- Included implementation-ready examples, checklists, and resources to guide maintainable and testable frontend development.
2025-11-03 11:59:21 +01:00
Felipe Cardoso
a36c1b61bb Document Phase 1 lessons learned for AuthContext migration and update hooks for compliance with React Rules of Hooks
- Added detailed documentation in `AUTH_CONTEXT_MIGRATION_PLAN.md` for lessons learned during Phase 1 of the `AuthContext` migration.
- Highlighted critical implementation insights, including refactoring `useAuth` to call Zustand hooks internally, strict type safety with the `AuthState` interface, and dependency injection via `AuthProvider`.
- Defined updated architecture for provider placement and emphasized the importance of documentation, barrel exports, and hook compliance with React rules.
- Included comprehensive examples, verification checklists, common mistakes to avoid, and future-proofing guidelines.
2025-11-03 11:40:46 +01:00
Felipe Cardoso
0cba8ea62a Introduce AuthContext and refactor layout for dependency injection
- Added `AuthContext` as a dependency injection wrapper over the Zustand auth store to support test isolation, E2E testability, and clean architecture patterns.
- Updated `layout.tsx` to utilize `AuthProvider` and initialize authentication context.
- Removed redundant `AuthInitializer` from `providers.tsx`.
- Enhanced modularity and testability by decoupling authentication context from direct store dependency.
2025-11-03 11:33:39 +01:00
Felipe Cardoso
01b406bca7 Add DI-based AuthContext wrapper and migrate auth flows to improve testability
- Introduced a new `AuthContext` with Dependency Injection to replace direct `useAuthStore` access, enhancing E2E testability.
- Migrated authentication core components (`AuthInitializer`, `AuthGuard`, `Header`) and hooks (`useAuth`, `useUser`) to use `AuthContext`.
- Updated test suite:
  - Refactored unit tests to mock `AuthContext` instead of `useAuthStore`.
  - Enhanced E2E test helpers to inject mock auth stores for authenticated and admin scenarios.
  - Verified API client interceptors remain compatible with the new setup.
- No breaking changes; maintained 98.38% test coverage.
2025-11-03 09:24:44 +01:00
Felipe Cardoso
77b914ffa2 Disable Firefox browser in Playwright config due to missing system dependencies. 2025-11-03 08:36:56 +01:00
Felipe Cardoso
10ff6a1a96 Add comprehensive E2E tests for settings pages (Profile, Password, Sessions)
- Implemented Playwright tests for profile settings, password change, and session management pages to validate user interactions, form handling, and navigation.
- Added `setupAuthenticatedMocks` helper to mock API interactions and improve test isolation.
- Verified edge cases like form validation, dirty states, session revocation, and navigation consistency.
2025-11-03 08:36:51 +01:00
Felipe Cardoso
88dc81735b Mark Phase 4 as complete: implemented Profile, Password, and Session management features with ProfileSettingsForm, PasswordChangeForm, and SessionsManager. Achieved 98.38% overall test coverage, 451 unit tests passing (100%), and updated documentation for Phase 5 readiness. 2025-11-03 00:46:43 +01:00
Felipe Cardoso
e81f54564b Remove unused imports and update comment annotations in settings components
- Remove unused icons (`Smartphone`, `Tablet`) from `SessionCard` component.
- Add `/* istanbul ignore next */` comment for untestable `isDirty`-dependent Reset button in `ProfileSettingsForm`.
2025-11-03 00:46:36 +01:00
Felipe Cardoso
f7133807fc Remove untestable unit tests for PasswordChangeForm and update comment annotations
- Remove redundant unit tests for `PasswordChangeForm` that rely on `isDirty` state handling, as this functionality is now covered by E2E Playwright tests.
- Add `/* istanbul ignore next */` comments to exclude untestable code paths related to form submission and `isDirty` state.
2025-11-03 00:18:19 +01:00
Felipe Cardoso
388ca08724 Add unit tests for settings components and session hooks
- Implement comprehensive tests for `ProfileSettingsForm`, `PasswordChangeForm`, and `SessionCard` components to validate rendering, interactions, and state handling.
- Add tests for session management hooks (`useSession`, `useRevokeSession`, and `useRevokeAllOtherSessions`) to verify logic and API integration.
- Ensure coverage of edge cases, error handling, and success callbacks across all new tests.
2025-11-03 00:12:59 +01:00
Felipe Cardoso
54a14047be Enhance auth flows and improve e2e test reliability
- Remove redundant `'use client'` directives in auth pages to streamline code.
- Refine Playwright config: adjust worker limits and add video recording for failed tests.
- Improve session management in e2e tests with isolated state clearing, console log collection, and detailed failure attachments.
- Update API client: better handle auth routes, ensure safe token refresh, and prevent unnecessary redirects.
2025-11-03 00:02:27 +01:00
Felipe Cardoso
65f209c679 Add forms for profile and password settings; improve tests for settings pages
- Implement `ProfileSettingsForm` and `PasswordChangeForm` components to manage user profile and password updates.
- Add `SessionCard` for session management and related API hooks (`useSession`).
- Update settings page tests to include user state mock and React Query provider for better test reliability.
- Enhance `PasswordSettingsPage` and `ProfileSettingsPage` tests to verify component rendering and user interaction.
- Improve API hook structure with dedicated hooks for session and user profile management.
2025-11-02 23:24:29 +01:00
Felipe Cardoso
64a4b3fb11 Improve login form validation and enhance e2e test reliability
- Update `LoginForm` to use `onBlur` mode and `onChange` revalidation for better UX.
- Enhance e2e tests to verify field interactivity, ensure visibility of submit button, and improve error validation reliability across browsers.
2025-11-02 23:23:49 +01:00
Felipe Cardoso
1c7f34c078 Mark Phase 3 as complete: performance optimized, achieved Lighthouse 100%, 98.63% test coverage, fixed token refresh race condition, and conditionalized production logs. Updated documentation for Phase 4 readiness. 2025-11-02 23:04:43 +01:00
Felipe Cardoso
fe5d152cee Add conditional logging for development, improve token refresh logic, and remove outdated comments
- Wrap `console.log` calls in `if (process.env.NODE_ENV === 'development')` to prevent production logs in `forms/page.tsx`.
- Refactor token refresh logic by relying solely on the `refreshPromise` to avoid race conditions.
- Remove outdated `isRefreshing` flag, utilizing `refreshPromise` as the primary lock.
- Update comments in `IMPLEMENTATION_PLAN.md` to reflect the current progress and eliminate redundant sections.
2025-11-02 22:59:34 +01:00
Felipe Cardoso
15f522b9b1 Improve e2e tests for Login and Register forms
- Ensure React hydration before interaction.
- Update error validation to improve reliability, especially for Firefox.
- Replace static URL checks with regex to handle query parameters.
2025-11-02 20:16:24 +01:00
Felipe Cardoso
fded54e61a Add comprehensive tests for authentication, settings, and password reset pages
- Introduced smoke tests for Login, Register, Password Reset, Password Reset Confirm, and Settings pages.
- Enhanced test coverage for all dynamic imports using mocks and added Jest exclusions for non-testable Next.js files.
- Added component-specific test files for better structure and maintainability.
- Improved test isolation by mocking navigation, providers, and rendering contexts.
2025-11-02 17:33:57 +01:00
Felipe Cardoso
77594e478d Add tests for ThemeProvider and authStore behavior refinements
- Added tests to validate `ThemeProvider` updates resolved theme on system preference changes and ignores changes for non-system themes.
- Introduced tests to ensure `authStore` gracefully handles invalid tokens, storage errors, and logs errors appropriately during authentication state transitions.
- Improved test coverage by adding defensive error handling cases and refining token validation logic.
2025-11-02 17:23:58 +01:00
Felipe Cardoso
ac3fac0426 Add tests for useFormError hook and FormField component
- Introduced `useFormError.test.tsx` to validate error handling, server error integration, and form behavior.
- Added `FormField.test.tsx`, covering rendering, accessibility, error handling, and prop forwarding.
- Updated Jest coverage exclusions to include `middleware.ts` (no logic to test).
2025-11-02 17:14:12 +01:00
Felipe Cardoso
0e554ef35e Add tests for AuthGuard, Skeleton components, and AdminPage
- Enhance `AuthGuard` tests with 150ms delay skeleton rendering.
- Add new test files: `Skeletons.test.tsx` to validate skeleton components and `admin/page.test.tsx` for admin dashboard.
- Refactor `AuthGuard` tests to utilize `jest.useFakeTimers` for delay simulation.
- Improve coverage for loading states, fallback behavior, and rendering logic.
2025-11-02 17:07:15 +01:00
Felipe Cardoso
aedc770afb Update Lighthouse report for /settings/profile and fix runtime errors
- Updated `lighthouse-report.json` to reflect audit for `http://localhost:3000/settings/profile`.
- Resolved `CHROME_INTERSTITIAL_ERROR` runtime issues.
- Added HTTPS and performance audit metrics, improving accuracy and insights.
2025-11-02 16:59:36 +01:00
Felipe Cardoso
54c32bf97f Introduce AuthLoadingSkeleton and HeaderSkeleton for smoother loading, replace spinner in AuthGuard, update ReactQueryDevtools toggle, enable Docker ports for local development. 2025-11-02 16:56:23 +01:00
Felipe Cardoso
1b9854d412 Performance optimizations: Bundle size reduction
Optimizations implemented:
1. Font display: swap + preload for critical fonts
2. ReactQueryDevtools: Lazy load in dev only, exclude from production
3. Auth forms code splitting: LoginForm, PasswordResetRequestForm
4. Remove invalid swcMinify option (default in Next.js 15)

Results:
- Login page: 178 kB → 104 kB (74 kB saved, 42% reduction)
- Password reset: 178 kB → 104 kB (74 kB saved, 42% reduction)
- Homepage: 108 kB (baseline 102 kB shared + 6 kB page)

Remaining issue:
- 102 kB baseline shared by all pages (React Query + Auth loaded globally)
2025-11-02 16:16:13 +01:00
Felipe Cardoso
911d4a594e Introduce DevBreadcrumbs component for navigation and replace headers in /dev pages with breadcrumb navigation. Adjust spacing for consistent layout. 2025-11-02 16:07:39 +01:00
Felipe Cardoso
86d8e1cace Remove analysis documents (ANALYSIS_SUMMARY.md, COMPONENT_IMPLEMENTATION_GUIDE.md, DEV_PAGES_QUICK_REFERENCE.md) for /dev/ pages refactor. Content has been fully implemented in codebase. 2025-11-02 16:07:12 +01:00
Felipe Cardoso
2c05f17ec5 Fix authStore tests after reverting persist middleware
- Replace deprecation tests with functional tests
- Test loadAuthFromStorage actually loads tokens
- Test initializeAuth calls loadAuthFromStorage
- All 281 tests passing
2025-11-02 14:54:00 +01:00
Felipe Cardoso
68e28e4c76 Revert Zustand persist middleware approach and restore AuthInitializer
- Remove persist middleware from authStore (causing hooks timing issues)
- Restore original AuthInitializer component pattern
- Keep good Phase 3 optimizations:
  - Theme FOUC fix (inline script)
  - React Query refetchOnWindowFocus disabled
  - Code splitting for dev/auth components
  - Shared form components (FormField, useFormError)
  - Store location in lib/stores
2025-11-02 14:52:12 +01:00
Felipe Cardoso
6d1b730ae7 Add _hasHydrated flag to authStore and update AuthGuard to wait for store hydration, ensuring stability during loading phases in tests and app. 2025-11-02 14:16:56 +01:00
Felipe Cardoso
29f98f059b **Add comprehensive backend documentation for FastAPI setup, configuration, and architecture** 2025-11-02 14:11:34 +01:00
Felipe Cardoso
b181182c3b **Authentication Refactor:** Remove authStore and its associated tests, transitioning to the new authentication model. Add dynamic loading for PasswordResetConfirmForm to optimize performance. Include a theme initialization script in layout.tsx to prevent FOUC. 2025-11-02 14:00:05 +01:00
Felipe Cardoso
92b7de352c **Docs and Code Enhancements:** Add CodeBlock component with copy functionality and syntax highlighting. Introduce /docs page as the central hub for design system documentation. Update MarkdownContent to support improved heading styles, enhanced links, optimized images with Next.js Image, and upgraded table, blockquote, and list styling for better readability and usability. 2025-11-02 13:47:26 +01:00
Felipe Cardoso
aff76e3a69 Update implementation plan to reflect Phase 2.5 completion, documenting design system integration, UI consistency, and enhanced test coverage (97.57%). 2025-11-02 13:34:50 +01:00
Felipe Cardoso
13771c5354 **Design System Enhancements:** Replace .md links with clean paths in /dev documentation. Migrate anchor tags (<a>) to Next.js <Link> components for internal navigation. Add dynamic [...slug] markdown route for rendering docs. Introduce MarkdownContent for styled markdown rendering with syntax highlighting. Perform general cleanup of unused imports and variables in design system files. Fix minor wording issues. 2025-11-02 13:33:47 +01:00
Felipe Cardoso
c3c6a18dd1 **Test Documentation Update:** Simplify test coverage description and clarify security-focused testing features, including CVE-2015-9235 prevention, session hijacking, and privilege escalation. 2025-11-02 13:28:49 +01:00
Felipe Cardoso
68e7ebc4e0 - **Middleware & Security Enhancements:** Add request size limit middleware to prevent DoS attacks via large payloads (10MB max).
- **Authentication Refactor:** Introduce `_create_login_session` utility to streamline session creation for login and OAuth flows.
- **Configurations:** Dynamically set app name in PostgreSQL connection (`application_name`) and adjust token expiration settings (`expires_in`) based on system configuration.
2025-11-02 13:25:53 +01:00
Felipe Cardoso
df299e3e45 Add pointer cursor style for interactive elements and exception for disabled states 2025-11-02 13:21:57 +01:00
Felipe Cardoso
8e497770c9 Add Dev Hub for interactive design system demos and /dev/forms with validation examples
- **Design System Hub:** Introduce `/dev` as a central hub for interactive design system showcases (components, layouts, spacing, etc.). Includes live demos, highlights, and documentation links.
- **Forms Demo:** Add `/dev/forms` for reactive forms with `react-hook-form` and `Zod`. Demonstrate validation patterns, error handling, loading states, and accessibility best practices.
- **Features:** Showcase reusable `Example`, `ExampleSection`, and `BeforeAfter` components for better UI demonstration and code previews.
2025-11-02 13:21:53 +01:00
Felipe Cardoso
58b761106b Add reusable Example, ExampleGrid, and ExampleSection components for live UI demonstrations with code previews. Refactor ComponentShowcase to use new components, improving structure, maintainability, and documentation coverage. Include semantic updates to labels and descriptions. 2025-11-02 13:21:25 +01:00
Felipe Cardoso
e734acf31d **Design System Documentation:** Add comprehensive project progress documentation summarizing Phase 1 completion, including created files, cleanup, and review results. Outline Phase 2 interactive demo plans and next steps. Reflect structure, content philosophy, and AI optimization guidelines. 2025-11-02 12:42:42 +01:00
Felipe Cardoso
76d36e1b12 - **Authentication & Lifespan Updates:** Add @asynccontextmanager for application lifecycle management, including startup/shutdown handling and daily session cleanup scheduling. Reduce token expiration from 24 hours to 15 minutes for enhanced security. Streamline superuser field validation via schema, removing redundant defensive checks. 2025-11-02 12:38:09 +01:00
Felipe Cardoso
6e95469d99 Remove version file 2025-11-02 12:34:47 +01:00
Felipe Cardoso
6d9b98943c Update documentation and tests for coverage, email integration, and authentication
- **Backend Documentation:** Improve authentication flow details, update token expiry times, and reflect defensive code in test coverage. Add guidance for email service integration with SMTP and third-party providers.
- **Test Coverage:** Backend overall coverage increased to **97%** with critical security tests added (JWT attacks, session hijacking, privilege escalation). Justify missing lines and update CI instructions.
- **Frontend Updates:** Update E2E worker configuration (`workers: 12` in non-CI mode) and maintain 100% E2E test pass rate.
- **Default Implementations:** Enhance email service with templates for registration and password resets. Document integration options for production use cases.
- **Consistency Improvements:** Align naming conventions and test configurations across backend and frontend to reflect current system architecture.
2025-11-02 12:32:08 +01:00
Felipe Cardoso
30cbaf8ad5 Add documentation for component creation and design system structure
- **Component Creation Guide:** Document best practices for creating reusable, accessible components using CVA patterns. Includes guidance on when to compose vs create, decision trees, templates, prop design, testing checklists, and real-world examples.
- **Design System README:** Introduce an organized structure for the design system documentation with quick navigation, learning paths, and reference links to key topics. Includes paths for quick starts, layouts, components, forms, and AI setup.
2025-11-02 12:32:01 +01:00
Felipe Cardoso
13f830ed6d Remove E2E tests for authenticated navigation and theme toggle 2025-11-02 12:30:57 +01:00
Felipe Cardoso
c051bbf0aa Add security tests for configurations, permissions, and authentication
- **Configurations:** Test minimum `SECRET_KEY` length validation to prevent weak JWT signing keys. Validate proper handling of secure defaults.
- **Permissions:** Add tests for inactive user blocking, API access control, and superuser privilege escalation across organizational roles.
- **Authentication:** Test logout safety, session revocation, token replay prevention, and defense against JWT algorithm confusion attacks.
- Include `# pragma: no cover` for unreachable defensive code in security-sensitive areas.
2025-11-02 11:55:58 +01:00
Felipe Cardoso
b39b7b4c94 Add E2E tests for authenticated navigation and theme toggle
- **Authenticated Navigation:** Test header, footer, settings navigation, user menu interactions, and settings tabs for authenticated users. Validate logout and active tab highlighting.
- **Theme Toggle:** Add tests for theme persistence and switching on both public and private pages. Verify localStorage integration and DOM updates across scenarios.
2025-11-02 07:56:31 +01:00
Felipe Cardoso
9f88736d13 Add comprehensive tests for schemas, validators, and exception handlers
- **Schemas:** Introduce unit tests for `OrganizationBase`, `OrganizationCreate`, and `OrganizationUpdate` schemas. Validate edge cases for slug and name validation.
- **Validators:** Add tests for `validate_password_strength`, `validate_phone_number`, `validate_email_format`, and `validate_slug`. Cover edge cases, boundary conditions, and defensive code paths.
- **Exception Handlers:** Ensure proper error handling in organization, user, and session CRUD operations. Mock database errors and validate exception responses.
- Include test cases to verify robust behavior, normalization, and failure scenarios across schema and validation logic.
2025-11-02 07:56:23 +01:00
Felipe Cardoso
ccd535cf0e Add # pragma: no cover to defensive code sections in validators and CRUD operations
- Mark unreachable code paths in `validators.py` and `base.py` with `# pragma: no cover` for coverage accuracy.
- Add comments to clarify defensive code's purpose and usage across methods.
2025-11-02 07:42:24 +01:00