Source code for smarter.apps.secret.views.listview.api

# pylint: disable=W0613
"""
This module contains views to implement the React.

Secret list view in the Smarter Dashboard.
"""

from http import HTTPStatus

from django.http import HttpRequest, JsonResponse

from smarter.apps.secret.caching import (
    invalidate_all_cached_secrets_for_user_profile,
)
from smarter.apps.secret.models import Secret
from smarter.apps.secret.serializers import SecretSerializer
from smarter.lib import logging
from smarter.lib.django.http.client_errors import (
    CLIENT_ERROR_TYPES,
    client_error_message,
)
from smarter.lib.django.listview import SmarterListApiView
from smarter.lib.django.views import SmarterAuthenticatedNeverCachedWebView
from smarter.lib.django.waffle import SmarterWaffleSwitches

logger = logging.getSmarterLogger(__name__, any_switches=[SmarterWaffleSwitches.SECRET_LOGGING])


[docs] class SecretListApiView(SmarterListApiView): """ Render the secret list view for the Smarter Workbench web console. This view displays all secrets available to the authenticated user as cards, providing a quick overview and access to secret details. :param request: Django HTTP request object. :type request: ASGIRequest :param args: Additional positional arguments. :type args: tuple :param kwargs: Additional keyword arguments. :type kwargs: dict :returns: Rendered HTML page with a card for each secret, or a 404 error page if the user is not authenticated. :rtype: HttpResponse """ model = Secret serializer_class = SecretSerializer listview_cache_kind = "Secret"
[docs] class SecretListApiCloneView(SmarterAuthenticatedNeverCachedWebView): """Clone a secret for the authenticated user."""
[docs] def post(self, request: HttpRequest, *args, **kwargs) -> JsonResponse: """ Handle POST requests to clone an existing Secret. Validates input parameters, checks for the existence of the Secret to be cloned, and creates a new Secret with the specified name. Invalidates the cache for the user's LLMClients after cloning. :param request: The HTTP request object containing the parameters for cloning. :type request: HttpRequest :param args: Additional positional arguments (not used). :param kwargs: Additional keyword arguments, including: - secret_id (str): The ID of the Secret to be cloned. - new_name (str): The new name for the cloned Secret. :returns: A JsonResponse containing the serialized data of the newly cloned Secret if successful, or an error message if the cloning fails. :rtype: JsonResponse """ secret_id = kwargs.get("secret_id") new_name = kwargs.get("new_name") secret: Secret if not secret_id or not new_name: logger.warning( "Missing required parameters. secret_id: %s, new_name: %s", secret_id, new_name, ) return JsonResponse({"error": "secret_id and new_name are required."}, status=HTTPStatus.BAD_REQUEST) try: secret = Secret.objects.with_read_permission_for(self.user_profile.user).get(id=secret_id) # type: ignore except Secret.DoesNotExist: logger.warning("Secret with id %s not found for cloning.", secret_id) return JsonResponse({"error": f"Secret with id {secret_id} not found."}, status=HTTPStatus.NOT_FOUND) try: new_name = self.to_snake_case(new_name.strip()) cloned_secret = secret.clone(new_name=new_name, user_profile=self.user_profile) # type: ignore invalidate_all_cached_secrets_for_user_profile(user_profile=self.user_profile) # type: ignore data = SecretSerializer(cloned_secret, context={"request": request}).data return JsonResponse(data, status=HTTPStatus.OK) # type: ignore except CLIENT_ERROR_TYPES as e: logger.warning( "Error cloning Secret with id %s: %s", secret_id, e, ) message = client_error_message(e, "An error occurred while cloning the Secret.") return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST) # pylint: disable=broad-except except Exception: logger.error( "Error cloning Secret with id %s", secret_id, exc_info=True, ) return JsonResponse( {"error": "An unknown error occurred while cloning the Secret."}, status=HTTPStatus.INTERNAL_SERVER_ERROR, )
[docs] class SecretListApiDeleteView(SmarterAuthenticatedNeverCachedWebView): """Delete a secret for the authenticated user."""
[docs] def post(self, request: HttpRequest, *args, **kwargs) -> JsonResponse: """ Handle POST requests to delete an existing Secret. Validates input parameters, checks for the existence of the Secret to be deleted, and deletes the Secret if it exists. Invalidates the cache for the user's LLMClients after deletion. :param request: The HTTP request object containing the parameters for deletion. :type request: HttpRequest :param args: Additional positional arguments (not used). :param kwargs: Additional keyword arguments, including: - secret_id (str): The ID of the Secret to be deleted. :returns: A JsonResponse indicating the success or failure of the deletion. :rtype: JsonResponse """ secret_id = kwargs.get("secret_id") if not secret_id: logger.warning("Missing required parameter secret_id for deletion.") return JsonResponse({"error": "secret_id is required."}, status=HTTPStatus.BAD_REQUEST) try: secret = Secret.objects.with_ownership_permission_for(self.user_profile.user).get(id=secret_id) # type: ignore except Secret.DoesNotExist: logger.warning("Secret with id %s not found for deletion.", secret_id) return JsonResponse({"error": f"Secret with id {secret_id} not found."}, status=HTTPStatus.NOT_FOUND) try: secret.delete() invalidate_all_cached_secrets_for_user_profile(user_profile=self.user_profile) # type: ignore return JsonResponse({"message": f"Secret with id {secret_id} deleted successfully."}, status=HTTPStatus.OK) except CLIENT_ERROR_TYPES as e: logger.warning( "Error deleting Secret with id %s: %s", secret_id, e, ) message = client_error_message(e, "An error occurred while deleting the Secret.") return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST) # pylint: disable=broad-except except Exception: logger.error( "Error deleting Secret with id %s", secret_id, exc_info=True, ) return JsonResponse( {"error": "An unknown error occurred while deleting the Secret."}, status=HTTPStatus.INTERNAL_SERVER_ERROR, )
[docs] class SecretListApiRenameView(SmarterAuthenticatedNeverCachedWebView): """Rename a secret for the authenticated user."""
[docs] def post(self, request: HttpRequest, *args, **kwargs) -> JsonResponse: """ Handle POST requests to rename an existing Secret. Validates input parameters, checks for the existence of the Secret to be renamed, and renames the Secret if it exists. Invalidates the cache for the user's LLMClients after renaming. :param request: The HTTP request object containing the parameters for renaming. :type request: HttpRequest :param args: Additional positional arguments (not used). :param kwargs: Additional keyword arguments, including: - secret_id (str): The ID of the Secret to be renamed. - new_name (str): The new name for the Secret. :returns: A JsonResponse indicating the success or failure of the renaming. :rtype: JsonResponse """ secret_id = kwargs.get("secret_id") new_name = kwargs.get("new_name") if not secret_id or not new_name: logger.warning( "Missing required parameters for renaming. secret_id: %s, new_name: %s", secret_id, new_name, ) return JsonResponse({"error": "secret_id and new_name are required."}, status=HTTPStatus.BAD_REQUEST) try: secret = Secret.objects.with_ownership_permission_for(self.user_profile.user).get(id=secret_id) # type: ignore except Secret.DoesNotExist: logger.warning("Secret with id %s not found for renaming.", secret_id) return JsonResponse({"error": f"Secret with id {secret_id} not found."}, status=HTTPStatus.NOT_FOUND) try: new_name = self.to_snake_case(new_name.strip()) secret.rename(new_name=new_name) invalidate_all_cached_secrets_for_user_profile(user_profile=self.user_profile) # type: ignore data = SecretSerializer(secret, context={"request": request}).data return JsonResponse(data, status=HTTPStatus.OK) # type: ignore except CLIENT_ERROR_TYPES as e: logger.warning( "Error renaming Secret with id %s: %s", secret_id, e, ) message = client_error_message(e, "An error occurred while renaming the Secret.") return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST) # pylint: disable=broad-except except Exception: logger.error( "Error renaming Secret with id %s", secret_id, exc_info=True, ) return JsonResponse( {"error": "An unknown error occurred while renaming the Secret."}, status=HTTPStatus.INTERNAL_SERVER_ERROR, )