Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨(dimail) send domain creation request to dimail #454

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/backend/mailbox_manager/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from core.api.serializers import UserSerializer
from core.models import User

from rest_framework import status
from mailbox_manager import enums, models
from mailbox_manager.utils.dimail import DimailAPIClient

Expand Down Expand Up @@ -77,6 +78,21 @@ def get_abilities(self, domain) -> dict:
return domain.get_abilities(request.user)
return {}

def create(self, validated_data):
"""
Override create function to fire a request to dimail upon domain creation.
"""
# send new domain request to dimail
client = DimailAPIClient()
response = client.post_domain_creation_request(
validated_data["name"], self.context["request"].user.sub
)

if response.status_code == status.HTTP_201_CREATED:
# actually save mailbox on our database
return models.MailDomain.objects.create(**validated_data)
else:
return response

class MailDomainAccessSerializer(serializers.ModelSerializer):
"""Serialize mail domain access."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
Tests for MailDomains API endpoint in People's app mailbox_manager. Focus on "create" action.
"""

import re
from logging import Logger
from unittest import mock

import pytest
import responses
from rest_framework import status
from rest_framework.test import APIClient

Expand Down Expand Up @@ -81,3 +86,49 @@ def test_api_mail_domains__create_authenticated():
assert domain.status == enums.MailDomainStatusChoices.PENDING
assert domain.name == "mydomain.com"
assert domain.accesses.filter(role="owner", user=user).exists()


## SYNC TO DIMAIL
@mock.patch.object(Logger, "info")
def test_api_mail_domains__create_dimail_domain(mock_info):
"""
Creating a domain should trigger a call to create a domain on dimail too.
"""
user = core_factories.UserFactory()

client = APIClient()
client.force_login(user)
domain_name = "test.fr"

with responses.RequestsMock() as rsps:
rsp = rsps.add(
rsps.POST,
re.compile(r".*/domains/"),
body=str(
{
"name": domain_name,
}
),
status=status.HTTP_201_CREATED,
content_type="application/json",
)
response = client.post(
"/api/v1.0/mail-domains/",
{
"name": domain_name,
},
format="json",
)

assert response.status_code == status.HTTP_201_CREATED
# make sure domain creation endpoint was called
assert rsp.call_count == 1

# Logger
assert mock_info.call_count == 2
assert mock_info.call_args_list[0][0] == (
"Domain %s successfully created on dimail by user %s",
domain_name,
user.sub,
)
# a new empty info has been added. To be investigated
38 changes: 38 additions & 0 deletions src/backend/mailbox_manager/utils/dimail.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,44 @@ def get_headers(self, user_sub=None):

return self.pass_dimail_unexpected_response(response)

def post_domain_creation_request(self, domain_name, request_user):
"""Send a domain creation request to dimail API."""

payload = {"domain": domain_name}
try:
response = session.post(
f"{self.API_URL}/domains/",
json=payload,
headers={"Authorization": f"Basic {self.API_CREDENTIALS}"},
verify=True,
timeout=10,
)
except requests.exceptions.ConnectionError as error:
logger.error(
"Connection error while trying to reach %s.",
self.API_URL,
exc_info=error,
)
raise error

if response.status_code == status.HTTP_201_CREATED:
logger.info(
"Domain %s successfully created on dimail by user %s",
domain_name,
request_user,
)
return response

if response.status_code == status.HTTP_409_CONFLICT:
logger.info(
"User %s tried to create domain %s already existing.",
request_user,
domain_name,
)
return response

return self.pass_dimail_unexpected_response(response)

def send_mailbox_request(self, mailbox, user_sub=None):
"""Send a CREATE mailbox request to mail provisioning API."""

Expand Down
Loading