65 lines
2.3 KiB
Python
65 lines
2.3 KiB
Python
import os
|
|
import jwt
|
|
import requests
|
|
|
|
from aare.common.models import TokenData
|
|
from aare.common.auth_models import get_user
|
|
from aare.common.logger_config import setup_logger
|
|
|
|
logger = setup_logger('aareGUI')
|
|
|
|
def auth(base_url: str | None) -> str:
|
|
curr_user = get_user()
|
|
if base_url is None:
|
|
token_data = TokenData(sub=curr_user,
|
|
staff=True,
|
|
session=15,
|
|
pgroups=["p16371", "p22233"])
|
|
return jwt.encode(token_data.model_dump(), "ABC123")
|
|
|
|
url = f"{base_url}/token"
|
|
try:
|
|
response = requests.post(
|
|
url,
|
|
data={
|
|
"username": curr_user,
|
|
"password": ""
|
|
},
|
|
headers={
|
|
"Content-Type": "application/x-www-form-urlencoded"
|
|
},
|
|
timeout=(3.0, 15.0), # (connect timeout, read timeout)
|
|
)
|
|
except requests.RequestException as e:
|
|
logger.error(f"Authentication request failed (network): {e}")
|
|
raise RuntimeError(
|
|
"Cannot reach AareDAQ server (network error). "
|
|
"Please check the server is running and your connection."
|
|
) from e
|
|
|
|
if response.status_code != 200:
|
|
# Avoid dumping full HTML/tracebacks into the GUI; keep it short and actionable
|
|
logger.error(f"Authentication request failed: HTTP {response.status_code}. Body: {response.text[:500]}")
|
|
raise RuntimeError(
|
|
f"Authentication failed (HTTP {response.status_code}). "
|
|
"The server may be starting up or unavailable."
|
|
)
|
|
|
|
try:
|
|
response_json = response.json()
|
|
except ValueError as e:
|
|
logger.error(f"Authentication response was not JSON. Body: {response.text[:500]}")
|
|
raise RuntimeError(
|
|
"Authentication failed (invalid server response). "
|
|
"The server may be starting up or misconfigured."
|
|
) from e
|
|
|
|
token = response_json.get("access_token")
|
|
if not token or not isinstance(token, str):
|
|
logger.error(f"Authentication response missing access_token. Keys: {list(response_json.keys())}")
|
|
raise RuntimeError(
|
|
"Authentication failed (missing token in server response). "
|
|
"The server may be starting up."
|
|
)
|
|
|
|
return token |