Aniworld/instruction.md

239 lines
9.8 KiB
Markdown

# Aniworld Server Tasks
## Controller Usage Analysis
### Tasks to Complete
#### API Controllers
- [x] **Auth Controller**: Implement simple master password authentication
- ✅ Single master password check (no email/user system)
- ✅ JWT token generation and validation
- ✅ Token verification endpoint
- ✅ Logout endpoint (client-side token clearing)
- ✅ Proper error handling for invalid credentials
- ✅ Environment-based password hash configuration
- [ ] **Anime Controller**: Improve anime data handling
- Fix anime search functionality - currently returns empty results
- Implement proper pagination for anime list endpoints
- Add caching for frequently requested anime data
- [ ] **Episode Controller**: Complete episode management
- Missing episode progress tracking
- Need to implement episode streaming URL validation
- Add episode download status tracking
#### Service Layer Issues
- [ ] **Database Service**: Fix connection pooling
- Current implementation creates too many connections
- Add proper connection timeout handling
- Implement database health check endpoint
#### Repository Pattern Implementation
- [ ] **Anime Repository**: Optimize database queries
- Replace N+1 query issues with proper joins
- Add database indexing for search queries
- Implement query result caching
#### Configuration & Security
- [x] **Authentication Configuration**: Simple master password system
- ✅ No email or user management required
- ✅ Single master password stored as hash in environment
- ✅ JWT tokens for session management
- ✅ Configurable token expiry
- ✅ Secure password hashing with salt
- [ ] **Environment Configuration**: Secure sensitive data
- ✅ Master password hash in environment variables
- Add API key validation middleware (if needed for external APIs)
- Implement rate limiting for public endpoints
- [ ] **Error Handling**: Centralize error responses
- Create consistent error response format
- Add proper HTTP status codes
- Implement global exception handling middleware
#### Testing & Documentation
- [ ] **Unit Tests**: Add missing test coverage
- ✅ Auth controller tests for master password validation
- Missing integration tests for API endpoints
- Add performance tests for streaming endpoints
- [ ] **API Documentation**: Complete OpenAPI specifications
- ✅ Auth endpoints documented (login, verify, logout)
- Missing request/response schemas for other endpoints
- Add example requests and responses
#### Performance Optimizations
- [ ] **Caching Strategy**: Implement Redis caching
- Add caching for anime metadata
- Implement session caching (JWT tokens are stateless)
- Add cache invalidation strategy
- [ ] **Async Operations**: Convert blocking operations
- Database queries should use async/await pattern
- File I/O operations need async implementation
- Add background job processing for heavy operations
## API Implementation Review & Bug Fixes
### Critical API Issues to Address
#### API Structure & Organization
- [ ] **FastAPI Application Setup**: Review main application configuration
- Check if CORS is properly configured for web client access
- Verify middleware order and configuration
- Ensure proper exception handlers are registered
- Validate API versioning strategy (if applicable)
- [ ] **Dependency Injection**: Review service dependencies
- Check if database connections are properly injected
- Verify repository pattern implementation consistency
- Ensure proper scope management for dependencies
- Validate session management in DI container
#### Request/Response Handling
- [ ] **Pydantic Models**: Validate data models
- Check if all request/response models use proper type hints
- Verify field validation rules are comprehensive
- Ensure proper error messages for validation failures
- Review nested model relationships and serialization
- [ ] **HTTP Status Codes**: Review response status codes
- Verify correct status codes for different scenarios (200, 201, 400, 401, 404, 500)
- Check if error responses follow consistent format
- Ensure proper status codes for authentication failures
- Validate status codes for resource not found scenarios
#### Security Vulnerabilities
- [ ] **Input Validation**: Review security measures
- Check for SQL injection prevention in database queries
- Verify all user inputs are properly sanitized
- Ensure file upload endpoints have proper validation
- Review path traversal prevention for file operations
- [ ] **JWT Token Security**: Review token implementation
- Verify JWT secret is properly configured from environment
- Check token expiration handling
- Ensure proper token refresh mechanism (if implemented)
- Review token blacklisting strategy for logout
#### Database Integration Issues
- [ ] **Connection Management**: Fix database connection issues
- Check for proper connection pooling configuration
- Verify connection timeout and retry logic
- Ensure proper transaction management
- Review database migration strategy
- [ ] **Query Optimization**: Address performance issues
- Identify and fix N+1 query problems
- Review slow queries and add proper indexing
- Check for unnecessary database calls in loops
- Validate pagination implementation efficiency
#### API Endpoint Issues
- [ ] **Route Definitions**: Review endpoint configurations
- Check for duplicate route definitions
- Verify proper HTTP methods for each endpoint
- Ensure consistent URL patterns and naming
- Review parameter validation in path and query parameters
- [ ] **Error Handling**: Improve error responses
- Check if all endpoints have proper try-catch blocks
- Verify consistent error response format across all endpoints
- Ensure sensitive information is not leaked in error messages
- Review logging of errors for debugging purposes
#### Content Type & Serialization
- [ ] **JSON Handling**: Review JSON serialization
- Check if datetime fields are properly serialized
- Verify proper handling of null values
- Ensure circular reference prevention in nested objects
- Review custom serializers for complex data types
- [ ] **File Handling**: Review file upload/download endpoints
- Check file size limits and validation
- Verify proper content-type headers
- Ensure secure file storage and access
- Review streaming implementation for large files
#### Testing & Monitoring Issues
- [ ] **Health Checks**: Implement application monitoring
- Add health check endpoint for application status
- Implement database connectivity checks
- Add memory and performance monitoring
- Review logging configuration and levels
- [ ] **Integration Testing**: Add missing test coverage
- Test complete request/response cycles
- Verify authentication flow end-to-end
- Test error scenarios and edge cases
- Add load testing for critical endpoints
### Common Bug Patterns to Check
#### FastAPI Specific Issues
- [ ] **Async/Await Usage**: Review asynchronous implementation
- Check if async endpoints are properly awaited
- Verify database operations use async patterns
- Ensure proper async context management
- Review thread safety in async operations
- [ ] **Dependency Scope**: Review dependency lifecycles
- Check if singleton services are properly configured
- Verify database connections are not leaked
- Ensure proper cleanup in dependency teardown
- Review request-scoped vs application-scoped dependencies
#### Data Consistency Issues
- [ ] **Race Conditions**: Check for concurrent access issues
- Review critical sections that modify shared data
- Check for proper locking mechanisms
- Verify atomic operations for data updates
- Review transaction isolation levels
- [ ] **Data Validation**: Comprehensive input validation
- Check for missing required field validation
- Verify proper format validation (email, URL, etc.)
- Ensure proper range validation for numeric fields
- Review business logic validation rules
## Authentication System Design
### Simple Master Password Authentication
- **No User Registration**: Single master password for the entire application
- **No Email System**: No email verification or password reset via email
- **Environment Configuration**: Master password hash stored securely in .env
- **JWT Tokens**: Stateless authentication using JWT for API access
- **Session Management**: Client-side token storage and management
### Authentication Flow
1. **Login**: POST `/auth/login` with master password
2. **Token**: Receive JWT token for subsequent requests
3. **Authorization**: Include token in Authorization header for protected endpoints
4. **Verification**: Use `/auth/verify` to check token validity
5. **Logout**: Client removes token (stateless logout)
### Security Features
- Password hashing with SHA-256 and salt
- Configurable token expiry
- JWT secret from environment variables
- No sensitive data in source code
## Priority Order
1. **Critical Priority**: Fix API implementation bugs and security vulnerabilities
2. **High Priority**: Complete core functionality (Anime Controller, Episode Controller)
3. **Medium Priority**: Performance optimizations (Database Service, Caching)
4. **Low Priority**: Enhanced features and testing
## Notes
- ✅ Authentication system uses simple master password (no email/user management)
- Follow the repository pattern consistently across all data access
- Use dependency injection for all service dependencies
- Implement proper logging for all controller actions
- Add input validation using Pydantic models for all endpoints
- Use the `get_current_user` dependency for protecting endpoints that require authentication
- All API endpoints should follow RESTful conventions
- Implement proper OpenAPI documentation for all endpoints
- Use environment variables for all configuration values
- Follow Python typing best practices with proper type hints