Skip to content

Commit 9f5e4d1

Browse files
committed
fix auth token lookup logic and add request timeouts
1 parent b312f03 commit 9f5e4d1

2 files changed

Lines changed: 29 additions & 21 deletions

File tree

x2text-service/app/authentication_middleware.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99

1010
def authentication_middleware(func: Any) -> Any:
11+
"""Decorator to enforce bearer token authentication on flask routes."""
12+
1113
def wrapper(*args: Any, **kwargs: Any) -> Any:
1214
token = AuthenticationMiddleware.get_token_from_auth_header(request)
1315
# Check if bearer token exists and validate it
@@ -23,32 +25,26 @@ def wrapper(*args: Any, **kwargs: Any) -> Any:
2325
class AuthenticationMiddleware:
2426
@classmethod
2527
def validate_bearer_token(cls, token: str | None) -> bool:
28+
"""Validate the provided bearer token against the database."""
2629
try:
2730
if token is None:
2831
current_app.logger.error("Authentication failed. Empty bearer token")
2932
return False
3033
platform_key_table = f'"{Env.DB_SCHEMA}".{DBTable.PLATFORM_KEY}'
31-
query = f"SELECT * FROM {platform_key_table} WHERE key = '{token}'"
32-
cursor = be_db.execute_sql(query)
34+
query = f"SELECT * FROM {platform_key_table} WHERE key = %s"
35+
cursor = be_db.execute_sql(query, (token,))
3336
result_row = cursor.fetchone()
3437
cursor.close()
3538
if not result_row or len(result_row) == 0:
36-
current_app.logger.error(
37-
f"Authentication failed. bearer token not found {token}"
38-
)
39+
current_app.logger.error("Authentication failed. bearer token not found")
3940
return False
4041
platform_key = str(result_row[1])
4142
is_active = bool(result_row[2])
4243
if not is_active:
43-
current_app.logger.error(
44-
f"Token is not active. Activate \
45-
before using it. token {token}"
46-
)
44+
current_app.logger.error("Token is not active. Activate before using it.")
4745
return False
4846
if platform_key != token:
49-
current_app.logger.error(
50-
f"Authentication failed. Invalid bearer token: {token}"
51-
)
47+
current_app.logger.error("Authentication failed. Invalid bearer token")
5248
return False
5349

5450
except Exception as e:
@@ -62,6 +58,7 @@ def validate_bearer_token(cls, token: str | None) -> bool:
6258

6359
@classmethod
6460
def get_token_from_auth_header(cls, request: Request) -> str | None:
61+
"""Extract the bearer token from the Authorization header."""
6562
try:
6663
bearer_token = request.headers.get("Authorization")
6764
if not bearer_token:
@@ -99,6 +96,7 @@ def get_organization_from_bearer_token(cls, token: str) -> tuple[int | None, str
9996

10097
@classmethod
10198
def execute_query(cls, query: str, params: tuple = ()) -> Any:
99+
"""Execute a SQL query and return the first result."""
102100
cursor = be_db.execute_sql(query, params)
103101
result_row = cursor.fetchone()
104102
cursor.close()

x2text-service/app/controllers/controller.py

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,15 @@
2626

2727
@basic.route("/health", methods=["GET"])
2828
def health() -> str:
29+
"""Check the health status of the service."""
2930
logging.info("Checking health from : %s", request.remote_addr)
3031
return "OK"
3132

3233

3334
@basic.route("/test-connection", methods=["POST"])
3435
@authentication_middleware
3536
def test_connection() -> Any:
37+
"""Test the connection to the Unstructured API."""
3638
logging.info("Received a test connection request from %s", request.remote_addr)
3739
form_data = dict(request.form)
3840
unstructured_api_key = X2TextUtil.get_value_for_key(UNSTRUCTURED_API_KEY, form_data)
@@ -54,7 +56,7 @@ def test_connection() -> Any:
5456
headers=headers,
5557
data=None,
5658
files=files,
57-
timeout=None,
59+
timeout=60,
5860
)
5961

6062
if response.status_code == 400:
@@ -76,6 +78,7 @@ def test_connection() -> Any:
7678
@basic.route("/process", methods=["POST"])
7779
@authentication_middleware
7880
def process() -> Any:
81+
"""Process a document for text extraction."""
7982
logging.info("Received a doc processing request from %s", request.remote_addr)
8083
form_data = dict(request.form)
8184
url = X2TextUtil.get_value_for_key(UNSTRUCTURED_URL, form_data)
@@ -116,14 +119,21 @@ def process() -> Any:
116119
}
117120
payload = form_data
118121

119-
response = requests.request(
120-
"POST",
121-
url,
122-
headers=headers,
123-
data=payload,
124-
files=files,
125-
timeout=None,
126-
)
122+
try:
123+
response = requests.request(
124+
"POST",
125+
url,
126+
headers=headers,
127+
data=payload,
128+
files=files,
129+
timeout=60,
130+
)
131+
except requests.exceptions.RequestException as e:
132+
logging.error("Text extraction request failed: %s", e)
133+
x2_text_audit.status = "Failed"
134+
x2_text_audit.save()
135+
return {"message": "Text extraction request failed"}, 502
136+
127137
if response.ok:
128138
json_response = response.json()
129139
response_text = X2TextUtil.get_text_content(json_response)

0 commit comments

Comments
 (0)