Skip to content

Commit

Permalink
✨(backend) domain accesses update API
Browse files Browse the repository at this point in the history
Allow to update (PUT, PATCH) an access.
Role can be change only to a role available
depending to the authenticated user.
  • Loading branch information
sdemagny committed Sep 18, 2024
1 parent e9b0075 commit 3e1f9b0
Show file tree
Hide file tree
Showing 2 changed files with 392 additions and 2 deletions.
36 changes: 34 additions & 2 deletions src/backend/mailbox_manager/api/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

from django.db.models import Subquery

from rest_framework import filters, mixins, viewsets
from rest_framework import exceptions, filters, mixins, viewsets
from rest_framework import permissions as drf_permissions

from core import models as core_models

from mailbox_manager import models
from mailbox_manager import enums, models
from mailbox_manager.api import permissions, serializers


Expand Down Expand Up @@ -58,6 +58,7 @@ def perform_create(self, serializer):
class MailDomainAccessViewSet(
viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin,
):
"""
Expand All @@ -66,6 +67,14 @@ class MailDomainAccessViewSet(
GET /api/v1.0/mail-domains/<domain_slug>/accesses/:<domain_access_id>
Return list of all domain accesses related to the logged-in user and one
domain access if an id is provided.
PUT /api/v1.0/mail-domains/<domain_slug>/accesses/<domain_access_id>/ with expected data:
- role: str [owner|admin|viewer]
Return updated domain access
PATCH /api/v1.0/mail-domains/<domain_slug>/accesses/<domain_access_id>/ with expected data:
- role: str [owner|admin|viewer]
Return partially updated domain access
"""

permission_classes = [drf_permissions.IsAuthenticated]
Expand Down Expand Up @@ -118,6 +127,29 @@ def get_queryset(self):
)
return queryset

def perform_update(self, serializer):
"""Check that we don't change the role if it leads to losing the last owner."""
instance = serializer.instance

# Check if the role is being updated and the new role is not "owner"
if (
"role" in self.request.data
and self.request.data["role"] != enums.MailDomainRoleChoices.OWNER
):
domain = instance.domain
# Check if the access being updated is the last owner access for the domain
if (
instance.role == enums.MailDomainRoleChoices.OWNER
and domain.accesses.filter(
role=enums.MailDomainRoleChoices.OWNER
).count()
== 1
):
message = "Cannot change the role to a non-owner role for the last owner access."
raise exceptions.ValidationError({"role": message})
# todo: check if the role is a role available (can_role_set_to)
serializer.save()


class MailBoxViewSet(
mixins.CreateModelMixin,
Expand Down
Loading

0 comments on commit 3e1f9b0

Please sign in to comment.