Skip to content

Commit

Permalink
finalize
Browse files Browse the repository at this point in the history
  • Loading branch information
pablonyx committed Feb 18, 2025
1 parent 2522374 commit 5e75caf
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 1 deletion.
2 changes: 2 additions & 0 deletions backend/onyx/connectors/bookstack/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

class BookStackClientRequestFailedError(ConnectionError):
def __init__(self, status: int, error: str) -> None:
self.status_code = status
self.error = error
super().__init__(
"BookStack Client request failed with status {status}: {error}".format(
status=status, error=error
Expand Down
40 changes: 40 additions & 0 deletions backend/onyx/connectors/bookstack/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@
from onyx.configs.app_configs import INDEX_BATCH_SIZE
from onyx.configs.constants import DocumentSource
from onyx.connectors.bookstack.client import BookStackApiClient
from onyx.connectors.bookstack.client import BookStackClientRequestFailedError
from onyx.connectors.cross_connector_utils.miscellaneous_utils import time_str_to_utc
from onyx.connectors.interfaces import ConnectorValidationError
from onyx.connectors.interfaces import CredentialExpiredError
from onyx.connectors.interfaces import GenerateDocumentsOutput
from onyx.connectors.interfaces import InsufficientPermissionsError
from onyx.connectors.interfaces import LoadConnector
from onyx.connectors.interfaces import PollConnector
from onyx.connectors.interfaces import SecondsSinceUnixEpoch
Expand Down Expand Up @@ -214,3 +218,39 @@ def poll_source(
break
else:
time.sleep(0.2)

def validate_connector_settings(self) -> None:
"""
Validate that the BookStack credentials and connector settings are correct.
Specifically checks that we can make an authenticated request to BookStack.
"""
if not self.bookstack_client:
raise ConnectorMissingCredentialError(
"BookStack credentials have not been loaded."
)

try:
# Attempt to fetch a small batch of books (arbitrary endpoint) to verify credentials
_ = self.bookstack_client.get(
"/books", params={"count": "1", "offset": "0"}
)

except BookStackClientRequestFailedError as e:
# Check for HTTP status codes
if e.status_code == 401:
raise CredentialExpiredError(
"Your BookStack credentials appear to be invalid or expired (HTTP 401)."
) from e
elif e.status_code == 403:
raise InsufficientPermissionsError(
"The configured BookStack token does not have sufficient permissions (HTTP 403)."
) from e
else:
raise ConnectorValidationError(
f"Unexpected BookStack error (status={e.status_code}): {e}"
) from e

except Exception as exc:
raise ConnectorValidationError(
f"Unexpected error while validating BookStack connector settings: {exc}"
) from exc
6 changes: 5 additions & 1 deletion backend/onyx/server/documents/cc_pair.py
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,9 @@ def associate_credential_to_connector(
return response

except ConnectorValidationError as e:
print("EXCEPTINO 1")
print(type(e))

# If validation fails, delete the connector and commit the changes
# Ensures we don't leave invalid connectors in the database
# NOTE: consensus is that it makes sense to unify connector and ccpair creation flows
Expand All @@ -664,7 +667,8 @@ def associate_credential_to_connector(
logger.error(f"IntegrityError: {e}")
raise HTTPException(status_code=400, detail="Name must be unique")

except Exception:
except Exception as e:
logger.exception(f"Unexpected error: {e}")
raise HTTPException(status_code=500, detail="Unexpected error")


Expand Down
40 changes: 40 additions & 0 deletions check_bookstack_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import requests


def check_bookstack_api(base_url, token_id, token_secret):
# Construct the API endpoint URL
api_url = f"{base_url.rstrip('/')}/api/books"

# Set up the headers with the API credentials
headers = {
"Authorization": f"Token {token_id}:{token_secret}",
"Accept": "application/json",
}

try:
# Make a GET request to the API
response = requests.get(api_url, headers=headers)

# Check the response status code
if response.status_code == 200:
print("API key is valid and not expired.")
return True
elif response.status_code == 401:
print("API key is invalid or has expired.")
return False
else:
print(f"Unexpected response. Status code: {response.status_code}")
print(f"Response content: {response.text}")
return False

except requests.RequestException as e:
print(f"An error occurred while making the request: {e}")
return False


if __name__ == "__main__":
base_url = "https://kb.yuma1.com"
token_id = "MK4OgjOLEEhvHQf0cEwjYr1kVSYZoGa7"
token_secret = "kV6a8dnHOwAzAjL22jTMJHDhxWhqkeSw"

check_bookstack_api(base_url, token_id, token_secret)

0 comments on commit 5e75caf

Please sign in to comment.