Commit Graph

16 Commits

Author SHA1 Message Date
david 5d92820591 Remove timezone from User model and pass as request parameter
Timezone is now sent from the client on each request that needs it,
instead of storing it in the database. This simplifies the model and
allows timezone to be dynamic (useful for traveling users).

Changes:
- Remove timezone field from User entity
- Remove timezone from user registration
- GET /habits/today now requires ?timezone= query param
- Add migration to drop timezone column from database
- Update related tests
2025-11-29 16:18:04 +01:00
david 8d631f8fab Improve README SEO and increase test coverage to 50%
Optimized README for better discoverability with keywords: api, habits, self-hosted. Consolidated content to reduce redundancy while maintaining clarity.

Added comprehensive test coverage across multiple layers:
- Infrastructure: bcrypt hashing, JWT tokens, configuration validation
- Application commands: user deletion, password reset, token revocation, email verification
- Application queries: login, token refresh
- Domain entities: refresh tokens, password reset tokens

Coverage increased from 42.5% to 50.8% with meaningful business logic tests.

Fixed integration test handler initialization with correct parameters.
2025-11-28 17:59:39 +01:00
david f37c1ac19b Improve email verification flow and error handling
- Send verification email before creating user to prevent orphaned accounts
- Detect SMTP authentication errors and fail fast without retries
- Add field-level validation errors for better frontend UX
- Configure docker-compose with explicit environment variables
- Document dollar sign escaping in .env.example (use $$)
- Implement welcome email on successful verification
- Clean up unnecessary comments
2025-11-28 11:32:51 +01:00
david 00f6b51228 Add optional email verification and registration control
Implemented email service infrastructure with SMTP support and optional email verification for self-hosted deployments. Registration flow now supports open/closed modes and hardcoded Apocapoc branding.

Key features:
- Email service with SMTP and template rendering
- Optional email verification (auto-verified without SMTP config)
- Registration modes: open/closed for access control
- Hardcoded Apocapoc branding (AppName, AppURL, DefaultFrom)
- Separate registration and login flows (registration no longer returns tokens)
2025-11-28 08:21:51 +01:00
david 7cb2756b67 Implement Sprint 2 security enhancements
CI/CD Pipeline / Test (push) Has been cancelled
CI/CD Pipeline / Lint (push) Has been cancelled
CI/CD Pipeline / Build and Push Docker Image (push) Has been cancelled
Add user-based rate limiting middleware (100 req/min) for authenticated endpoints using httprate library. Implement common password validation blocking 50+ weak passwords. Improve test coverage from 38.3% to 44.6% with comprehensive refresh token tests.

Security improvements:
- Rate limiting by user ID for /habits and /stats endpoints
- X-RateLimit-Limit header in responses
- Common password blacklist in password validation
- Refresh token test suite with 5 scenarios (valid, invalid, expired, revoked, empty)
2025-11-27 10:33:01 +01:00
david bbe0757ab6 Add refresh token authentication system
CI/CD Pipeline / Test (push) Has been cancelled
CI/CD Pipeline / Lint (push) Has been cancelled
CI/CD Pipeline / Build and Push Docker Image (push) Has been cancelled
Implement complete refresh token flow for improved security:
- Short-lived access tokens (configurable, default 1h)
- Long-lived refresh tokens (configurable, default 7d)
- Automatic token rotation on refresh
- Token revocation for proper logout

Domain layer:
- Add RefreshToken entity with validation and revocation
- Add RefreshTokenRepository interface

Application layer:
- Add RefreshTokenHandler for token refresh operations
- Add RevokeTokenHandler for single token revocation
- Add RevokeAllTokensHandler for user-wide revocation

Infrastructure layer:
- Implement SQLite RefreshTokenRepository
- Add refresh_tokens table migration with indexes
- Add parseDuration helper for flexible time configuration

HTTP layer:
- Add POST /api/v1/auth/refresh endpoint
- Add POST /api/v1/auth/logout endpoint
- Update login/register to return refresh tokens
- Improve Swagger documentation with clear descriptions

Configuration:
- Update .env.example with secure token expiry defaults
- Add support for minute/hour/day duration formats

Tests:
- Fix test suite to work with new signatures
- All existing tests passing
2025-11-27 09:57:54 +01:00
david 10d45fc34e Add COUNTER type with auto-increment and IsNegative field
COUNTER type:
- Only accepts integer values (rejects decimals)
- Auto-increment behavior: each mark adds to existing value
- Supports decrement via negative values (e.g., -2)
- Enforces minimum value of 0 (never negative)
- Default increment is 1 if no value provided

VALUE type:
- Accepts decimal values
- Replaces value (no auto-increment)

IsNegative field:
- New boolean field on Habit entity
- Persisted in database (is_negative column)
- Available in all DTOs and HTTP responses
- Marks habits as "negative" (e.g., candy consumption)

Examples:
- COUNTER: 5 + (-2) = 3, 2 + (-3) = 0, 0 + (-1) = 0
- VALUE: 5000 → 12000 = 12000 (replacement)
2025-11-27 08:58:39 +01:00
david 358f844073 Remove unnecessary comments from codebase
Clean up obvious and redundant comments that don't add value:
- Remove step-by-step comments in command handlers
- Remove obvious test setup comments
- Keep only meaningful comments that explain why, not what
2025-11-27 00:48:50 +01:00
david ca2533d4df Improve type safety with proper value objects for HabitType and Frequency
Replace generic string types with strongly-typed value objects throughout
the application layer. This change ensures compile-time type checking and
automatic validation during JSON deserialization.

