Эх сурвалжийг харах

claude doing claude things

zehe 3 сар өмнө
parent
commit
e6d811eb03
1 өөрчлөгдсөн 28 нэмэгдсэн , 3 устгасан
  1. 28 3
      main.py

+ 28 - 3
main.py

@@ -58,7 +58,7 @@ logger = logging.getLogger(__name__)
 
 
 app = Flask(__name__)
 app = Flask(__name__)
 
 
-# Global config instance will be initialized in main
+# Global config instance - initialized during main execution
 config = None
 config = None
 
 
 def require_auth(key_config=None, is_health=False):
 def require_auth(key_config=None, is_health=False):
@@ -66,6 +66,10 @@ def require_auth(key_config=None, is_health=False):
     def decorator(f):
     def decorator(f):
         @wraps(f)
         @wraps(f)
         def decorated_function(*args, **kwargs):
         def decorated_function(*args, **kwargs):
+            if config is None:
+                logger.error("Configuration not loaded")
+                return jsonify({'error': 'Server configuration error'}), 500
+
             auth = request.authorization
             auth = request.authorization
 
 
             if not auth:
             if not auth:
@@ -79,6 +83,9 @@ def require_auth(key_config=None, is_health=False):
                 expected_password_hash = config.health_password_hash
                 expected_password_hash = config.health_password_hash
                 auth_type = "health check"
                 auth_type = "health check"
             else:
             else:
+                if key_config is None:
+                    logger.error("Key configuration not provided for authentication")
+                    return jsonify({'error': 'Server configuration error'}), 500
                 expected_username = key_config.username
                 expected_username = key_config.username
                 expected_password_hash = key_config.password_hash
                 expected_password_hash = key_config.password_hash
                 auth_type = f"key '{key_config.key_id}'"
                 auth_type = f"key '{key_config.key_id}'"
@@ -118,6 +125,9 @@ def send_ntfy_notification(backends: List[str], message: str, title: str = None)
                 except ImportError:
                 except ImportError:
                     raise Exception("ntfy package not available. Please install with: pip install ntfy")
                     raise Exception("ntfy package not available. Please install with: pip install ntfy")
 
 
+                if config is None:
+                    raise Exception("Configuration not loaded")
+
                 # Load the ntfy config file
                 # Load the ntfy config file
                 ntfy_config = load_config(config.ntfy_config_path)
                 ntfy_config = load_config(config.ntfy_config_path)
                 ntfy_config["backends"] = [backend]
                 ntfy_config["backends"] = [backend]
@@ -209,6 +219,10 @@ def create_key_handler(key_config):
     @require_auth(key_config=key_config)
     @require_auth(key_config=key_config)
     def get_key_part():
     def get_key_part():
         """Emergency key access endpoint"""
         """Emergency key access endpoint"""
+        if key_config is None:
+            logger.error("Key configuration is None in get_key_part")
+            return jsonify({'error': 'Server configuration error'}), 500
+
         logger.warning(f"EMERGENCY: Key access attempt detected for key '{key_config.key_id}'")
         logger.warning(f"EMERGENCY: Key access attempt detected for key '{key_config.key_id}'")
 
 
         try:
         try:
@@ -262,6 +276,10 @@ def health_check():
     """Health check endpoint that verifies both health monitoring and all key request functionality"""
     """Health check endpoint that verifies both health monitoring and all key request functionality"""
     logger.info("Health check requested")
     logger.info("Health check requested")
 
 
+    if config is None:
+        logger.error("Configuration not loaded during health check")
+        return jsonify({'status': 'error', 'message': 'Configuration not loaded'}), 500
+
     try:
     try:
         # Test health notification system
         # Test health notification system
         health_notification_success, health_backends = send_ntfy_notification(
         health_notification_success, health_backends = send_ntfy_notification(
@@ -378,6 +396,10 @@ def validate_setup():
     """Validate system setup before starting"""
     """Validate system setup before starting"""
     logger.info("Validating system setup...")
     logger.info("Validating system setup...")
 
 
+    if config is None:
+        logger.error("Configuration not loaded")
+        return False
+
     # Check dummy file exists
     # Check dummy file exists
     if not os.path.exists(config.dummy_file_path):
     if not os.path.exists(config.dummy_file_path):
         logger.error(f"Dummy file not found: {config.dummy_file_path}")
         logger.error(f"Dummy file not found: {config.dummy_file_path}")
@@ -456,8 +478,8 @@ class ProductionRequestHandler(WSGIRequestHandler):
         """Override to use our logger"""
         """Override to use our logger"""
         logger.info(f"HTTP: {format % args}")
         logger.info(f"HTTP: {format % args}")
 
 
-if __name__ == '__main__':
-    config = None
+def main():
+    global config
     try:
     try:
         # Load configuration
         # Load configuration
         config = Config()
         config = Config()
@@ -529,3 +551,6 @@ if __name__ == '__main__':
         sys.exit(1)
         sys.exit(1)
     finally:
     finally:
         logger.info("Emergency Access server shutdown complete")
         logger.info("Emergency Access server shutdown complete")
+
+if __name__ == '__main__':
+    main()