Files
AareDAQ/src/aare/gui/auth.py
T

73 lines
2.6 KiB
Python

import json
import subprocess
import jwt
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"
apache_url = f"https://mx-x10sa-queue-01.psi.ch/"
try:
result = subprocess.run(
[
'curl', '-sk', '--cacert', '/my/top/secret/path',
'--negotiate', '-u', ':',
apache_url,
],
capture_output=True,
text=True,
timeout=18.0,
)
except subprocess.TimeoutExpired as e:
logger.error(f"Authentication curl timed out: {e}")
raise RuntimeError(
"Cannot reach AareDAQ server (timeout). "
"Please check the server is running and your connection."
) from e
except FileNotFoundError as e:
logger.error(f"curl not found: {e}")
raise RuntimeError("curl not found on this system.") from e
except OSError as e:
logger.error(f"Authentication curl failed (OS error): {e}")
raise RuntimeError(
"Cannot reach AareDAQ server (OS error). "
"Please check the server is running and your connection."
) from e
if result.returncode != 0:
logger.error(f"Authentication curl exited {result.returncode}. stderr: {result.stderr[:500]}")
raise RuntimeError(
f"Authentication failed (curl exit {result.returncode}). "
"Check server is running and Kerberos ticket is valid (kinit)."
)
try:
response_json = json.loads(result.stdout)
except json.JSONDecodeError as e:
logger.error(f"Authentication response not JSON. stdout: {result.stdout[: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