76 lines
2.8 KiB
Python
76 lines
2.8 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')
|
|
|
|
CACERT = "/sls/x10sa/misc/.cert/10s.crt"
|
|
|
|
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")
|
|
|
|
# Single call: Kerberos SPNEGO through Apache, which proxies to the DAQ server.
|
|
# Apache injects X-Remote-User; the DAQ server reads it from the localhost-proxied request.
|
|
url = f"{base_url}/token"
|
|
try:
|
|
token_result = subprocess.run(
|
|
['curl', '-s', '--cacert', CACERT,
|
|
'--negotiate', '-u', ':',
|
|
'-X', 'POST', url,
|
|
'-d', 'username=&password=',
|
|
'-H', 'Content-Type: application/x-www-form-urlencoded'],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=18.0,
|
|
)
|
|
except subprocess.TimeoutExpired as e:
|
|
logger.error(f"Token request 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"Token request curl OS error: {e}")
|
|
raise RuntimeError(
|
|
"Cannot reach AareDAQ server (OS error). "
|
|
"Please check the server is running and your connection."
|
|
) from e
|
|
|
|
if token_result.returncode != 0:
|
|
logger.error(f"Token curl exited {token_result.returncode}. stderr: {token_result.stderr[:500]}")
|
|
raise RuntimeError(
|
|
f"Token request failed (curl exit {token_result.returncode}). "
|
|
"Check Kerberos ticket is valid (kinit) and server is reachable."
|
|
)
|
|
|
|
try:
|
|
response_json = json.loads(token_result.stdout)
|
|
except json.JSONDecodeError as e:
|
|
logger.error(f"Token response not JSON. stdout: {token_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"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 |