Files
2026-11-26 00:53:32 +00:00

95 lines
3.7 KiB
Python

from helpers.api import ApiHandler, Request
from usr.plugins.baserow.helpers.baserow_client import BaserowClient, BaserowError
from usr.plugins.baserow.helpers.connection_store import (
load_connections,
resolve_connection,
store_connection_secrets,
)
class TestConnection(ApiHandler):
"""Validate a Baserow connection (token or email/password).
Credentials may come from the request body (WebUI form) or, when blank,
are resolved from Agent Zero's built-in SecretsManager using the
connection name / single configured connection.
"""
@classmethod
def get_methods(cls):
return ["POST"]
async def process(self, input: dict, request: Request) -> dict:
conn = input.get("connection", {}) or {}
base_url = (conn.get("base_url") or "").strip()
auth_type = conn.get("auth_type", "token")
name = (conn.get("name") or "").strip()
token = (conn.get("token") or "").strip()
email = (conn.get("email") or "").strip()
password = conn.get("password") or ""
# Load configured connections; choose by name, or default to the sole connection.
configured = load_connections()
if not name and len(configured) == 1:
name = next(iter(configured))
meta = configured.get(name, {})
if not base_url:
base_url = meta.get("base_url", "")
if not auth_type:
auth_type = meta.get("auth_type", "token")
if not base_url:
return {"ok": False, "error": "Missing base URL."}
# If the form sent no secrets, resolve from the secret store.
if (auth_type == "token" and not token) or (auth_type == "password" and (not email or not password)):
if meta:
resolved = resolve_connection(meta)
token = resolved.get("token", "")
email = resolved.get("email", "")
password = resolved.get("password", "")
jwt = ""
if auth_type == "password":
if not email or not password:
return {"ok": False, "error": "Email and password required for password auth."}
try:
jwt = BaserowClient.login(base_url, email, password)
except BaserowError as e:
return {"ok": False, "error": str(e)}
# Persist provided credentials into the secret store for next time.
store_connection_secrets({
"name": name or "baserow",
"auth_type": "password",
"email": email,
"password": password,
})
else:
if not token:
return {"ok": False, "error": "API token required for token auth."}
store_connection_secrets({
"name": name or "baserow",
"auth_type": "token",
"token": token,
})
client = BaserowClient(base_url, token=token or None, jwt=jwt or None)
# Probe the applications listing to classify the token.
try:
client.list_applications()
return {"ok": True, "token_type": "workspace", "jwt": jwt}
except BaserowError as e:
msg = str(e)
if "Authentication credentials" in msg or "ERROR_NO_PERMISSION" in msg:
return {
"ok": True,
"token_type": "database_scoped",
"note": "Token authenticates but is database-scoped (listing denied).",
"jwt": jwt,
}
return {"ok": False, "error": f"Authentication failed: {msg}"}
except Exception as e:
return {"ok": False, "error": f"Connection error: {e}"}