Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

refactor: use exceptions instead of return tuples for auth errors

LearningCircuit5331ea0408c3
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index 969ba51d82..a505c30cd4 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -45,6 +45,18 @@ from ...utilities.db_utils import get_settings_manager
library_bp = Blueprint("library", __name__, url_prefix="/library")
+# Error handler for authentication errors
+@library_bp.errorhandler(Exception)
+def handle_web_api_exception(error):
+ """Handle WebAPIException and its subclasses."""
+ from ...web.exceptions import WebAPIException
+
+ if isinstance(error, WebAPIException):
+ return jsonify(error.to_dict()), error.status_code
+ # Re-raise other exceptions
+ raise error
+
+
def is_downloadable_domain(url: str) -> bool:
"""Check if URL is from a downloadable academic domain using proper URL parsing."""
try:
@@ -137,7 +149,7 @@ def is_downloadable_domain(url: str) -> bool:
def get_authenticated_user_password(
username: str, flask_session_id: str = None
-):
+) -> str:
"""
Get authenticated user password from session store with fallback to g.user_password.
@@ -146,10 +158,13 @@ def get_authenticated_user_password(
flask_session_id: Optional Flask session ID. If not provided, uses session.get("_id")
Returns:
- tuple: (password, error_response) where error_response is None on success,
- or a Flask response tuple on failure
+ str: The user's password
+
+ Raises:
+ AuthenticationRequiredError: If no password is available for the user
"""
from ...database.session_passwords import session_password_store
+ from ...web.exceptions import AuthenticationRequiredError
session_id = flask_session_id or session.get("session_id")
@@ -162,7 +177,7 @@ def get_authenticated_user_password(
logger.debug(
f"Retrieved user password from session store for user {username}"
)
- return user_password, None
+ return user_password
except Exception:
logger.exception("Failed to get user password from session store")
@@ -172,20 +187,14 @@ def get_authenticated_user_password(
logger.debug(
f"Retrieved user password from g.user_password fallback for user {username}"
)
- return user_password, None
+ return user_password
# No password available
logger.error(f"No user password available for user {username}")
- error_response = (
- jsonify(
- {
- "status": "error",
- "message": "Authentication required: Please refresh the page and log in again to access encrypted database features.",
- }
- ),
- 401,
+ raise AuthenticationRequiredError(
+ message="Authentication required: Please refresh the page and log in again to access encrypted database features.",
+ username=username,
)
- return None, error_response
# ============= Page Routes =============
@@ -614,9 +623,7 @@ def open_folder():
def download_single_resource(resource_id):
"""Download a single resource."""
username = session.get("username")
- user_password, error_response = get_authenticated_user_password(username)
- if error_response:
- return error_response
+ user_password = get_authenticated_user_password(username)
service = DownloadService(username, user_password)
success, error = service.download_resource(resource_id)
@@ -638,11 +645,7 @@ def download_text_single(resource_id):
"""Download a single resource as text file."""
try:
username = session.get("username")
- user_password, error_response = get_authenticated_user_password(
- username
- )
- if error_response:
- return error_response
+ user_password = get_authenticated_user_password(username)
service = DownloadService(username, user_password)
success, error = service.download_as_text(resource_id)
@@ -674,11 +677,14 @@ def download_all_text():
def generate():
# Get user password for database operations
- user_password, _ = get_authenticated_user_password(
- username, flask_session_id
- )
- if user_password is None:
- logger.error(f"Could not get password for user {username}")
+ from ...web.exceptions import AuthenticationRequiredError
+
+ try:
+ user_password = get_authenticated_user_password(
+ username, flask_session_id
+ )
+ except AuthenticationRequiredError:
+ logger.warning(f"Authentication expired for user {username}")
return
download_service = DownloadService(username, user_password)
@@ -760,9 +766,7 @@ def download_all_text():
def download_research_pdfs(research_id):
"""Queue all PDFs from a research session for download."""
username = session.get("username")
- user_password, error_response = get_authenticated_user_password(username)
- if error_response:
- return error_response
+ user_password = get_authenticated_user_password(username)
service = DownloadService(username, user_password)
# Get optional collection_id from request body
@@ -799,10 +803,13 @@ def download_bulk():
def generate():
"""Generate progress updates as Server-Sent Events."""
# Get user password for database operations
- user_password, _ = get_authenticated_user_password(
- username, flask_session_id
- )
- if user_password is None:
+ from ...web.exceptions import AuthenticationRequiredError
+
+ try:
+ user_password = get_authenticated_user_password(
+ username, flask_session_id
+ )
+ except AuthenticationRequiredError:
return
download_service = DownloadService(username, user_password)
@@ -1069,11 +1076,7 @@ def queue_all_undownloaded():
logger.info(f"Found {len(undownloaded)} total undownloaded resources")
# Get user password for encrypted database access
- user_password, error_response = get_authenticated_user_password(
- username
- )
- if error_response:
- return error_response
+ user_password = get_authenticated_user_password(username)
resource_filter = ResourceFilter(username, user_password)
filter_results = resource_filter.filter_downloadable_resources(
@@ -1305,9 +1308,7 @@ def check_downloads():
def download_source():
"""Download a single source from a research."""
username = session.get("username")
- user_password, error_response = get_authenticated_user_password(username)
- if error_response:
- return error_response
+ user_password = get_authenticated_user_password(username)
data = request.json
research_id = data.get("research_id")
url = data.get("url")
diff --git a/src/local_deep_research/web/exceptions.py b/src/local_deep_research/web/exceptions.py
new file mode 100644
index 0000000000..0bbadafe73
--- /dev/null
+++ b/src/local_deep_research/web/exceptions.py
@@ -0,0 +1,65 @@
+"""
+Custom exceptions for the web module.
+
+These exceptions are used to provide structured error handling
+that can be caught by Flask error handlers and converted to
+appropriate JSON responses.
+"""
+
+from typing import Any, Optional
+
+
+class WebAPIException(Exception):
+ """Base exception for all web API related errors."""
+
+ def __init__(
+ self,
+ message: str,
+ status_code: int = 500,
+ error_code: Optional[str] = None,
+ details: Optional[dict[str, Any]] = None,
+ ):
+ """
+ Initialize the web API exception.
+
+ Args:
+ message: Human-readable error message
+ status_code: HTTP status code for the error
+ error_code: Machine-readable error code for API consumers
+ details: Additional error details/context
+ """
+ super().__init__(message)
+ self.message = message
+ self.status_code = status_code
+ self.error_code = error_code or self.__class__.__name__
+ self.details = details or {}
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert exception to dictionary for JSON response."""
+ result = {
+ "status": "error",
+ "message": self.message,
+ "error_code": self.error_code,
+ }
+ if self.details:
+ result["details"] = self.details
+ return result
+
+
+class AuthenticationRequiredError(WebAPIException):
+ """Raised when authentication is required but not available."""
+
+ def __init__(
+ self,
+ message: str = "Authentication required: Please refresh the page and log in again.",
+ username: Optional[str] = None,
+ ):
+ details = {}
+ if username:
+ details["username"] = username
+ super().__init__(
+ message,
+ status_code=401,
+ error_code="AUTHENTICATION_REQUIRED",
+ details=details,
+ )