User APIs Implementation¶
Date: December 13, 2025
Status: ✅ Complete
Location: backend/app/modules/users/
Overview¶
Implemented 5 user management APIs based on the old FastAPI project structure, adapted to the new monorepo's modular architecture. These APIs are now testable via the frontend user dropdown menu.
APIs Implemented¶
1. Signin¶
- Endpoint:
POST /api/v1/users/signin - Purpose: Authenticate user with email and password
- Request:
- Response:
2. Get User Info¶
- Endpoint:
POST /api/v1/users/info - Purpose: Get user information for authenticated session
- Request:
- Response:
3. Get Sessions¶
- Endpoint:
POST /api/v1/users/sessions - Purpose: List all active sessions for user
- Request:
- Response:
4. Signout User¶
- Endpoint:
POST /api/v1/users/signout - Purpose: Invalidate current session
- Request:
- Response:
5. Signout Multiple Sessions¶
- Endpoint:
POST /api/v1/users/signout-sessions - Purpose: Invalidate multiple sessions by IDs
- Request:
- Response:
Demo Credentials¶
For testing purposes, two users are available:
- Admin User
- Email:
admin@example.com - Password:
admin123 -
ID: 1
-
Test User
- Email:
user@example.com - Password:
user123 - ID: 2
Architecture Notes¶
Backend Structure¶
backend/app/modules/users/
├── router.py # API endpoints
├── schemas.py # Pydantic models (request/response)
├── service.py # Business logic
└── repository.py # Data access (not yet used)
Key Design Decisions¶
- Module Location: Placed in
modules/users/(notdomains/users/) - Reasoning: User management is a supporting feature, not a core business domain
-
Aligns with DDD principles: modules for infrastructure, domains for business logic
-
In-Memory Storage: Currently using dictionaries for demo
USERS_DB: Stores user credentials and infoSESSIONS_DB: Stores active sessions-
Note: Replace with PostgreSQL + Redis in production
-
Session Management:
- 24-hour session expiration
- Secure token generation (32-byte urlsafe)
-
SHA256 password hashing (replace with bcrypt/argon2 in production)
-
Security Considerations:
- Session tokens truncated in responses
- Password hashing (basic SHA256 for demo)
- Session validation on each request
- Last activity tracking
Frontend Integration¶
User Dropdown Test Menu¶
Added 4 new test functions to frontend/src/shared/components/layout/user-dropdown.tsx:
- Test Signin: Authenticates with admin credentials
- Test User Info: Signs in and fetches user data
- Test Sessions: Signs in and lists active sessions
- Test Signout: Signs in and immediately signs out
Access: Click user avatar → Test submenu → Select test
Test Flow Example¶
1. User clicks "Test Signin"
→ POST /api/v1/users/signin
→ Returns session token
→ Success toast with truncated token
2. User clicks "Test User Info"
→ POST /api/v1/users/signin (gets session)
→ POST /api/v1/users/info (with session)
→ Returns user details
→ Success toast with name and email
3. User clicks "Test Sessions"
→ POST /api/v1/users/signin
→ POST /api/v1/users/sessions
→ Returns session count
→ Success toast with total count
4. User clicks "Test Signout"
→ POST /api/v1/users/signin
→ POST /api/v1/users/signout
→ Invalidates session
→ Success toast confirming signout
Next Steps (Production Readiness)¶
High Priority¶
- Database Integration
- Create
userstable in PostgreSQL - Create
sessionstable with indexes - Implement repository layer (repository.py)
-
Add SQLAlchemy models
-
Security Enhancements
- Replace SHA256 with bcrypt/argon2id
- Add rate limiting (signin attempts)
- Implement CSRF protection
- Add IP address and user agent tracking
-
Session fingerprinting
-
Redis Integration
- Store sessions in Redis instead of memory
- Add session TTL with automatic cleanup
- Implement session refresh mechanism
Medium Priority¶
- Validation & Error Handling
- Email validation (proper regex)
- Password strength requirements
- Brute force protection
-
Account lockout after failed attempts
-
Observability
- Add Sentry error tracking
- Structured logging for audit trail
- Metrics for signin attempts/success/failures
-
Performance monitoring
-
Testing
- Unit tests for service layer
- Integration tests for endpoints
- Load testing for concurrent sessions
- Security testing (OWASP)
Low Priority¶
- Features
- Password reset flow
- Email verification
- 2FA/MFA support
- Remember me functionality
- Device management
Usage Examples¶
cURL Examples¶
Signin:
curl -X POST http://localhost:8000/api/v1/users/signin \
-H "Content-Type: application/json" \
-d '{"login":"admin@example.com","password":"admin123"}'
Get User Info:
curl -X POST http://localhost:8000/api/v1/users/info \
-H "Content-Type: application/json" \
-d '{"session":"YOUR_SESSION_TOKEN"}'
Get Sessions:
curl -X POST http://localhost:8000/api/v1/users/sessions \
-H "Content-Type: application/json" \
-d '{"session":"YOUR_SESSION_TOKEN"}'
Signout:
curl -X POST http://localhost:8000/api/v1/users/signout \
-H "Content-Type: application/json" \
-d '{"session":"YOUR_SESSION_TOKEN"}'
Logging Examples¶
All APIs include structured logging:
# Signin attempt
logger.info("User signin attempt", extra={"email": "admin@example.com"})
# Successful authentication
logger.info("User signin successful", extra={
"email": "admin@example.com",
"user_id": 1
})
# Failed authentication
logger.warning("Signin failed: invalid password", extra={"email": "admin@example.com"})
# Session validation
logger.warning("Get user info failed: invalid session")
# Signout
logger.info("User signed out", extra={"user_id": 1})
Observability Integration¶
These APIs are perfect for testing your observability stack:
- Structured Logging: All operations logged with correlation IDs
- Error Handling: Try invalid credentials → see error logs
- Tracing: Each request gets traced through service layer
- Metrics: Count signin attempts, failures, active sessions
Test Scenarios for Observability¶
- Successful Flow: Signin → Get Info → Get Sessions → Signout
- Verify logs appear in Loki
- Check traces in Tempo
-
Monitor metrics in Prometheus
-
Error Flow: Invalid credentials, expired session
- Verify error logs captured
- Check Sentry exceptions (when integrated)
-
Monitor error rate metrics
-
Performance: Multiple concurrent signins
- Check response time metrics
- Monitor session creation rate
- Verify database connection pool (when integrated)
Files Modified¶
Backend¶
- ✅
backend/app/modules/users/schemas.py- Added 13 new schemas - ✅
backend/app/modules/users/service.py- Added 5 service functions + helpers - ✅
backend/app/modules/users/router.py- Added 5 API endpoints
Frontend¶
- ✅
frontend/src/shared/components/layout/user-dropdown.tsx- Added 4 test handlers
Documentation¶
- ✅
docs/AI-GUIDES/USER-APIS-IMPLEMENTATION.md- This file
API Testing Checklist¶
From the frontend user dropdown "Test" menu:
- Test Connection (existing)
- Ping (existing)
- Test Signin (new) - Should show success with session token
- Test User Info (new) - Should show user name and email
- Test Sessions (new) - Should show active session count
- Test Signout (new) - Should confirm session invalidated
All tests should show success toasts with relevant data!
Comparison with Old Project¶
What Changed¶
- Structure: Old project had flat structure → New has modular DDD structure
- Routing: Old used direct paths → New uses
/api/v1prefix with router composition - Schemas: Old had inline models → New has proper Pydantic schemas in schemas.py
- Service Layer: Old mixed logic in routes → New has clean separation (router → service → repository)
- Logging: Old had print statements → New has structured logging with correlation IDs
What Stayed the Same¶
- API Contracts: Request/response formats match (for compatibility)
- Business Logic: Signin, session management, signout flow identical
- Demo Credentials: Same test users for easy testing
- Error Handling: Similar error messages and status codes
Integration with Observability¶
Now that you have working APIs, you can:
- Test Sentry Integration:
- Implement Sentry exception tracking
- Test with invalid signin attempts
-
See errors in Sentry dashboard
-
Test Distributed Tracing:
- Enable OpenTelemetry tracing
- Trace signin → get_user_info flow
-
See spans in Grafana Tempo
-
Test Audit Logging:
- Log all signin/signout events
- Track session creation/invalidation
-
Store in dedicated audit log table
-
Test Metrics:
- Count signin attempts (success/failure)
- Track active session count
- Monitor API response times
Summary¶
✅ Implemented: 5 user management APIs (signin, user info, sessions, signout operations) ✅ Frontend Testing: Added 4 test buttons to user dropdown menu ✅ Demo Ready: Two test users with working credentials ✅ Architecture: Clean modular structure following DDD principles ✅ Logging: Structured logging on all operations ✅ Documentation: Complete API docs with examples
Next: Use these APIs to test your observability infrastructure (Sentry, OpenTelemetry, audit logging)!