config.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Application configuration module.
  3. Manages JWT and OAuth settings from YAML configuration file.
  4. """
  5. import os
  6. import secrets
  7. import logging
  8. import yaml
  9. from pathlib import Path
  10. from typing import Dict, Any
  11. logger = logging.getLogger(__name__)
  12. class Settings:
  13. """Application settings loaded from config.yaml."""
  14. def __init__(self):
  15. """Load configuration from YAML file."""
  16. config_path = Path(__file__).parent / "config.yaml"
  17. if not config_path.exists():
  18. raise FileNotFoundError(f"配置文件不存在: {config_path}")
  19. with open(config_path, 'r', encoding='utf-8') as f:
  20. config = yaml.safe_load(f)
  21. # JWT Settings
  22. jwt_config = config.get('jwt', {})
  23. self.JWT_SECRET_KEY = jwt_config.get('secret_key', secrets.token_urlsafe(32))
  24. self.JWT_ALGORITHM = jwt_config.get('algorithm', 'HS256')
  25. self.ACCESS_TOKEN_EXPIRE_MINUTES = jwt_config.get('access_token_expire_minutes', 15)
  26. self.REFRESH_TOKEN_EXPIRE_DAYS = jwt_config.get('refresh_token_expire_days', 7)
  27. # Database Settings
  28. db_config = config.get('database', {})
  29. self.DATABASE_PATH = db_config.get('path', 'annotation_platform.db')
  30. # OAuth Settings
  31. oauth_config = config.get('oauth', {})
  32. self.OAUTH_ENABLED = oauth_config.get('enabled', False)
  33. self.OAUTH_BASE_URL = oauth_config.get('base_url', '')
  34. self.OAUTH_CLIENT_ID = oauth_config.get('client_id', '')
  35. self.OAUTH_CLIENT_SECRET = oauth_config.get('client_secret', '')
  36. self.OAUTH_REDIRECT_URI = oauth_config.get('redirect_uri', '')
  37. self.OAUTH_SCOPE = oauth_config.get('scope', 'profile email')
  38. # OAuth Endpoints
  39. self.OAUTH_AUTHORIZE_ENDPOINT = oauth_config.get('authorize_endpoint', '/oauth/authorize')
  40. self.OAUTH_TOKEN_ENDPOINT = oauth_config.get('token_endpoint', '/oauth/token')
  41. self.OAUTH_USERINFO_ENDPOINT = oauth_config.get('userinfo_endpoint', '/oauth/userinfo')
  42. self.OAUTH_REVOKE_ENDPOINT = oauth_config.get('revoke_endpoint', '/oauth/revoke')
  43. # Server Settings
  44. server_config = config.get('server', {})
  45. self.SERVER_HOST = server_config.get('host', '0.0.0.0')
  46. self.SERVER_PORT = server_config.get('port', 8000)
  47. self.SERVER_RELOAD = server_config.get('reload', True)
  48. # Warn if using default JWT secret
  49. if self.JWT_SECRET_KEY == 'your-secret-key-here':
  50. logger.warning("使用默认 JWT_SECRET_KEY,生产环境请修改 config.yaml!")
  51. # Create settings instance
  52. settings = Settings()