Source code for smarter.apps.account.api.v1.views.user

# pylint: disable=W0707,W0718,W0613
"""User views for smarter api."""

from http import HTTPStatus
from typing import Optional, Union

from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
from django.db import transaction
from django.http import Http404, HttpRequest, HttpResponseRedirect, JsonResponse
from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response

from smarter.apps.account.contract.models import AccountApiUserDetail
from smarter.apps.account.models import User, UserProfile, get_resolved_user
from smarter.apps.account.serializers import UserSerializer
from smarter.apps.api.signals import api_request_completed
from smarter.common.utils import is_authenticated_request, smarter_build_absolute_uri
from smarter.lib import json, logging
from smarter.lib.django.http.client_errors import (
    CLIENT_ERROR_TYPES,
    REQUEST_DATA_ERROR_TYPES,
    client_error_message,
)
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.typing import SmarterDictType

from .base import AccountListViewBase, AccountViewBase

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

#: The fields of a new user that the request body may set.
USER_CREATE_FIELDS = ("username", "password", "email", "first_name", "last_name")
#: The fields of a user that the request body may update.
USER_UPDATE_FIELDS = ("username", "email", "first_name", "last_name", "is_active")

# -----------------------------------------------------------------------
# handlers for users
# -----------------------------------------------------------------------


