Tadeas Kosek commited on
Commit
3482f6a
·
1 Parent(s): 94a2fe4

fixes vol2

Browse files
app.py CHANGED
@@ -126,7 +126,7 @@ def custom_openapi():
126
 
127
  # Add Bearer token security scheme
128
  openapi_schema["components"]["securitySchemes"] = {
129
- "bearerAuth": {
130
  "type": "http",
131
  "scheme": "bearer",
132
  "bearerFormat": "JWT",
@@ -134,6 +134,15 @@ def custom_openapi():
134
  }
135
  }
136
 
 
 
 
 
 
 
 
 
 
137
  app.openapi_schema = openapi_schema
138
  return app.openapi_schema
139
 
 
126
 
127
  # Add Bearer token security scheme
128
  openapi_schema["components"]["securitySchemes"] = {
129
+ "HTTPBearer": {
130
  "type": "http",
131
  "scheme": "bearer",
132
  "bearerFormat": "JWT",
 
134
  }
135
  }
136
 
137
+ # Apply security to protected endpoints
138
+ for path, path_item in openapi_schema["paths"].items():
139
+ for method, operation in path_item.items():
140
+ if method.lower() in ["get", "post", "put", "patch", "delete"]:
141
+ # Apply security to all endpoints except public ones
142
+ if not (path.endswith("/info") or path.endswith("/health") or path == "/" or path.endswith("/openapi.json") or path.endswith("/docs") or path.endswith("/redoc")):
143
+ # Check if the operation has dependencies that include authentication
144
+ operation["security"] = [{"HTTPBearer": []}]
145
+
146
  app.openapi_schema = openapi_schema
147
  return app.openapi_schema
148
 
interfaces/api/dependencies.py CHANGED
@@ -1,7 +1,7 @@
1
- # interfaces/api/dependencies.py
2
  """FastAPI dependency injection configuration."""
3
  from typing import Annotated, Optional
4
  from fastapi import Depends, UploadFile, Form, HTTPException, Request, Header
 
5
  from pydantic import BaseModel, Field, validator
6
  import re
7
 
@@ -9,6 +9,9 @@ from application.use_cases.container import UseCaseContainer
9
  from infrastructure.services.container import ServiceContainer
10
  from infrastructure.services.jwt_validation_service import JWTValidationService
11
 
 
 
 
12
  class ExtractionRequest(BaseModel):
13
  """Request model for audio extraction."""
14
  output_format: str = Field(default="mp3", description="Output audio format")
@@ -57,13 +60,13 @@ async def validate_video_file(video: UploadFile) -> UploadFile:
57
  return video
58
 
59
  async def validate_bearer_token(
60
- authorization: Optional[str] = Header(None, description="Bearer token for authentication")
61
  ) -> str:
62
  """
63
  Extract and validate bearer token from Authorization header.
64
 
65
  Args:
66
- authorization: Authorization header value
67
 
68
  Returns:
69
  str: The validated bearer token
@@ -76,23 +79,15 @@ async def validate_bearer_token(
76
  if not settings.enforce_authentication:
77
  return "authentication-disabled"
78
 
79
- if not authorization:
80
  raise HTTPException(
81
  status_code=401,
82
  detail="Missing Authorization header",
83
  headers={"WWW-Authenticate": "Bearer"}
84
  )
85
 
86
- # Check if it starts with "Bearer "
87
- if not authorization.startswith("Bearer "):
88
- raise HTTPException(
89
- status_code=401,
90
- detail="Invalid Authorization header format. Expected: Bearer <token>",
91
- headers={"WWW-Authenticate": "Bearer"}
92
- )
93
-
94
- # Extract token
95
- token = authorization[7:] # Remove "Bearer " prefix
96
  if not token:
97
  raise HTTPException(
98
  status_code=401,
 
 
1
  """FastAPI dependency injection configuration."""
2
  from typing import Annotated, Optional
3
  from fastapi import Depends, UploadFile, Form, HTTPException, Request, Header
4
+ from fastapi.security import HTTPBearer
5
  from pydantic import BaseModel, Field, validator
6
  import re
7
 
 
9
  from infrastructure.services.container import ServiceContainer
10
  from infrastructure.services.jwt_validation_service import JWTValidationService
11
 
12
+ # Create HTTPBearer scheme that will be recognized by OpenAPI
13
+ bearer_scheme = HTTPBearer(auto_error=False)
14
+
15
  class ExtractionRequest(BaseModel):
16
  """Request model for audio extraction."""
17
  output_format: str = Field(default="mp3", description="Output audio format")
 
60
  return video
61
 
62
  async def validate_bearer_token(
63
+ credentials = Depends(bearer_scheme)
64
  ) -> str:
65
  """
66
  Extract and validate bearer token from Authorization header.
67
 
68
  Args:
69
+ credentials: HTTPAuthorizationCredentials from HTTPBearer scheme
70
 
