feat: add endpoint to KanidmQueryError

This commit is contained in:
dettlaff 2024-12-13 17:51:40 +04:00
parent 1a07b1306b
commit 2b7e64f280
3 changed files with 57 additions and 26 deletions

View file

@ -1,6 +1,7 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import Optional from typing import Optional
from selfprivacy_api.models.group import Group
from selfprivacy_api.models.user import UserDataUser from selfprivacy_api.models.user import UserDataUser
@ -34,7 +35,9 @@ class AbstractUserRepository(ABC):
@staticmethod @staticmethod
@abstractmethod @abstractmethod
def delete_user(username: str) -> None: def delete_user(username: str) -> None:
"""Deletes an existing user""" """
Deletes an existing user
"""
@staticmethod @staticmethod
@abstractmethod @abstractmethod
@ -54,17 +57,25 @@ class AbstractUserRepository(ABC):
@staticmethod @staticmethod
@abstractmethod @abstractmethod
def get_user_by_username(username: str) -> UserDataUser: def get_user_by_username(username: str) -> UserDataUser:
"""Retrieves user data (UserDataUser) by username""" """
Retrieves user data (UserDataUser) by username
"""
# ! Not implemented in JsonUserRepository !
# | |
# \|/ \|/
@staticmethod @staticmethod
@abstractmethod @abstractmethod
def generate_password_reset_link(username: str) -> str: def generate_password_reset_link(username: str) -> str:
""" """
Do not reset the password, just generate a link to reset the password. Do not reset the password, just generate a link to reset the password.
! Not implemented in JsonUserRepository !
""" """
@staticmethod @staticmethod
@abstractmethod @abstractmethod
def groups_list() -> list: def groups_list() -> list[Group]:
"""Get groups list""" """
Get groups list.
"""

View file

@ -5,15 +5,19 @@ from typing import Any
class KanidmQueryError(Exception): class KanidmQueryError(Exception):
"""Error occurred during kanidm query""" """Error occurred during kanidm query"""
def __init__(self, error_text: Optional[str] = None) -> None: def __init__(
self.error_text = error_text self, error_text: Optional[Any] = None, endpoint: Optional[str] = None
) -> None:
self.error_text = str(error_text)
self.endpoint = endpoint
def get_error_message(self) -> str: def get_error_message(self) -> str:
return ( message = "An error occurred during the Kanidm query."
f"An error occurred during the Kanidm query. Error {self.error_text}" if self.endpoint:
if self.error_text message += f" Endpoint: {self.endpoint}"
else "An error occurred during the Kanidm query." if self.error_text:
) message += f" Error: {self.error_text}"
return message
class KanidmReturnEmptyResponse(Exception): class KanidmReturnEmptyResponse(Exception):

View file

@ -1,9 +1,9 @@
from json import JSONDecodeError from json import JSONDecodeError
from typing import Any, Optional, Union from typing import Any, Optional, Union
import subprocess import subprocess
import requests
import re import re
import logging import logging
import requests
from selfprivacy_api.models.group import Group from selfprivacy_api.models.group import Group
from selfprivacy_api.repositories.users.exceptions import ( from selfprivacy_api.repositories.users.exceptions import (
@ -130,8 +130,10 @@ class KanidmAdminToken:
@staticmethod @staticmethod
def _is_token_valid(token: str) -> bool: def _is_token_valid(token: str) -> bool:
endpoint = f"{KANIDM_URL}/v1/person/root"
try:
response = requests.get( response = requests.get(
f"{KANIDM_URL}/v1/person/root", endpoint,
headers={ headers={
"Authorization": f"Bearer {token}", "Authorization": f"Bearer {token}",
"Content-Type": "application/json", "Content-Type": "application/json",
@ -139,6 +141,13 @@ class KanidmAdminToken:
timeout=1, timeout=1,
verify=False, # TODO: REMOVE THIS NOT HALAL!!!!! verify=False, # TODO: REMOVE THIS NOT HALAL!!!!!
) )
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as error:
raise KanidmQueryError(error_text=f"Kanidm is not responding to requests. Error: {str(error)}", endpoint=endpoint)
except Exception as error:
raise KanidmQueryError(error_text=error, endpoint=endpoint)
response_data = response.json() response_data = response.json()
# we do not handle the other errors, this is handled by the main function in KanidmUserRepository._send_query # we do not handle the other errors, this is handled by the main function in KanidmUserRepository._send_query
@ -243,11 +252,16 @@ class KanidmUserRepository(AbstractUserRepository):
except JSONDecodeError as error: except JSONDecodeError as error:
logger.error(f"Kanidm query error: {str(error)}") logger.error(f"Kanidm query error: {str(error)}")
raise KanidmQueryError(error_text=f"No JSON found in Kanidm response. Error: {str(error)}") raise KanidmQueryError(
error_text=f"No JSON found in Kanidm response. Error: {str(error)}",
endpoint=full_endpoint,
)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as error:
raise KanidmQueryError(error_text=f"Kanidm is not responding to requests. Error: {str(error)}", endpoint=endpoint)
except Exception as error: except Exception as error:
logger.error(f"Kanidm query error: {str(error)}") logger.error(f"Kanidm query error: {str(error)}")
raise KanidmQueryError(error_text=str(error)) raise KanidmQueryError(error_text=error, endpoint=full_endpoint)
if response.status_code != 200: if response.status_code != 200:
if isinstance(response_data, dict): if isinstance(response_data, dict):
@ -259,12 +273,14 @@ class KanidmUserRepository(AbstractUserRepository):
if response_data == "nomatchingentries": if response_data == "nomatchingentries":
raise UserNotFound # does it work only for user? hate kanidm's response raise UserNotFound # does it work only for user? hate kanidm's response
elif response_data == "accessdenied": elif response_data == "accessdenied":
raise KanidmQueryError(error_text="Kanidm access issue") raise KanidmQueryError(
error_text="Kanidm access issue", endpoint=full_endpoint
)
elif response_data == "notauthenticated": elif response_data == "notauthenticated":
raise FailedToGetValidKanidmToken raise FailedToGetValidKanidmToken
logger.error(f"Kanidm query error: {response.text}") logger.error(f"Kanidm query error: {response.text}")
raise KanidmQueryError(error_text=response.text) raise KanidmQueryError(error_text=response.text, endpoint=full_endpoint)
return response_data return response_data