Changes:
- Add JSON marshaling/unmarshaling to HabitType and Frequency value objects
- Update all DTOs to use typed fields instead of strings
- Update commands and queries to use proper types
- Remove unnecessary string conversions
- Add comprehensive JSON serialization tests
- Fix existing tests to work with typed fields

Benefits:
- Type safety: compiler catches invalid usage
- Automatic validation: invalid values rejected during JSON parsing
- Better code documentation and self-explanatory APIs
- Reduced runtime errors
2025-11-27 00:39:45 +01:00
david 7768037724 Add robust input validation system and fix test suite
- Add comprehensive validation package with email (RFC 5322), password strength, and IANA timezone validation
- Implement strict password requirements: min 8 chars, uppercase, lowercase, digit, special character
- Integrate validation into RegisterUserHandler with complete test coverage (59 validation tests + 25 handler tests)
- Fix pre-existing test failures:
  - Remove tests for non-existent HabitEntry.DeletedAt and Delete() methods
  - Replace deprecated HabitTypeQuantity with HabitTypeValue
  - Add missing FindByHabitIDAndDateRange mock implementation
- Remove hardcoded localhost:8080 from Swagger config for self-hosted flexibility
2025-11-27 00:17:18 +01:00
david 4c8f3022f0 Refactor password hashing to follow DIP and improve CI/CD
CI/CD Pipeline / Test (push) Has been cancelled
CI/CD Pipeline / Lint (push) Has been cancelled
CI/CD Pipeline / Build and Push Docker Image (push) Has been cancelled
- Create PasswordHasher interface in domain layer
- Implement BcryptHasher in infrastructure layer
- Update RegisterUserHandler and LoginUserHandler to use interface
- Remove bcrypt dependency from application layer
- Update main.go and integration tests with dependency injection
- Enhance CI/CD workflow with test and lint jobs
- Add code coverage check (minimum 50%)
- Add go vet and gofmt validation
- Configure build job to depend on test and lint passing
- Update GitHub Actions to latest versions (v4→v5)

This achieves 100% SOLID compliance (DIP) and ensures Clean Architecture
by removing external library dependencies from application/domain layers.
2025-11-26 21:39:52 +01:00
david 9f673bfca3 Refactor habit entries: remove soft delete and add smart pagination
Remove soft delete from HabitEntry:
- Eliminate DeletedAt field from entity and database
- Change UnmarkHabit from soft delete to hard delete
- Simplify all queries removing deleted_at checks
- Update migration to remove deleted_at column

Add date filtering and smart pagination to GetHabitEntries:
- Support optional from/to date parameters
- Implement intelligent pagination rules:
  * No date range: pagination required
  * Date range > 1 year: pagination required
  * Date range ≤ 1 year: pagination optional
- Pagination defaults (page=1, limit=50) only when required
- Return metadata with total count, page, and limit

Technical improvements:
- Cleaner codebase without soft delete complexity
- Better performance (no filtering in queries)
- More intuitive API with flexible pagination
- Comprehensive test coverage for validation rules
2025-11-26 16:33:40 +01:00
david e87b7df979 Rename project to apocapoc-api
Update module name and all imports from habit-tracker-api to apocapoc-api.
This reflects the project's new branding as part of the apocapoc ecosystem
(apocapoc-api, apocapoc-web, apocapoc-android).
2025-11-26 11:21:17 +01:00
david 0977d3a58b Implement SQLite persistence layer (TDD)
- Add SQLite and UUID dependencies (go-sqlite3, google/uuid)
- Create database connection with automatic migrations
- Implement UserRepository with full CRUD operations
- Implement HabitRepository with JSON serialization for arrays
- Implement HabitEntryRepository with date range queries
- Add comprehensive test coverage for all repositories
- Fix User entity to default timezone to UTC when empty
- All tests passing with TDD approach (Red-Green-Refactor)
2025-11-25 14:29:51 +01:00
david 64bfe80806 Implement domain layer (TDD - Green phase)
Implementation to make all tests pass:

Value Objects:
- HabitType: BOOLEAN, COUNTER, VALUE with validation
- Frequency: DAILY, WEEKLY, MONTHLY with validation

Entities:
- User: email, password hash, timezone with defaults
- Habit: tracking habits with type, frequency, carry-over
- HabitEntry: recording habit completions with soft delete

Repositories (interfaces):
- UserRepository: CRUD operations for users
- HabitRepository: CRUD operations for habits
- HabitEntryRepository: CRUD operations for entries

Shared:
- Common error definitions for domain layer

All domain tests now pass.
2025-11-25 10:13:08 +01:00
david 664f7a0de0 Add domain layer tests (TDD - Red phase)
Following TDD principles, adding tests before implementation:

- Add HabitType value object tests (validation)
- Add Frequency value object tests (validation)
- Add User entity tests (creation, default timezone)
- Add Habit entity tests (creation, archive, active status)
- Add HabitEntry entity tests (creation, soft delete)

Tests cover core domain logic and business rules.
All tests will fail until implementation is added.
2025-11-25 10:12:04 +01:00