71
  Returns:
72
  str: The validated bearer token
 
79
  if not settings.enforce_authentication:
80
  return "authentication-disabled"
81
 
82
+ if not credentials:
83
  raise HTTPException(
84
  status_code=401,
85
  detail="Missing Authorization header",
86
  headers={"WWW-Authenticate": "Bearer"}
87
  )
88
 
89
+ # Extract token from credentials
90
+ token = credentials.credentials
 
 
 
 
 
 
 
 
91
  if not token:
92
  raise HTTPException(
93
  status_code=401,
interfaces/api/routes/extraction_routes.py CHANGED
@@ -1,7 +1,6 @@
1
  """Audio extraction API routes."""
2
- from fastapi import APIRouter, BackgroundTasks, UploadFile, Form, HTTPException, Security
3
  from fastapi.responses import JSONResponse
4
- from fastapi.security import HTTPBearer
5
  from dataclasses import asdict
6
  from typing import Optional
7
 
@@ -17,9 +16,6 @@ from domain.exceptions.domain_exceptions import (
17
 
18
  router = APIRouter()
19
 
20
- # Security scheme for OpenAPI documentation
21
- security = HTTPBearer()
22
-
23
  @router.post("/extract",
24
  response_model=JobCreatedResponse,
25
  summary="Extract Audio from Video",
@@ -31,7 +27,7 @@ security = HTTPBearer()
31
  All files are processed asynchronously and return a job ID for tracking progress.
32
  Use the job status endpoint to check processing status and download the result when complete.
33
  """,
34
- dependencies=[Security(security)],
35
  responses={
36
  202: {
37
  "description": "Job created for async processing",
 
1
  """Audio extraction API routes."""
2
+ from fastapi import APIRouter, BackgroundTasks, UploadFile, Form, HTTPException
3
  from fastapi.responses import JSONResponse
 
4
  from dataclasses import asdict
5
  from typing import Optional
6
 
 
16
 
17
  router = APIRouter()
18
 
 
 
 
19
  @router.post("/extract",
20
  response_model=JobCreatedResponse,
21
  summary="Extract Audio from Video",
 
27
  All files are processed asynchronously and return a job ID for tracking progress.
28
  Use the job status endpoint to check processing status and download the result when complete.
29
  """,
30
+
31
  responses={
32
  202: {
33
  "description": "Job created for async processing",
interfaces/api/routes/job_routes.py CHANGED
@@ -1,7 +1,6 @@
1
  """Job management API routes."""
2
- from fastapi import APIRouter, HTTPException, Path, Query, BackgroundTasks, Security
3
  from fastapi.responses import FileResponse
4
- from fastapi.security import HTTPBearer
5
  from typing import Any, Optional
6
  import logging
7
 
@@ -17,14 +16,10 @@ from domain.exceptions.domain_exceptions import (
17
  router = APIRouter()
18
  logger = logging.getLogger(__name__)
19
 
20
- # Security scheme for OpenAPI documentation
21
- security = HTTPBearer()
22
-
23
  @router.get("/jobs/{job_id}",
24
  response_model=JobStatusResponse,
25
  summary="Get Job Status",
26
  description="Check the status of an audio extraction job. **Authentication Required**: This endpoint requires a valid JWT Bearer token.",
27
- dependencies=[Security(security)],
28
  responses={
29
  200: {"description": "Job status retrieved successfully"},
30
  401: {"description": "Authentication required", "content": {"application/json": {"example": {"error": "Authentication required", "code": "AUTHENTICATION_ERROR"}}}},
@@ -93,7 +88,6 @@ async def get_job_status(
93
  If only start is provided, audio from start time to the end is returned.
94
  If only end is provided, audio from beginning to end time is returned.
95
  """,
96
- dependencies=[Security(security)],
97
  responses={
98
  200: {
99
  "description": "Audio file",
 
1
  """Job management API routes."""
2
+ from fastapi import APIRouter, HTTPException, Path, Query, BackgroundTasks
3
  from fastapi.responses import FileResponse
 
4
  from typing import Any, Optional
5
  import logging
6
 
 
16
  router = APIRouter()
17
  logger = logging.getLogger(__name__)
18
 
 
 
 
19
  @router.get("/jobs/{job_id}",
20
  response_model=JobStatusResponse,
21
  summary="Get Job Status",
22
  description="Check the status of an audio extraction job. **Authentication Required**: This endpoint requires a valid JWT Bearer token.",
 
23
  responses={
24
  200: {"description": "Job status retrieved successfully"},
25
  401: {"description": "Authentication required", "content": {"application/json": {"example": {"error": "Authentication required", "code": "AUTHENTICATION_ERROR"}}}},
 
88
  If only start is provided, audio from start time to the end is returned.
89
  If only end is provided, audio from beginning to end time is returned.
90
  """,
 
91
  responses={
92
  200: {
93
  "description": "Audio file",