[docs] def validate_request_body(request: Request): """ Check that the request body is a json dict with a ``username`` and a ``password``. :param request: The request. :returns: None if the body is valid, else a 400 :class:`JsonResponse` that explains why not. """ # do a cursory check of the request data. The body has the new user's password, so it isn't logged. logger.debug("request body of %d bytes", len(request.body)) try: data = json.loads(request.body) if not isinstance(data, dict): raise ValidationError( f"Invalid request data. Was expecting a dictionary but received {type(request.data) if hasattr(request, 'data') else 'unknown'}." ) if "username" not in data: raise ValidationError("Invalid request data. Missing 'username' field.") if "password" not in data: raise ValidationError("Invalid request data. Missing 'password' field.") except json.JSONDecodeError: return JsonResponse({"error": "Invalid JSON format in request body."}, status=HTTPStatus.BAD_REQUEST.value) except REQUEST_DATA_ERROR_TYPES as e: message = client_error_message(e, "The request data is not valid.") return JsonResponse( {"error": "Invalid request data", "exception": message}, status=HTTPStatus.BAD_REQUEST.value ) # pylint: disable=broad-except except Exception: logger.error("failed", exc_info=True) return JsonResponse( {"error": "An unknown error occurred while reading the request."}, status=HTTPStatus.INTERNAL_SERVER_ERROR.value, ) return None
[docs] def eval_permissions(request, user_to_update: User, user_to_update_profile: Optional[UserProfile] = None): """ Check that the request user may modify a user. A superuser may modify anyone. Anyone else needs a UserProfile, and may only modify users of their own Account; a non-staff user may only modify themself. :param request: The request. :param user_to_update: The User to modify. :param user_to_update_profile: The UserProfile of ``user_to_update``, if it has one. :returns: None if the request user may modify the user, else a 401 :class:`JsonResponse`. """ logger.debug("request: %s", request) user = get_resolved_user(request.user) if user is None or not getattr(user, "is_authenticated", False): return JsonResponse({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED.value) if not user.is_superuser: # if the user is not a superuser then they need to have a UserProfile try: request_user_account = UserProfile.objects.get(user=user).account except UserProfile.DoesNotExist: return JsonResponse( {"error": "You are not authorized to modify Smarter user accounts."}, status=HTTPStatus.UNAUTHORIZED.value, ) # if the user is not a superuser then at most they can update users within their own account if user_to_update_profile and user_to_update_profile.account != request_user_account: return JsonResponse( {"error": "You are not authorized to modify this user account."}, status=HTTPStatus.UNAUTHORIZED.value ) # if the user is neither a superuser nor a staff member then they can only update their own account if not request.user.is_staff and user_to_update != request.user: return JsonResponse( {"error": "You are not authorized to modify this user account."}, status=HTTPStatus.UNAUTHORIZED.value ) return None
[docs] def get_user_for_operation(request, user_id: int) -> tuple[User, UserProfile] | JsonResponse: """ Look up a User and its UserProfile by the User's id. :param request: The request, whose user must be a :class:`User`. :param user_id: The User's id. :returns: The User and its UserProfile, or a 401 or 400 :class:`JsonResponse` when the request user is not a User, or the User or its UserProfile does not exist. """ if not isinstance(request.user, User): return JsonResponse({"error": "Unauthorized"}, status=HTTPStatus.UNAUTHORIZED.value) try: user = User.objects.get(id=user_id) except User.DoesNotExist: return JsonResponse({"error": "User not found"}, status=HTTPStatus.BAD_REQUEST.value) try: user_profile = UserProfile.objects.get(user=user) except UserProfile.DoesNotExist: return JsonResponse({"error": "User profile not found"}, status=HTTPStatus.BAD_REQUEST.value) logger.debug("user: %s", user) return user, user_profile
[docs] def user_response(user) -> Response: """ The response of a user: its :class:`AccountApiUserDetail`. :param user: The user. :type user: django.contrib.auth.models.User :returns: The response. :rtype: rest_framework.response.Response """ return Response(AccountApiUserDetail.from_model(user).model_dump(mode="json"), status=HTTPStatus.OK.value)
# pylint: disable=too-many-return-statements
[docs] def get_user(request, user_id: Optional[int] = None): """ Get a user's json representation, an :class:`AccountApiUserDetail`, by id. A superuser may get any user, a staff user the users of their own Account, and anyone else only themself. :param request: The request. :param user_id: The User's id, or None for the request user. :returns: The user's json response, or a 401 or 404 :class:`JsonResponse`. """ logger.debug("user_id: %s, request: %s", user_id, request) if user_id is None: logger.debug("returning current user: %s", request.user) return user_response(request.user) request_user = get_resolved_user(request.user) if request_user is None: logger.debug("user not found for request: %s", request) return JsonResponse({"detail": "User not found"}, status=HTTPStatus.UNAUTHORIZED.value) # if the user is a superuser, they can get any user if request_user.is_superuser: try: user = User.objects.get(id=user_id) except User.DoesNotExist: logger.debug("user not found for id: %s", user_id) return JsonResponse({"detail": "User not found"}, status=HTTPStatus.NOT_FOUND.value) logger.debug("returning user for id %s: %s", user_id, user) return user_response(user) # if the user is a staff member, they can get users within their own account if request_user.is_staff: try: account = UserProfile.objects.get(user=request.user).account user = UserProfile.objects.get(account=account, user_id=user_id).user except (UserProfile.DoesNotExist, User.DoesNotExist): logger.debug("user not found for id: %s", user_id) return JsonResponse({"detail": "User not found"}, status=HTTPStatus.NOT_FOUND.value) return user_response(user) # mere mortals can only get their own account if user_id != request.user.id: logger.debug("unauthorized access attempt for user id: %s", user_id) return JsonResponse({"detail": "Unauthorized"}, status=HTTPStatus.UNAUTHORIZED.value) logger.debug("returning current user: %s", request.user) return user_response(request.user)
[docs] def create_user(request: Request): """Create an account from a json representation in the body of the request.""" logger.debug("request: %s", request) data: SmarterDictType user = get_resolved_user(request.user) if user is None: logger.debug("user not found for request: %s", request) return JsonResponse({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED.value) if not user.is_superuser and not user.is_staff: logger.debug("unauthorized access attempt for user: %s", user) return JsonResponse({"error": "Unauthorized"}, status=HTTPStatus.UNAUTHORIZED.value) invalid = validate_request_body(request) if invalid: return invalid data = json.loads(request.body) # only these fields: the request body must not set e.g. is_superuser or is_staff. data = {key: value for key, value in data.items() if key in USER_CREATE_FIELDS} # the new user will be associated with the account of the current user try: account = UserProfile.objects.get(user=request.user).account except UserProfile.DoesNotExist: logger.debug("user profile not found for user: %s", user) return JsonResponse({"error": "User is not associated with any account."}, status=HTTPStatus.UNAUTHORIZED.value) try: with transaction.atomic(): user = User.objects.create_user(**data) UserProfile.objects.create(name=user.username, user=user, account=account) except REQUEST_DATA_ERROR_TYPES as e: logger.warning("could not create the user: %s", type(e).__name__) message = client_error_message(e, "The request data is not valid.") return JsonResponse( {"error": "Invalid request data", "exception": message}, status=HTTPStatus.BAD_REQUEST.value ) # pylint: disable=broad-except except Exception: logger.error("failed", exc_info=True) return JsonResponse( {"error": "An unknown error occurred while creating the user."}, status=HTTPStatus.INTERNAL_SERVER_ERROR.value, ) logger.debug("user created successfully: %s", user) return HttpResponseRedirect(request.path_info + str(user.id) + "/") # type: ignore[return-value]
[docs] def update_user(request: Request, user_id: int): """ Update a user from a json representation in the body of the request. Only the fields in ``USER_UPDATE_FIELDS`` are changed, and the request user needs the permissions that :func:`eval_permissions` checks. :param request: The request, whose body is a json dict of the fields to change. :param user_id: The User's id. :returns: The response: the updated user, or an error :class:`JsonResponse`. """ logger.debug("user_id: %s, request: %s", user_id, request) data: SmarterDictType # a partial update: the body needn't have the username and password that validate_request_body() requires. try: data = json.loads(request.body) except json.JSONDecodeError: # the body may have a password, so it isn't logged. logger.debug( "invalid JSON format in a request body of %d bytes", len(request.body), ) return JsonResponse({"error": "Invalid JSON format in request body."}, status=HTTPStatus.BAD_REQUEST.value) if not isinstance(data, dict): return JsonResponse( {"error": "Invalid request data. Was expecting a dictionary."}, status=HTTPStatus.BAD_REQUEST.value ) # an error is a single JsonResponse, not a (user, user_profile) tuple. result = get_user_for_operation(request, user_id) if isinstance(result, JsonResponse): return result user_to_update, user_to_update_profile = result if not isinstance(user_to_update, User): logger.debug("user not found for request: %s", request) return JsonResponse({"error": "User not found"}, status=HTTPStatus.BAD_REQUEST.value) if not isinstance(user_to_update_profile, UserProfile): logger.debug("user profile not found for user: %s", user_to_update) return JsonResponse({"error": "User profile not found"}, status=HTTPStatus.BAD_REQUEST.value) forbidden = eval_permissions(request, user_to_update, user_to_update_profile) if forbidden: return forbidden try: for key, value in data.items(): # only these fields: the request body must not set e.g. is_superuser, or the password hash. if key in USER_UPDATE_FIELDS: setattr(user_to_update, key, value) user_to_update.save() logger.debug("user updated successfully: %s", user_to_update) except CLIENT_ERROR_TYPES as e: logger.warning("could not update the user: %s", type(e).__name__) message = client_error_message(e, "The request data is not valid.") return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST.value) # pylint: disable=broad-except except Exception: logger.error("failed", exc_info=True) return JsonResponse( {"error": "An unknown error occurred while updating the user."}, status=HTTPStatus.INTERNAL_SERVER_ERROR.value, ) return HttpResponseRedirect(request.path_info)
[docs] def delete_user(request: Request, user_id: Optional[int] = None): """ Delete a user and its UserProfile, in one transaction. :param request: The request. :param user_id: The User's id, or None for the request user. :returns: A redirect to the parent url, or a 404, 401 or 500 :class:`JsonResponse`. """ logger.debug("user_id: %s, request: %s", user_id, request) user: Union[User, AnonymousUser] try: if user_id: user = User.objects.get(id=user_id) else: user = request.user except User.DoesNotExist: logger.debug("user not found for request: %s", request) return JsonResponse({"error": "User not found"}, status=HTTPStatus.NOT_FOUND.value) if not isinstance(user, User): # an anonymous request user, which eval_permissions() would refuse as well. return JsonResponse({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED.value) forbidden = eval_permissions(request, user, UserProfile.objects.filter(user=user).first()) if forbidden: return forbidden try: with transaction.atomic(): UserProfile.objects.get(user=user).delete() user.delete() logger.debug("user deleted successfully: %s", user) except CLIENT_ERROR_TYPES as e: logger.warning("refused: %s", type(e).__name__) message = client_error_message(e, "The user could not be deleted.") return JsonResponse({"error": message}, status=HTTPStatus.BAD_REQUEST.value) # pylint: disable=broad-except except Exception: logger.error("failed", exc_info=True) return JsonResponse( {"error": "An unknown error occurred while deleting the user."}, status=HTTPStatus.INTERNAL_SERVER_ERROR.value, ) plugins_path = request.path_info.rsplit("/", 2)[0] return HttpResponseRedirect(plugins_path)
[docs] class UserView(AccountViewBase): """User view for smarter api."""
[docs] def get(self, request, user_id: int): """ Return a user as json, and send ``api_request_completed``. :param request: The request. :param user_id: The User's id. :returns: The response of :func:`get_user`. """ response = get_user(request, user_id) api_request_completed.send(sender=self.__class__, instance=self, request=request, response=response) return response
[docs] def post(self, request, user_id: Optional[int] = None): """ Create a user from the request body, and send ``api_request_completed``. :param request: The request. :param user_id: Unused. :returns: The response of :func:`create_user`. """ response = create_user(request) api_request_completed.send(sender=self.__class__, instance=self, request=request, response=response) return response
[docs] def patch(self, request, user_id: int): """ Update a user from the request body, and send ``api_request_completed``. :param request: The request. :param user_id: The User's id. :returns: The response of :func:`update_user`. """ response = update_user(request, user_id) api_request_completed.send(sender=self.__class__, instance=self, request=request, response=response) return response
[docs] def delete(self, request, user_id): """ Delete a user, and send ``api_request_completed``. :param request: The request. :param user_id: The User's id. :returns: The response of :func:`delete_user`. """ response = delete_user(request, user_id) api_request_completed.send(sender=self.__class__, instance=self, request=request, response=response) return response
[docs] def handle_exception(self, exc): """ Answer an Http404 with a json 404 response, and leave any other exception to DRF. :param exc: The exception that the view raised. :returns: The response. """ if isinstance(exc, Http404): logger.debug("Http404: %s", exc) return Response({"detail": "Not found"}, status=status.HTTP_404_NOT_FOUND) logger.error("unhandled exception: %s", exc) return super().handle_exception(exc)
[docs] class UserListView(AccountListViewBase): """User list view for smarter api.""" serializer_class = UserSerializer
[docs] def setup(self, request: HttpRequest, *args, **kwargs): """ Setup the view. This is called by Django before dispatch() and is used to initialize attributes that require the request object. """ super().setup(request, *args, **kwargs) logger.debug( "request: %s, user: %s, user_profile: %s is_authenticated: %s", smarter_build_absolute_uri(self.request), self.request.user.username if self.request.user else "Anonymous", # type: ignore[assignment] self.user_profile, is_authenticated_request(self.request), )
[docs] def get_queryset(self): """ Return every User for a superuser, else the Users of the request user's Accounts. :returns: The queryset, or an error :class:`Response` when the user or its UserProfile is not found. """ logger.debug("request: %s", self.request) user = get_resolved_user(self.request.user) if user is None: logger.debug("user not found for request: %s", self.request) return Response({"error": "User not found"}, status=HTTPStatus.UNAUTHORIZED.value) if user.is_superuser: logger.debug("user is superuser: %s", user) return User.objects.all() try: accounts = UserProfile.objects.filter(user=self.request.user).values("account") account_users = UserProfile.objects.filter(account__in=accounts).values_list("user", flat=True) logger.debug( "account users for %s: %s", user, list(account_users), ) return User.objects.filter(id__in=account_users) except UserProfile.DoesNotExist: logger.debug("user profile not found for user: %s", user) return Response({"error": "User not found"}, status=HTTPStatus.NOT_FOUND.value)
[docs] def get_list(self, request: Request): """Get a list of all users the requesting user has access to, as :class:`AccountApiUserDetail` models.""" logger.debug("request: %s", request) queryset = self.get_queryset() if isinstance(queryset, Response): return queryset users = [AccountApiUserDetail.from_model(user).model_dump(mode="json") for user in queryset] return Response(users, status=HTTPStatus.OK.value)
[docs] def get(self, request: Request, *args, **kwargs): """Handle GET requests to retrieve the list of users.""" logger.debug("request: %s", request) return self.get_list(request)
[docs] def post(self, request, *args, **kwargs): """Handle POST requests to create a new user.""" logger.debug("request: %s", request) return self.get_list(request)