2024-10-28 21:57:23 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
2024-11-02 23:15:51 +00:00
|
|
|
import requests
|
|
|
|
|
|
|
|
from selfprivacy_api.models.user import UserDataUser
|
2024-10-28 21:57:23 +00:00
|
|
|
from selfprivacy_api.repositories.users.abstract_user_repository import (
|
|
|
|
AbstractUserRepository,
|
|
|
|
)
|
|
|
|
|
2024-11-02 23:15:51 +00:00
|
|
|
KANIDM_URL = "http://localhost:9001"
|
|
|
|
|
|
|
|
|
|
|
|
class KanidmQueryError(Exception):
|
|
|
|
"""Error occurred during Kanidm query"""
|
2024-10-28 21:57:23 +00:00
|
|
|
|
|
|
|
|
|
|
|
class KanidmUserRepository(AbstractUserRepository):
|
2024-11-02 23:15:51 +00:00
|
|
|
@staticmethod
|
|
|
|
def _send_query(endpoint: str, method: str = "GET", **kwargs):
|
|
|
|
request_method = getattr(requests, method.lower(), None)
|
|
|
|
|
|
|
|
try:
|
|
|
|
response = request_method(
|
|
|
|
f"{KANIDM_URL}/api/v1/{endpoint}",
|
|
|
|
params=kwargs,
|
|
|
|
timeout=0.8, # TODO: change timeout
|
|
|
|
)
|
|
|
|
|
|
|
|
if response.status_code != 200:
|
|
|
|
raise KanidmQueryError(
|
|
|
|
error=f"Kanidm returned unexpected HTTP status code. Error: {response.text}."
|
|
|
|
)
|
|
|
|
json = response.json()
|
|
|
|
|
|
|
|
return json["data"]
|
|
|
|
except Exception as error:
|
|
|
|
raise KanidmQueryError(error=f"Kanidm request failed! Error: {str(error)}")
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def create_user(username: str, password: str):
|
|
|
|
return KanidmUserRepository._send_query(
|
|
|
|
endpoint="person", method="POST", name=username, displayname=username
|
|
|
|
)
|
|
|
|
|
2024-10-28 21:57:23 +00:00
|
|
|
def get_users(
|
|
|
|
exclude_primary: bool = False,
|
|
|
|
exclude_root: bool = False,
|
|
|
|
) -> list[UserDataUser]:
|
2024-11-02 23:15:51 +00:00
|
|
|
return KanidmUserRepository._send_query()
|
2024-10-28 21:57:23 +00:00
|
|
|
|
|
|
|
def delete_user(username: str) -> None:
|
|
|
|
"""Deletes an existing user"""
|
2024-11-02 23:15:51 +00:00
|
|
|
return KanidmUserRepository._send_query()
|
2024-10-28 21:57:23 +00:00
|
|
|
|
|
|
|
def update_user(username: str, password: str) -> None:
|
|
|
|
"""Updates the password of an existing user"""
|
2024-11-02 23:15:51 +00:00
|
|
|
return KanidmUserRepository._send_query()
|
2024-10-28 21:57:23 +00:00
|
|
|
|
|
|
|
def get_user_by_username(username: str) -> Optional[UserDataUser]:
|
|
|
|
"""Retrieves user data (UserDataUser) by username"""
|
2024-11-02 23:15:51 +00:00
|
|
|
return KanidmUserRepository._send_query()
|