Commit Graph

57 Commits

Author SHA1 Message Date
Felipe Cardoso
b8d3248a48 Refactor password reset flow and improve ESLint integration
- Extracted password reset logic into `PasswordResetConfirmContent` wrapped in `Suspense` for cleaner and more modular component structure.
- Updated ESLint config to ignore generated files and added rules for stricter code quality (`eslint-comments`, `@typescript-eslint` adjustments).
- Automated insertion of `eslint-disable` in auto-generated TypeScript files through `generate-api-client.sh`.
- Replaced unsafe `any` type casts with safer `Record<string, unknown>` type assertions for TypeScript compliance.
- Added `lint:tests` script for pre-commit test coverage checks.
- Improved `useAuth` hooks and related type guards for better runtime safety and maintainability.
2025-11-01 06:04:35 +01:00
Felipe Cardoso
a062daddc5 Remove CRUD test modules for unused and deprecated features
- Deleted `test_crud_base.py`, `test_crud_error_paths.py`, and `test_organization_async.py` due to the removal of corresponding deprecated CRUD implementations.
- Improved codebase maintainability and reduced test suite noise by eliminating obsolete test files.
2025-11-01 05:48:20 +01:00
Felipe Cardoso
efcf10f9aa Remove unused async database and CRUD modules
- Deleted `database_async.py`, `base_async.py`, and `organization_async.py` modules due to deprecation and unused references across the project.
- Improved overall codebase clarity and minimized redundant functionality by removing unused async database logic, CRUD utilities, and organization-related operations.
2025-11-01 05:47:43 +01:00
Felipe Cardoso
ee938ce6a6 Add extensive form tests and enhanced error handling for auth components.
- Introduced comprehensive tests for `RegisterForm`, `PasswordResetRequestForm`, and `PasswordResetConfirmForm` covering successful submissions, validation errors, and API error handling.
- Refactored forms to handle unexpected errors gracefully and improve test coverage for edge cases.
- Updated `crypto` and `storage` modules with robust error handling for storage issues and encryption key management.
- Removed unused `axios-mock-adapter` dependency for cleaner dependency management.
2025-11-01 05:24:26 +01:00
Felipe Cardoso
035e6af446 Add comprehensive tests for session cleanup and async CRUD operations; improve error handling and validation across schemas and API routes
- Introduced extensive tests for session cleanup, async session CRUD methods, and concurrent cleanup to ensure reliability and efficiency.
- Enhanced `schemas/users.py` with reusable password strength validation logic.
- Improved error handling in `admin.py` routes by replacing `detail` with `message` for consistency and readability.
2025-11-01 05:22:45 +01:00
Felipe Cardoso
c79b76be41 Remove and reorder unused imports across the project for cleaner and more consistent code structure 2025-11-01 04:50:43 +01:00
Felipe Cardoso
61173d0dc1 Refactor authentication and session management for optimized performance, enhanced security, and improved error handling
- Replaced N+1 deletion pattern with a bulk `DELETE` in session cleanup for better efficiency in `session_async`.
- Updated security utilities to use HMAC-SHA256 signatures to mitigate length extension attacks and added constant-time comparisons to prevent timing attacks.
- Improved exception hierarchy with custom error types `AuthError` and `DatabaseError` for better granularity in error handling.
- Enhanced logging with `exc_info=True` for detailed error contexts across authentication services.
- Removed unused imports and reordered imports for cleaner code structure.
2025-11-01 04:50:01 +01:00
Felipe Cardoso
ea544ecbac Refactor useAuth hooks for improved type safety, error handling, and compliance with auto-generated API client
- Migrated `useAuth` hooks to use functions from auto-generated API client for improved maintainability and OpenAPI compliance.
- Replaced manual API calls with SDK functions (`login`, `register`, `logout`, etc.) and added error type guards for runtime safety (`isTokenWithUser`, `isSuccessResponse`).
- Enhanced hooks with better error logging, optional success callbacks, and stricter type annotations.
- Refactored `Logout` and `LogoutAll` mutations to handle missing tokens gracefully and clear local state on server failure.
- Added tests for API type guards and updated functionality of hooks to validate proper behaviors.
- Removed legacy `client-config.ts` to align with new API client utilization.
- Improved inline documentation for hooks with detailed descriptions and usage guidance.
2025-11-01 04:25:44 +01:00
Felipe Cardoso
3ad48843e4 Update tests for security and validation improvements
- Adjusted test case for duplicate email registration to assert 400 status and include generic error messaging to prevent user enumeration.
- Annotated invalid phone number example with clarification on cleaning behavior.
- Updated test password to meet enhanced security requirements.
2025-11-01 04:00:51 +01:00
Felipe Cardoso
544be2bea4 Remove deprecated authStore and update implementation plan progress tracking
- Deleted `authStore` in favor of updated state management and authentication handling.
- Updated `IMPLEMENTATION_PLAN.md` with revised checklist and Phase 2 completion details.
2025-11-01 03:53:45 +01:00
Felipe Cardoso
3fe5d301f8 Refactor authentication services to async password handling; optimize bulk operations and queries
- Updated `verify_password` and `get_password_hash` to their async counterparts to prevent event loop blocking.
- Replaced N+1 query patterns in `admin.py` and `session_async.py` with optimized bulk operations for improved performance.
- Enhanced `user_async.py` with bulk update and soft delete methods for efficient user management.
- Added eager loading support in CRUD operations to prevent N+1 query issues.
- Updated test cases with stronger password examples for better security representation.
2025-11-01 03:53:22 +01:00
Felipe Cardoso
819f3ba963 Add tests for useAuth hooks and AuthGuard component; Update .gitignore
- Implemented comprehensive tests for `useAuth` hooks (`useIsAuthenticated`, `useCurrentUser`, and `useIsAdmin`) with mock states and coverage for edge cases.
- Added tests for `AuthGuard` to validate route protection, admin access control, loading states, and use of fallback components.
- Updated `.gitignore` to exclude `coverage.json`.
2025-11-01 01:31:22 +01:00
Felipe Cardoso
9ae89a20b3 Refactor error handling, validation, and schema logic; improve query performance and add shared validators
- Added reusable validation functions (`validate_password_strength`, `validate_phone_number`, etc.) to centralize schema validation in `validators.py`.
- Updated `schemas/users.py` to use shared validators, simplifying and unifying validation logic.
- Introduced new error codes (`AUTH_007`, `SYS_005`) for enhanced error specificity.
- Refactored exception handling in admin routes to use more appropriate error types (`AuthorizationError`, `DuplicateError`).
- Improved organization query performance by replacing N+1 queries with optimized methods for member counts and data aggregation.
- Strengthened security in JWT decoding to prevent algorithm confusion attacks, with strict validation of required claims and algorithm enforcement.
2025-11-01 01:31:10 +01:00
Felipe Cardoso
c58cce358f Refactor form error handling with type guards, enhance API client configuration, and update implementation plan
- Introduced `isAPIErrorArray` type guard to improve error handling in authentication forms, replacing type assertions for better runtime safety.
- Refactored error handling logic across `RegisterForm`, `LoginForm`, `PasswordResetRequestForm`, and `PasswordResetConfirmForm` for unexpected error fallbacks.
- Updated `next.config.ts` and `.eslintrc.json` to exclude generated API client files from linting and align configuration with latest project structure.
- Added comprehensive documentation on Phase 2 completion in `IMPLEMENTATION_PLAN.md`.
2025-11-01 01:29:17 +01:00
Felipe Cardoso
38eb5313fc Improve error handling, logging, and security in authentication services and utilities
- Refactored `create_user` and `change_password` methods to add transaction rollback on failures and enhanced logging for error contexts.
- Updated security utilities to use constant-time comparison (`hmac.compare_digest`) to mitigate timing attacks.
- Adjusted API responses in registration and password reset flows for better security and user experience.
- Added session invalidation after password resets to enhance account security.
2025-11-01 01:13:19 +01:00
Felipe Cardoso
4de440ed2d Improve error handling, logging, and security in authentication services and utilities
- Refactored `create_user` and `change_password` methods to add transaction rollback on failures and enhanced logging for error contexts.
- Updated security utilities to use constant-time comparison (`hmac.compare_digest`) to mitigate timing attacks.
- Adjusted API responses in registration and password reset flows for better security and user experience.
- Added session invalidation after password resets to enhance account security.
2025-11-01 01:13:02 +01:00
Felipe Cardoso
cc98a76e24 Add timeout cleanup to password reset confirm page and improve accessibility attributes
- Added `useEffect` for proper timeout cleanup in `PasswordResetConfirmForm` to prevent memory leaks during unmount.
- Enhanced form accessibility by adding `aria-required` attributes to all required fields for better screen reader compatibility.
- Updated `IMPLEMENTATION_PLAN.md` to reflect completion of Password Reset Flow and associated quality metrics.
2025-11-01 01:01:56 +01:00
Felipe Cardoso
925950d58e Add password reset functionality with form components, pages, and tests
- Implemented `PasswordResetRequestForm` and `PasswordResetConfirmForm` components with email and password validation, strength indicators, and error handling.
- Added dedicated pages for requesting and confirming password resets, integrated with React Query hooks and Next.js API routes.
- Included tests for validation rules, UI states, and token handling to ensure proper functionality and coverage.
- Updated ESLint and configuration files for new components and pages.
- Enhanced `IMPLEMENTATION_PLAN.md` with updated task details and documentation for password reset workflows.
2025-11-01 00:57:57 +01:00
Felipe Cardoso
dbb05289b2 Add pytest-xdist to requirements for parallel test execution 2025-11-01 00:05:41 +01:00
Felipe Cardoso
f4be8b56f0 Remove legacy test files for auth, rate limiting, and users
- Deleted outdated backend test cases (`test_auth.py`, `test_rate_limiting.py`, `test_users.py`) to clean up deprecated test structure.
- These tests are now redundant with newer async test implementations and improved coverage.
2025-11-01 00:02:17 +01:00
Felipe Cardoso
31e2109278 Add auto-generated API client and update authStore tests
- Integrated OpenAPI-generated TypeScript SDK (`sdk.gen.ts`, `types.gen.ts`, `client.gen.ts`) for API interactions.
- Refactored `authStore` tests to include storage mock reset logic with default implementations.
2025-10-31 23:24:19 +01:00
Felipe Cardoso
b4866f9100 Remove old configuration, API client, and redundant crypto mocks
- Deleted legacy `config` module and replaced its usage with the new runtime-validated `app.config`.
- Removed old custom Axios `apiClient` with outdated token refresh logic.
- Cleaned up redundant crypto-related mocks in storage tests and replaced them with real encryption/decryption during testing.
- Updated Jest coverage exclusions to reflect the new file structure and generated client usage.
2025-10-31 23:04:53 +01:00
Felipe Cardoso
092a82ee07 Add async-safe polyfills, Jest custom config, and improved token validation
- Introduced Web Crypto API polyfills (`@peculiar/webcrypto`) for Node.js to enable SSR-safe cryptography utilities.
- Added Jest setup file for global mocks (e.g., `localStorage`, `sessionStorage`, and `TextEncoder/Decoder`).
- Enhanced token validation behavior in `storage` tests to reject incomplete tokens.
- Replaced runtime configuration validation with clamping using `parseIntSafe` constraints for improved reliability.
- Updated `package.json` and `package-lock.json` to include new dependencies (`@peculiar/webcrypto` and related libraries).
2025-10-31 22:41:18 +01:00
Felipe Cardoso
92a8699479 Convert password reset and auth dependencies tests to async
- Refactored all `password reset` and `auth dependency` tests to utilize async patterns for compatibility with async database sessions.
- Enhanced test fixtures with `pytest-asyncio` to support asynchronous database operations.
- Improved user handling with async context management for `test_user` and `async_mock_user`.
- Introduced `await` syntax for route calls, token generation, and database transactions in test cases.
2025-10-31 22:31:01 +01:00
Felipe Cardoso
8a7a3b9521 Replace crypto tests with comprehensive unit tests for authStore, storage, and configuration modules
- Removed outdated `crypto` tests; added dedicated and structured tests for `authStore`, `storage`, and `app.config`.
- Enhanced test coverage for user and token validation, secure persistence, state management, and configuration parsing.
- Consolidated encryption and storage error handling with thorough validation to ensure SSR-safety and resilience.
- Improved runtime validations for tokens and configuration with stricter type checks and fallback mechanisms.
2025-10-31 22:25:50 +01:00
Felipe Cardoso
6d811747ee Enhance input validation and error handling in authStore
- Added robust validation for `user` object fields to ensure non-empty strings.
- Improved `calculateExpiry` with value range checks and warnings for invalid `expiresIn`.
- Incorporated try-catch in `initializeAuth` to log errors and prevent app crashes during auth initialization.
2025-10-31 22:10:48 +01:00
Felipe Cardoso
76023694f8 Add SSR-safe checks and improve error handling for token storage and encryption
- Introduced SSR guards for browser APIs in `crypto` and `storage` modules.
- Enhanced resilience with improved error handling for encryption key management, token storage, and retrieval.
- Added validation for token structure and fallback mechanisms for corrupted data.
- Refactored localStorage handling with explicit availability checks for improved robustness.
2025-10-31 22:09:20 +01:00
Felipe Cardoso
cf5bb41c17 Refactor config, auth, and storage modules with runtime validation and encryption
- Centralized and refactored configuration management (`config`) with runtime validation for environment variables.
- Introduced utilities for secure token storage, including AES-GCM encryption and fallback handling.
- Enhanced `authStore` state management with token validation, secure persistence, and initialization from storage.
- Modularized authentication utilities and updated export structure for better maintainability.
- Improved error handling, input validation, and added detailed comments for enhanced clarity.
2025-10-31 22:00:45 +01:00
Felipe Cardoso
1f15ee6db3 Add async CRUD classes for organizations, sessions, and users
- Implemented `CRUDOrganizationAsync`, `CRUDSessionAsync`, and `CRUDUserAsync` with full async support for database operations.
- Added filtering, sorting, pagination, and advanced methods for organization management.
- Developed session-specific logic, including cleanup, per-device management, and security enhancements.
- Enhanced user CRUD with password hashing and comprehensive update handling.
2025-10-31 21:59:40 +01:00
Felipe Cardoso
26ff08d9f9 Refactor backend to adopt async patterns across services, API routes, and CRUD operations
- Migrated database sessions and operations to `AsyncSession` for full async support.
- Updated all service methods and dependencies (`get_db` to `get_async_db`) to support async logic.
- Refactored admin, user, organization, session-related CRUD methods, and routes with await syntax.
- Improved consistency and performance with async SQLAlchemy patterns.
- Enhanced logging and error handling for async context.
2025-10-31 21:57:12 +01:00
Felipe Cardoso
19ecd04a41 Add foundational API client, UI components, and state management setup
- Created `generate-api-client.sh` for OpenAPI-based TypeScript client generation.
- Added `src/lib/api` with Axios-based API client, error handling utilities, and placeholder for generated types.
- Implemented Zustand-based `authStore` for user authentication and token management.
- Integrated reusable UI components (e.g., `Dialog`, `Select`, `Textarea`, `Sheet`, `Separator`, `Checkbox`) using Radix UI and utility functions.
- Established groundwork for client-server integration, state management, and modular UI development.
2025-10-31 21:46:03 +01:00
Felipe Cardoso
9554782202 Update dependencies in package-lock.json
- Upgraded project dependencies and development tools.
- Added various libraries including `@hookform/resolvers`, `@radix-ui/react-*`, `axios`, `react-hook-form`, and others.
- Enhanced dev dependencies with testing libraries like `@testing-library/*`, `jest`, and configurations for API codegen.
2025-10-31 21:33:06 +01:00
Felipe Cardoso
59f8c8076b Add comprehensive frontend requirements document
- Created `frontend-requirements.md` outlining detailed specifications for a production-ready Next.js + FastAPI template.
- Documented technology stack, architecture, state management, authentication flows, API integration, UI components, and developer guidelines.
- Provided a complete directory layout, coding conventions, and error handling practices.
- Aimed to establish a solid foundation for modern, scalable, and maintainable web application development.
2025-10-31 21:26:33 +01:00
Felipe Cardoso
e8156b751e Add async coding standards and common pitfalls documentation
- Updated `CODING_STANDARDS.md` with async SQLAlchemy patterns, modern Python type hints, and new error handling examples.
- Introduced a new `COMMON_PITFALLS.md` file detailing frequent implementation mistakes and explicit rules to prevent them.
- Covered database optimizations, validation best practices, FastAPI design guidelines, security considerations, and Python language issues.
- Aimed to enhance code quality and reduce recurring mistakes during development.
2025-10-31 19:24:00 +01:00
Felipe Cardoso
86f67a925c Add detailed backend architecture documentation
- Created `ARCHITECTURE.md` with an extensive overview of backend design, principles, and project structure.
- Documented key architectural layers: API, dependencies, services, CRUD, and data layers.
- Included comprehensive guidelines for database architecture, authentication/authorization, error handling, and testing strategy.
- Provided examples for each layer, security practices, and performance considerations.
- Aimed at improving developer onboarding and ensuring consistent implementation practices.
2025-10-31 19:02:46 +01:00
Felipe Cardoso
80c26c3df2 Enhance security headers middleware with configurable CSP modes
- Introduced `CSP_MODE` setting with `strict`, `relaxed`, and `disabled` options for flexible content security policies.
- Updated middleware to apply varying CSP rules based on mode and request context (e.g., API docs).
- Improved security and frontend compatibility with detailed policy definitions for external resources.
- Defaulted `CSP_MODE` to `relaxed`, ensuring balanced security and usability in modern applications.
2025-10-31 12:50:34 +01:00
Felipe Cardoso
2d909774df Add organization management and admin-specific APIs
- Introduced schemas for organizations, including creation, updates, and responses.
- Created models for `Organization` and `UserOrganization` with role-based access control and relationships.
- Implemented admin APIs for managing users, organizations, and bulk actions.
- Added advanced filtering, sorting, and pagination for user and organization queries.
- Updated `CRUD` logic to support organization-specific operations and member management.
- Enhanced database with necessary indexes and validation for improved performance and data integrity.
2025-10-31 12:18:43 +01:00
Felipe Cardoso
e19026453f Add session management API, cleanup service, and session-specific tests
- Introduced session management endpoints to list, revoke, and cleanup sessions per user.
- Added cron-based job for periodic cleanup of expired sessions.
- Implemented `CRUDSession` for session-specific database operations.
- Integrated session cleanup startup and shutdown events in the application lifecycle.
- Enhanced CORS configuration to include `X-Device-Id` for session tracking.
- Added comprehensive integration tests for multi-device login, per-device logout, session listing, and cleanup logic.
2025-10-31 08:30:18 +01:00
Felipe Cardoso
b42a29faad Add user session tracking, schemas, utilities, and per-device session management
- Introduced `user_sessions` table with support for per-device authentication sessions.
- Added `UserSession` model, including fields for device metadata, IP, and session state.
- Created schemas (`SessionBase`, `SessionCreate`, `SessionResponse`) to manage session data and responses.
- Implemented utilities for extracting and parsing device information from HTTP requests.
- Added Alembic migration to define `user_sessions` table with indexes for performance and cleanup.
2025-10-31 07:56:35 +01:00
Felipe Cardoso
e767920407 Add extensive tests for user routes, CRUD error paths, and coverage configuration
- Implemented comprehensive tests for user management API endpoints, including edge cases, error handling, and permission validations.
- Added CRUD tests focusing on exception handling in database operations, soft delete, and update scenarios.
- Introduced custom `.coveragerc` for enhanced coverage tracking and exclusions.
- Improved test reliability by mocking rate-limiting configurations and various database errors.
2025-10-30 17:54:14 +01:00
Felipe Cardoso
defa33975f Add comprehensive test coverage for email service, password reset endpoints, and soft delete functionality
- Introduced unit tests for `EmailService` covering `ConsoleEmailBackend` and `SMTPEmailBackend`.
- Added tests for password reset request and confirmation endpoints, including edge cases and error handling.
- Implemented soft delete CRUD tests to validate `deleted_at` behavior and data exclusion in queries.
- Enhanced API tests for email functionality and user management workflows.
2025-10-30 17:18:25 +01:00
Felipe Cardoso
182b12b2d5 Add password reset functionality, email service, and related API endpoints
- Introduced endpoints for requesting and confirming password resets.
- Implemented token-based password reset logic with validation checks.
- Added `EmailService` with `ConsoleEmailBackend` and placeholder for SMTP backend.
- Integrated password reset flow in `auth` API routes with rate limiting.
- Updated schemas for password reset requests and token confirmation.
- Refined validation for secure password updates and token verification.
- Enhanced configuration with `FRONTEND_URL` for email links.
2025-10-30 16:54:18 +01:00
Felipe Cardoso
313e6691b5 Add async CRUD base, async database configuration, soft delete for users, and composite indexes
- Introduced `CRUDBaseAsync` for reusable async operations.
- Configured async database connection using SQLAlchemy 2.0 patterns with `asyncpg`.
- Added `deleted_at` column and soft delete functionality to the `User` model, including related Alembic migration.
- Optimized queries by adding composite indexes for common user filtering scenarios.
- Extended tests: added cases for token-based security utilities and user management endpoints.
2025-10-30 16:45:01 +01:00
Felipe Cardoso
c684f2ba95 Add UUID handling, sorting, filtering, and soft delete functionality to CRUD operations
- Enhanced UUID validation by supporting both string and `UUID` formats.
- Added advanced filtering and sorting capabilities to `get_multi_with_total` method.
- Introduced soft delete and restore functionality for models with `deleted_at` column.
- Updated tests to reflect new endpoints and rate-limiting logic.
- Improved schema definitions with `SortParams` and `SortOrder` for consistent API inputs.
2025-10-30 16:44:15 +01:00
Felipe Cardoso
2c600290a1 Enhance user management, improve API structure, add database optimizations, and update Docker setup
- Introduced endpoints for user management, including CRUD operations, pagination, and password management.
- Added new schema validations for user updates, password strength, pagination, and standardized error responses.
- Integrated custom exception handling for a consistent API error experience.
- Refined CORS settings: restricted methods and allowed headers, added header exposure, and preflight caching.
- Optimized database: added indexes on `is_active` and `is_superuser` fields, updated column types, enforced constraints, and set defaults.
- Updated `Dockerfile` to improve security by using a non-root user and adding a health check for the application.
- Enhanced tests for database initialization, user operations, and exception handling to ensure better coverage.
2025-10-30 15:43:52 +01:00
Felipe Cardoso
d83959963b Add security headers middleware and tests; improve user model schema
- Added security headers middleware to enforce best practices (e.g., XSS and clickjacking prevention, CSP, HSTS in production).
- Updated `User` model schema: refined field constraints and switched `preferences` to `JSONB` for PostgreSQL compatibility.
- Introduced tests to validate security headers across endpoints and error responses.
- Ensured headers like `X-Frame-Options`, `X-Content-Type-Options`, and `Permissions-Policy` are correctly configured.
2025-10-30 08:30:21 +01:00
Felipe Cardoso
5bed14b6b0 Add rate-limiting for authentication endpoints and health check feature
- Introduced rate-limiting to `/auth/*` routes with configurable limits using `SlowAPI`.
- Added `/health` endpoint for service monitoring and load balancer health checks.
- Updated `requirements.txt` to include `SlowAPI` for rate limiting.
- Implemented tests for rate-limiting and health check functionality.
- Enhanced configuration and security with updated environment variables, pinned dependencies, and validation adjustments.
- Provided example usage and extended coverage in testing.
2025-10-29 23:59:29 +01:00
Felipe Cardoso
f163ffbb83 Add validation for SECRET_KEY and FIRST_SUPERUSER_PASSWORD with environment-specific rules
- Enforced minimum length and security standards for `SECRET_KEY` (32 chars, random value required in production).
- Added checks for strong `FIRST_SUPERUSER_PASSWORD` (min 12 chars with mixed case, digits).
- Updated `.env.template` with guidelines for secure configurations.
- Added `test_config.py` to verify validations for environment configurations, passwords, and database URLs.
2025-10-29 23:00:55 +01:00
Felipe Cardoso
54e389d230 Add package-lock.json for package version consistency and dependency management. 2025-10-29 22:52:14 +01:00
Felipe Cardoso
778da09a42 Expand README with detailed documentation on project structure, backend features, development workflows, and deployment instructions. 2025-10-29 22:30:48 +01:00