diff --git a/docs/developer/registry-access.md b/docs/developer/registry-access.md
index a59c8b8b7..c7737d5bc 100644
--- a/docs/developer/registry-access.md
+++ b/docs/developer/registry-access.md
@@ -31,7 +31,7 @@ Finally, you'll need to craft a request and send it.
```
request = ...
-response = registry.send(request)
+response = registry.send(request, cleaned=True)
```
Note that you'll need to attest that the data you are sending has been sanitized to remove malicious or invalid strings. Use `send(..., cleaned=True)` to do that.
diff --git a/src/epplibwrapper/client.py b/src/epplibwrapper/client.py
index 156ee7608..0234ef6c6 100644
--- a/src/epplibwrapper/client.py
+++ b/src/epplibwrapper/client.py
@@ -83,7 +83,7 @@ class EPPLibWrapper:
logger.warning(message, cmd_type, exc_info=True)
raise RegistryError(message) from err
except Exception as err:
- message = "%s failed to execute due to an unknown error."
+ message = "%s failed to execute due to an unknown error." % err
logger.warning(message, cmd_type, exc_info=True)
raise RegistryError(message) from err
else:
diff --git a/src/registrar/admin.py b/src/registrar/admin.py
index 78b19191e..d78947c85 100644
--- a/src/registrar/admin.py
+++ b/src/registrar/admin.py
@@ -130,6 +130,7 @@ class MyUserAdmin(BaseUserAdmin):
inlines = [UserContactInline]
list_display = (
+ "username",
"email",
"first_name",
"last_name",
@@ -159,10 +160,51 @@ class MyUserAdmin(BaseUserAdmin):
("Important dates", {"fields": ("last_login", "date_joined")}),
)
+ analyst_fieldsets = (
+ (
+ None,
+ {"fields": ("password", "status")},
+ ),
+ ("Personal Info", {"fields": ("first_name", "last_name", "email")}),
+ (
+ "Permissions",
+ {
+ "fields": (
+ "is_active",
+ "is_staff",
+ "is_superuser",
+ )
+ },
+ ),
+ ("Important dates", {"fields": ("last_login", "date_joined")}),
+ )
+
+ analyst_readonly_fields = [
+ "password",
+ "Personal Info",
+ "first_name",
+ "last_name",
+ "email",
+ "Permissions",
+ "is_active",
+ "is_staff",
+ "is_superuser",
+ "Important dates",
+ "last_login",
+ "date_joined",
+ ]
+
def get_list_display(self, request):
if not request.user.is_superuser:
# Customize the list display for staff users
- return ("email", "first_name", "last_name", "is_staff", "is_superuser")
+ return (
+ "email",
+ "first_name",
+ "last_name",
+ "is_staff",
+ "is_superuser",
+ "status",
+ )
# Use the default list display for non-staff users
return super().get_list_display(request)
@@ -171,11 +213,18 @@ class MyUserAdmin(BaseUserAdmin):
if not request.user.is_superuser:
# If the user doesn't have permission to change the model,
# show a read-only fieldset
- return ((None, {"fields": []}),)
+ return self.analyst_fieldsets
# If the user has permission to change the model, show all fields
return super().get_fieldsets(request, obj)
+ def get_readonly_fields(self, request, obj=None):
+ if request.user.is_superuser:
+ return () # No read-only fields for superusers
+ elif request.user.is_staff:
+ return self.analyst_readonly_fields # Read-only fields for staff
+ return () # No read-only fields for other users
+
class HostIPInline(admin.StackedInline):
"""Edit an ip address on the host page."""
@@ -189,102 +238,6 @@ class MyHostAdmin(AuditedAdmin):
inlines = [HostIPInline]
-class DomainAdmin(ListHeaderAdmin):
- """Custom domain admin class to add extra buttons."""
-
- # Columns
- list_display = [
- "name",
- "organization_type",
- "state",
- ]
-
- def organization_type(self, obj):
- return obj.domain_info.organization_type
-
- organization_type.admin_order_field = ( # type: ignore
- "domain_info__organization_type"
- )
-
- # Filters
- list_filter = ["domain_info__organization_type"]
-
- search_fields = ["name"]
- search_help_text = "Search by domain name."
- change_form_template = "django/admin/domain_change_form.html"
- readonly_fields = ["state"]
-
- def response_change(self, request, obj):
- # Create dictionary of action functions
- ACTION_FUNCTIONS = {
- "_place_client_hold": self.do_place_client_hold,
- "_remove_client_hold": self.do_remove_client_hold,
- "_edit_domain": self.do_edit_domain,
- }
-
- # Check which action button was pressed and call the corresponding function
- for action, function in ACTION_FUNCTIONS.items():
- if action in request.POST:
- return function(request, obj)
-
- # If no matching action button is found, return the super method
- return super().response_change(request, obj)
-
- def do_place_client_hold(self, request, obj):
- try:
- obj.place_client_hold()
- obj.save()
- except Exception as err:
- self.message_user(request, err, messages.ERROR)
- else:
- self.message_user(
- request,
- (
- "%s is in client hold. This domain is no longer accessible on"
- " the public internet."
- )
- % obj.name,
- )
- return HttpResponseRedirect(".")
-
- def do_remove_client_hold(self, request, obj):
- try:
- obj.remove_client_hold()
- obj.save()
- except Exception as err:
- self.message_user(request, err, messages.ERROR)
- else:
- self.message_user(
- request,
- ("%s is ready. This domain is accessible on the public internet.")
- % obj.name,
- )
- return HttpResponseRedirect(".")
-
- def do_edit_domain(self, request, obj):
- # We want to know, globally, when an edit action occurs
- request.session["analyst_action"] = "edit"
- # Restricts this action to this domain (pk) only
- request.session["analyst_action_location"] = obj.id
- return HttpResponseRedirect(reverse("domain", args=(obj.id,)))
-
- def change_view(self, request, object_id):
- # If the analyst was recently editing a domain page,
- # delete any associated session values
- if "analyst_action" in request.session:
- del request.session["analyst_action"]
- del request.session["analyst_action_location"]
- return super().change_view(request, object_id)
-
- def has_change_permission(self, request, obj=None):
- # Fixes a bug wherein users which are only is_staff
- # can access 'change' when GET,
- # but cannot access this page when it is a request of type POST.
- if request.user.is_staff:
- return True
- return super().has_change_permission(request, obj)
-
-
class ContactAdmin(ListHeaderAdmin):
"""Custom contact admin class to add search."""
@@ -380,6 +333,81 @@ class DomainInformationAdmin(ListHeaderAdmin):
]
search_help_text = "Search by domain."
+ fieldsets = [
+ (None, {"fields": ["creator", "domain_application"]}),
+ (
+ "Type of organization",
+ {
+ "fields": [
+ "organization_type",
+ "federally_recognized_tribe",
+ "state_recognized_tribe",
+ "tribe_name",
+ "federal_agency",
+ "federal_type",
+ "is_election_board",
+ "about_your_organization",
+ ]
+ },
+ ),
+ (
+ "Organization name and mailing address",
+ {
+ "fields": [
+ "organization_name",
+ "address_line1",
+ "address_line2",
+ "city",
+ "state_territory",
+ "zipcode",
+ "urbanization",
+ ]
+ },
+ ),
+ ("Authorizing official", {"fields": ["authorizing_official"]}),
+ (".gov domain", {"fields": ["domain"]}),
+ ("Your contact information", {"fields": ["submitter"]}),
+ ("Other employees from your organization?", {"fields": ["other_contacts"]}),
+ (
+ "No other employees from your organization?",
+ {"fields": ["no_other_contacts_rationale"]},
+ ),
+ ("Anything else we should know?", {"fields": ["anything_else"]}),
+ (
+ "Requirements for operating .gov domains",
+ {"fields": ["is_policy_acknowledged"]},
+ ),
+ ]
+
+ # Read only that we'll leverage for CISA Analysts
+ analyst_readonly_fields = [
+ "creator",
+ "type_of_work",
+ "more_organization_information",
+ "address_line1",
+ "address_line2",
+ "zipcode",
+ "domain",
+ "submitter",
+ "no_other_contacts_rationale",
+ "anything_else",
+ "is_policy_acknowledged",
+ ]
+
+ def get_readonly_fields(self, request, obj=None):
+ """Set the read-only state on form elements.
+ We have 1 conditions that determine which fields are read-only:
+ admin user permissions.
+ """
+
+ readonly_fields = list(self.readonly_fields)
+
+ if request.user.is_superuser:
+ return readonly_fields
+ else:
+ readonly_fields.extend([field for field in self.analyst_readonly_fields])
+ return readonly_fields
+
class DomainApplicationAdminForm(forms.ModelForm):
"""Custom form to limit transitions to available transitions"""
@@ -416,10 +444,6 @@ class DomainApplicationAdmin(ListHeaderAdmin):
"""Custom domain applications admin class."""
- # Set multi-selects 'read-only' (hide selects and show data)
- # based on user perms and application creator's status
- # form = DomainApplicationForm
-
# Columns
list_display = [
"requested_domain",
@@ -445,7 +469,7 @@ class DomainApplicationAdmin(ListHeaderAdmin):
# Detail view
form = DomainApplicationAdminForm
fieldsets = [
- (None, {"fields": ["status", "investigator", "creator"]}),
+ (None, {"fields": ["status", "investigator", "creator", "approved_domain"]}),
(
"Type of organization",
{
@@ -457,8 +481,7 @@ class DomainApplicationAdmin(ListHeaderAdmin):
"federal_agency",
"federal_type",
"is_election_board",
- "type_of_work",
- "more_organization_information",
+ "about_your_organization",
]
},
),
@@ -496,8 +519,7 @@ class DomainApplicationAdmin(ListHeaderAdmin):
# Read only that we'll leverage for CISA Analysts
analyst_readonly_fields = [
"creator",
- "type_of_work",
- "more_organization_information",
+ "about_your_organization",
"address_line1",
"address_line2",
"zipcode",
@@ -517,29 +539,57 @@ class DomainApplicationAdmin(ListHeaderAdmin):
# Get the original application from the database
original_obj = models.DomainApplication.objects.get(pk=obj.pk)
- if obj.status != original_obj.status:
- status_method_mapping = {
- models.DomainApplication.STARTED: None,
- models.DomainApplication.SUBMITTED: obj.submit,
- models.DomainApplication.IN_REVIEW: obj.in_review,
- models.DomainApplication.ACTION_NEEDED: obj.action_needed,
- models.DomainApplication.APPROVED: obj.approve,
- models.DomainApplication.WITHDRAWN: obj.withdraw,
- models.DomainApplication.REJECTED: obj.reject,
- models.DomainApplication.INELIGIBLE: obj.reject_with_prejudice,
- }
- selected_method = status_method_mapping.get(obj.status)
- if selected_method is None:
- logger.warning("Unknown status selected in django admin")
- else:
- # This is an fsm in model which will throw an error if the
- # transition condition is violated, so we roll back the
- # status to what it was before the admin user changed it and
- # let the fsm method set it.
- obj.status = original_obj.status
- selected_method()
+ if (
+ obj
+ and original_obj.status == models.DomainApplication.APPROVED
+ and (
+ obj.status == models.DomainApplication.REJECTED
+ or obj.status == models.DomainApplication.INELIGIBLE
+ )
+ and not obj.domain_is_not_active()
+ ):
+ # If an admin tried to set an approved application to
+ # rejected or ineligible and the related domain is already
+ # active, shortcut the action and throw a friendly
+ # error message. This action would still not go through
+ # shortcut or not as the rules are duplicated on the model,
+ # but the error would be an ugly Django error screen.
- super().save_model(request, obj, form, change)
+ # Clear the success message
+ messages.set_level(request, messages.ERROR)
+
+ messages.error(
+ request,
+ "This action is not permitted. The domain "
+ + "is already active.",
+ )
+
+ else:
+ if obj.status != original_obj.status:
+ status_method_mapping = {
+ models.DomainApplication.STARTED: None,
+ models.DomainApplication.SUBMITTED: obj.submit,
+ models.DomainApplication.IN_REVIEW: obj.in_review,
+ models.DomainApplication.ACTION_NEEDED: obj.action_needed,
+ models.DomainApplication.APPROVED: obj.approve,
+ models.DomainApplication.WITHDRAWN: obj.withdraw,
+ models.DomainApplication.REJECTED: obj.reject,
+ models.DomainApplication.INELIGIBLE: (
+ obj.reject_with_prejudice
+ ),
+ }
+ selected_method = status_method_mapping.get(obj.status)
+ if selected_method is None:
+ logger.warning("Unknown status selected in django admin")
+ else:
+ # This is an fsm in model which will throw an error if the
+ # transition condition is violated, so we roll back the
+ # status to what it was before the admin user changed it and
+ # let the fsm method set it.
+ obj.status = original_obj.status
+ selected_method()
+
+ super().save_model(request, obj, form, change)
else:
# Clear the success message
messages.set_level(request, messages.ERROR)
@@ -589,6 +639,154 @@ class DomainApplicationAdmin(ListHeaderAdmin):
return super().change_view(request, object_id, form_url, extra_context)
+class DomainInformationInline(admin.StackedInline):
+ """Edit a domain information on the domain page.
+ We had issues inheriting from both StackedInline
+ and the source DomainInformationAdmin since these
+ classes conflict, so we'll just pull what we need
+ from DomainInformationAdmin"""
+
+ model = models.DomainInformation
+
+ fieldsets = DomainInformationAdmin.fieldsets
+ analyst_readonly_fields = DomainInformationAdmin.analyst_readonly_fields
+
+ def get_readonly_fields(self, request, obj=None):
+ return DomainInformationAdmin.get_readonly_fields(self, request, obj=None)
+
+
+class DomainAdmin(ListHeaderAdmin):
+ """Custom domain admin class to add extra buttons."""
+
+ inlines = [DomainInformationInline]
+
+ # Columns
+ list_display = [
+ "name",
+ "organization_type",
+ "state",
+ ]
+
+ def organization_type(self, obj):
+ return obj.domain_info.organization_type
+
+ organization_type.admin_order_field = ( # type: ignore
+ "domain_info__organization_type"
+ )
+
+ # Filters
+ list_filter = ["domain_info__organization_type", "state"]
+
+ search_fields = ["name"]
+ search_help_text = "Search by domain name."
+ change_form_template = "django/admin/domain_change_form.html"
+ readonly_fields = ["state"]
+
+ def response_change(self, request, obj):
+ # Create dictionary of action functions
+ ACTION_FUNCTIONS = {
+ "_place_client_hold": self.do_place_client_hold,
+ "_remove_client_hold": self.do_remove_client_hold,
+ "_edit_domain": self.do_edit_domain,
+ "_delete_domain": self.do_delete_domain,
+ "_get_status": self.do_get_status,
+ }
+
+ # Check which action button was pressed and call the corresponding function
+ for action, function in ACTION_FUNCTIONS.items():
+ if action in request.POST:
+ return function(request, obj)
+
+ # If no matching action button is found, return the super method
+ return super().response_change(request, obj)
+
+ def do_delete_domain(self, request, obj):
+ try:
+ obj.deleted()
+ obj.save()
+ except Exception as err:
+ self.message_user(request, err, messages.ERROR)
+ else:
+ self.message_user(
+ request,
+ ("Domain %s Should now be deleted " ". Thanks!") % obj.name,
+ )
+ return HttpResponseRedirect(".")
+
+ def do_get_status(self, request, obj):
+ try:
+ statuses = obj.statuses
+ except Exception as err:
+ self.message_user(request, err, messages.ERROR)
+ else:
+ self.message_user(
+ request,
+ ("Domain statuses are %s" ". Thanks!") % statuses,
+ )
+ return HttpResponseRedirect(".")
+
+ def do_place_client_hold(self, request, obj):
+ try:
+ obj.place_client_hold()
+ obj.save()
+ except Exception as err:
+ self.message_user(request, err, messages.ERROR)
+ else:
+ self.message_user(
+ request,
+ (
+ "%s is in client hold. This domain is no longer accessible on"
+ " the public internet."
+ )
+ % obj.name,
+ )
+ return HttpResponseRedirect(".")
+
+ def do_remove_client_hold(self, request, obj):
+ try:
+ obj.revert_client_hold()
+ obj.save()
+ except Exception as err:
+ self.message_user(request, err, messages.ERROR)
+ else:
+ self.message_user(
+ request,
+ ("%s is ready. This domain is accessible on the public internet.")
+ % obj.name,
+ )
+ return HttpResponseRedirect(".")
+
+ def do_edit_domain(self, request, obj):
+ # We want to know, globally, when an edit action occurs
+ request.session["analyst_action"] = "edit"
+ # Restricts this action to this domain (pk) only
+ request.session["analyst_action_location"] = obj.id
+ return HttpResponseRedirect(reverse("domain", args=(obj.id,)))
+
+ def change_view(self, request, object_id):
+ # If the analyst was recently editing a domain page,
+ # delete any associated session values
+ if "analyst_action" in request.session:
+ del request.session["analyst_action"]
+ del request.session["analyst_action_location"]
+ return super().change_view(request, object_id)
+
+ def has_change_permission(self, request, obj=None):
+ # Fixes a bug wherein users which are only is_staff
+ # can access 'change' when GET,
+ # but cannot access this page when it is a request of type POST.
+ if request.user.is_staff:
+ return True
+ return super().has_change_permission(request, obj)
+
+
+class DraftDomainAdmin(ListHeaderAdmin):
+ """Custom draft domain admin class."""
+
+ search_fields = ["name"]
+ search_help_text = "Search by draft domain name."
+
+
admin.site.unregister(LogEntry) # Unregister the default registration
admin.site.register(LogEntry, CustomLogEntryAdmin)
admin.site.register(models.User, MyUserAdmin)
@@ -597,8 +795,10 @@ admin.site.register(models.Contact, ContactAdmin)
admin.site.register(models.DomainInvitation, DomainInvitationAdmin)
admin.site.register(models.DomainInformation, DomainInformationAdmin)
admin.site.register(models.Domain, DomainAdmin)
+admin.site.register(models.DraftDomain, DraftDomainAdmin)
admin.site.register(models.Host, MyHostAdmin)
admin.site.register(models.Nameserver, MyHostAdmin)
admin.site.register(models.Website, WebsiteAdmin)
+admin.site.register(models.PublicContact, AuditedAdmin)
admin.site.register(models.DomainApplication, DomainApplicationAdmin)
admin.site.register(models.TransitionDomain, AuditedAdmin)
diff --git a/src/registrar/config/urls.py b/src/registrar/config/urls.py
index 0f136c932..9c3624c2c 100644
--- a/src/registrar/config/urls.py
+++ b/src/registrar/config/urls.py
@@ -27,7 +27,7 @@ for step, view in [
(Step.ORGANIZATION_FEDERAL, views.OrganizationFederal),
(Step.ORGANIZATION_ELECTION, views.OrganizationElection),
(Step.ORGANIZATION_CONTACT, views.OrganizationContact),
- (Step.TYPE_OF_WORK, views.TypeOfWork),
+ (Step.ABOUT_YOUR_ORGANIZATION, views.AboutYourOrganization),
(Step.AUTHORIZING_OFFICIAL, views.AuthorizingOfficial),
(Step.CURRENT_SITES, views.CurrentSites),
(Step.DOTGOV_DOMAIN, views.DotgovDomain),
diff --git a/src/registrar/fixtures.py b/src/registrar/fixtures.py
index 30924b8bf..a4e75dd2e 100644
--- a/src/registrar/fixtures.py
+++ b/src/registrar/fixtures.py
@@ -143,13 +143,23 @@ class UserFixture:
"permissions": ["view_logentry"],
},
{"app_label": "registrar", "model": "contact", "permissions": ["view_contact"]},
+ {
+ "app_label": "registrar",
+ "model": "domaininformation",
+ "permissions": ["change_domaininformation"],
+ },
{
"app_label": "registrar",
"model": "domainapplication",
"permissions": ["change_domainapplication"],
},
{"app_label": "registrar", "model": "domain", "permissions": ["view_domain"]},
- {"app_label": "registrar", "model": "user", "permissions": ["view_user"]},
+ {
+ "app_label": "registrar",
+ "model": "draftdomain",
+ "permissions": ["change_draftdomain"],
+ },
+ {"app_label": "registrar", "model": "user", "permissions": ["change_user"]},
]
@classmethod
diff --git a/src/registrar/forms/application_wizard.py b/src/registrar/forms/application_wizard.py
index 578a501d3..516683247 100644
--- a/src/registrar/forms/application_wizard.py
+++ b/src/registrar/forms/application_wizard.py
@@ -6,12 +6,12 @@ from phonenumber_field.formfields import PhoneNumberField # type: ignore
from django import forms
from django.core.validators import RegexValidator, MaxLengthValidator
-from django.urls import reverse
from django.utils.safestring import mark_safe
from api.views import DOMAIN_API_MESSAGES
from registrar.models import Contact, DomainApplication, DraftDomain, Domain
+from registrar.templatetags.url_helpers import public_site_url
from registrar.utility import errors
logger = logging.getLogger(__name__)
@@ -181,7 +181,6 @@ class TribalGovernmentForm(RegistrarForm):
self.cleaned_data["federally_recognized_tribe"]
or self.cleaned_data["state_recognized_tribe"]
):
- todo_url = reverse("todo")
raise forms.ValidationError(
# no sec because we are using it to include an internal URL
# into a link. There should be no user-facing input in the
@@ -190,10 +189,10 @@ class TribalGovernmentForm(RegistrarForm):
"You can’t complete this application yet. "
"Only tribes recognized by the U.S. federal government "
"or by a U.S. state government are eligible for .gov "
- 'domains. Please use our contact form to '
+ 'domains. Use our contact form to '
"tell us more about your tribe and why you want a .gov "
"domain. We’ll review your information and get back "
- "to you.".format(todo_url)
+ "to you.".format(public_site_url("contact"))
),
code="invalid",
)
@@ -310,28 +309,9 @@ class OrganizationContactForm(RegistrarForm):
return federal_agency
-class TypeOfWorkForm(RegistrarForm):
- type_of_work = forms.CharField(
- # label has to end in a space to get the label_suffix to show
- label="What type of work does your organization do? ",
- widget=forms.Textarea(),
- validators=[
- MaxLengthValidator(
- 1000,
- message="Response must be less than 1000 characters.",
- )
- ],
- error_messages={"required": "Enter the type of work your organization does."},
- )
-
- more_organization_information = forms.CharField(
- # label has to end in a space to get the label_suffix to show
- label=(
- "Describe how your organization is a government organization that is"
- " independent of a state government. Include links to authorizing"
- " legislation, applicable bylaws or charter, or other documentation to"
- " support your claims. "
- ),
+class AboutYourOrganizationForm(RegistrarForm):
+ about_your_organization = forms.CharField(
+ label="About your organization",
widget=forms.Textarea(),
validators=[
MaxLengthValidator(
@@ -340,9 +320,7 @@ class TypeOfWorkForm(RegistrarForm):
)
],
error_messages={
- "required": (
- "Describe how your organization is independent of a state government."
- )
+ "required": ("Enter more information about your organization.")
},
)
diff --git a/src/registrar/management/commands/load.py b/src/registrar/management/commands/load.py
index 69e7e9ec8..589d37260 100644
--- a/src/registrar/management/commands/load.py
+++ b/src/registrar/management/commands/load.py
@@ -2,7 +2,7 @@ import logging
from django.core.management.base import BaseCommand
from auditlog.context import disable_auditlog # type: ignore
-from django.conf import settings
+
from registrar.fixtures import UserFixture, DomainApplicationFixture, DomainFixture
@@ -13,11 +13,8 @@ class Command(BaseCommand):
def handle(self, *args, **options):
# django-auditlog has some bugs with fixtures
# https://github.com/jazzband/django-auditlog/issues/17
- if settings.DEBUG:
- with disable_auditlog():
- UserFixture.load()
- DomainApplicationFixture.load()
- DomainFixture.load()
- logger.info("All fixtures loaded.")
- else:
- logger.warn("Refusing to load fixture data in a non DEBUG env")
+ with disable_auditlog():
+ UserFixture.load()
+ DomainApplicationFixture.load()
+ DomainFixture.load()
+ logger.info("All fixtures loaded.")
diff --git a/src/registrar/migrations/0031_alter_domain_state.py b/src/registrar/migrations/0031_alter_domain_state.py
deleted file mode 100644
index 2545adb27..000000000
--- a/src/registrar/migrations/0031_alter_domain_state.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# Generated by Django 4.2.1 on 2023-09-07 17:53
-
-from django.db import migrations
-import django_fsm
-
-
-class Migration(migrations.Migration):
- dependencies = [
- ("registrar", "0030_alter_user_status"),
- ]
-
- operations = [
- migrations.AlterField(
- model_name="domain",
- name="state",
- field=django_fsm.FSMField(
- choices=[
- ("created", "Created"),
- ("deleted", "Deleted"),
- ("unknown", "Unknown"),
- ("ready", "Ready"),
- ("onhold", "Onhold"),
- ],
- default="unknown",
- help_text="Very basic info about the lifecycle of this domain object",
- max_length=21,
- protected=True,
- ),
- ),
- ]
diff --git a/src/registrar/migrations/0031_transitiondomain.py b/src/registrar/migrations/0031_transitiondomain.py
deleted file mode 100644
index e72a8d85a..000000000
--- a/src/registrar/migrations/0031_transitiondomain.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# Generated by Django 4.2.1 on 2023-09-11 14:44
-
-from django.db import migrations, models
-
-
-class Migration(migrations.Migration):
- dependencies = [
- ("registrar", "0030_alter_user_status"),
- ]
-
- operations = [
- migrations.CreateModel(
- name="TransitionDomain",
- fields=[
- (
- "id",
- models.BigAutoField(
- auto_created=True,
- primary_key=True,
- serialize=False,
- verbose_name="ID",
- ),
- ),
- ("created_at", models.DateTimeField(auto_now_add=True)),
- ("updated_at", models.DateTimeField(auto_now=True)),
- (
- "username",
- models.TextField(
- help_text="Username - this will be an email address",
- verbose_name="Username",
- ),
- ),
- (
- "domain_name",
- models.TextField(blank=True, null=True, verbose_name="Domain name"),
- ),
- (
- "status",
- models.CharField(
- blank=True,
- choices=[("created", "Created"), ("hold", "Hold")],
- help_text="domain status during the transfer",
- max_length=255,
- verbose_name="Status",
- ),
- ),
- (
- "email_sent",
- models.BooleanField(
- default=False,
- help_text="indicates whether email was sent",
- verbose_name="email sent",
- ),
- ),
- ],
- options={
- "abstract": False,
- },
- ),
- ]
diff --git a/src/registrar/migrations/0031_transitiondomain_and_more.py b/src/registrar/migrations/0031_transitiondomain_and_more.py
new file mode 100644
index 000000000..e378a33de
--- /dev/null
+++ b/src/registrar/migrations/0031_transitiondomain_and_more.py
@@ -0,0 +1,147 @@
+# Generated by Django 4.2.1 on 2023-09-15 21:05
+
+from django.db import migrations, models
+import django.db.models.deletion
+import django_fsm
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("registrar", "0030_alter_user_status"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="domain",
+ name="state",
+ field=django_fsm.FSMField(
+ choices=[
+ ("unknown", "Unknown"),
+ ("dns needed", "Dns Needed"),
+ ("ready", "Ready"),
+ ("on hold", "On Hold"),
+ ("deleted", "Deleted"),
+ ],
+ default="unknown",
+ help_text="Very basic info about the lifecycle of this domain object",
+ max_length=21,
+ protected=True,
+ ),
+ ),
+ migrations.CreateModel(
+ name="TransitionDomain",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "username",
+ models.TextField(
+ help_text="Username - this will be an email address",
+ verbose_name="Username",
+ ),
+ ),
+ (
+ "domain_name",
+ models.TextField(blank=True, null=True, verbose_name="Domain name"),
+ ),
+ (
+ "status",
+ models.CharField(
+ blank=True,
+ choices=[("created", "Created"), ("hold", "Hold")],
+ help_text="domain status during the transfer",
+ max_length=255,
+ verbose_name="Status",
+ ),
+ ),
+ (
+ "email_sent",
+ models.BooleanField(
+ default=False,
+ help_text="indicates whether email was sent",
+ verbose_name="email sent",
+ ),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ migrations.RemoveField(
+ model_name="domainapplication",
+ name="more_organization_information",
+ ),
+ migrations.RemoveField(
+ model_name="domainapplication",
+ name="type_of_work",
+ ),
+ migrations.RemoveField(
+ model_name="domaininformation",
+ name="more_organization_information",
+ ),
+ migrations.RemoveField(
+ model_name="domaininformation",
+ name="type_of_work",
+ ),
+ migrations.AddField(
+ model_name="domainapplication",
+ name="about_your_organization",
+ field=models.TextField(
+ blank=True, help_text="Information about your organization", null=True
+ ),
+ ),
+ migrations.AddField(
+ model_name="domaininformation",
+ name="about_your_organization",
+ field=models.TextField(
+ blank=True, help_text="Information about your organization", null=True
+ ),
+ ),
+ migrations.AlterField(
+ model_name="domainapplication",
+ name="approved_domain",
+ field=models.OneToOneField(
+ blank=True,
+ help_text="The approved domain",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="domain_application",
+ to="registrar.domain",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="domaininformation",
+ name="domain",
+ field=models.OneToOneField(
+ blank=True,
+ help_text="Domain to which this information belongs",
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="domain_info",
+ to="registrar.domain",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="publiccontact",
+ name="contact_type",
+ field=models.CharField(
+ choices=[
+ ("registrant", "Registrant"),
+ ("admin", "Administrative"),
+ ("tech", "Technical"),
+ ("security", "Security"),
+ ],
+ help_text="For which type of WHOIS contact",
+ max_length=14,
+ ),
+ ),
+ ]
diff --git a/src/registrar/migrations/0032_merge_0031_alter_domain_state_0031_transitiondomain.py b/src/registrar/migrations/0032_merge_0031_alter_domain_state_0031_transitiondomain.py
deleted file mode 100644
index 4c0a38427..000000000
--- a/src/registrar/migrations/0032_merge_0031_alter_domain_state_0031_transitiondomain.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# Generated by Django 4.2.1 on 2023-09-12 14:12
-
-from django.db import migrations
-
-
-class Migration(migrations.Migration):
- dependencies = [
- ("registrar", "0031_alter_domain_state"),
- ("registrar", "0031_transitiondomain"),
- ]
-
- operations = []
diff --git a/src/registrar/models/domain.py b/src/registrar/models/domain.py
index 306f895c6..13405d9bb 100644
--- a/src/registrar/models/domain.py
+++ b/src/registrar/models/domain.py
@@ -105,20 +105,21 @@ class Domain(TimeStampedModel, DomainHelper):
class State(models.TextChoices):
"""These capture (some of) the states a domain object can be in."""
- # the normal state of a domain object -- may or may not be active!
- CREATED = "created"
-
- # previously existed but has been deleted from the registry
- DELETED = "deleted"
-
# the state is indeterminate
UNKNOWN = "unknown"
- # the ready state for a domain object
+ # The domain object exists in the registry
+ # but nameservers don't exist for it yet
+ DNS_NEEDED = "dns needed"
+
+ # Domain has had nameservers set, may or may not be active
READY = "ready"
- # when a domain is on hold
- ONHOLD = "onhold"
+ # Registrar manually changed state to client hold
+ ON_HOLD = "on hold"
+
+ # previously existed but has been deleted from the registry
+ DELETED = "deleted"
class Cache(property):
"""
@@ -199,7 +200,7 @@ class Domain(TimeStampedModel, DomainHelper):
@expiration_date.setter # type: ignore
def expiration_date(self, ex_date: date):
- raise NotImplementedError()
+ pass
@Cache
def password(self) -> str:
@@ -225,34 +226,129 @@ class Domain(TimeStampedModel, DomainHelper):
Subordinate hosts (something.your-domain.gov) MUST have IP addresses,
while non-subordinate hosts MUST NOT.
"""
- # TODO: call EPP to get this info instead of returning fake data.
- return [
- ("ns1.example.com",),
- ("ns2.example.com",),
- ("ns3.example.com",),
- ]
+ try:
+ hosts = self._get_property("hosts")
+ except Exception as err:
+ # Don't throw error as this is normal for a new domain
+ # TODO - 433 error handling ticket should address this
+ logger.info("Domain is missing nameservers %s" % err)
+ return []
+
+ hostList = []
+ for host in hosts:
+ # TODO - this should actually have a second tuple value with the ip address
+ # ignored because uncertain if we will even have a way to display mult.
+ # and adresses can be a list of mult address
+ hostList.append((host["name"],))
+
+ return hostList
+
+ def _check_host(self, hostnames: list[str]):
+ """check if host is available, True if available
+ returns boolean"""
+ checkCommand = commands.CheckHost(hostnames)
+ try:
+ response = registry.send(checkCommand, cleaned=True)
+ return response.res_data[0].avail
+ except RegistryError as err:
+ logger.warning(
+ "Couldn't check hosts %s. Errorcode was %s, error was %s",
+ hostnames,
+ err.code,
+ err,
+ )
+ return False
+
+ def _create_host(self, host, addrs):
+ """Call _check_host first before using this function,
+ This creates the host object in the registry
+ doesn't add the created host to the domain
+ returns ErrorCode (int)"""
+ logger.info("Creating host")
+ if addrs is not None:
+ addresses = [epp.Ip(addr=addr) for addr in addrs]
+ request = commands.CreateHost(name=host, addrs=addresses)
+ else:
+ request = commands.CreateHost(name=host)
+
+ try:
+ logger.info("_create_host()-> sending req as %s" % request)
+ response = registry.send(request, cleaned=True)
+ return response.code
+ except RegistryError as e:
+ logger.error("Error _create_host, code was %s error was %s" % (e.code, e))
+ return e.code
@nameservers.setter # type: ignore
def nameservers(self, hosts: list[tuple[str]]):
- # TODO: call EPP to set this info.
- pass
+ """host should be a tuple of type str, str,... where the elements are
+ Fully qualified host name, addresses associated with the host
+ example: [(ns1.okay.gov, 127.0.0.1, others ips)]"""
+ # TODO: ticket #848 finish this implementation
+ # must delete nameservers as well or update
+ # ip version checking may need to be added in a different ticket
+
+ if len(hosts) > 13:
+ raise ValueError(
+ "Too many hosts provided, you may not have more than 13 nameservers."
+ )
+ logger.info("Setting nameservers")
+ logger.info(hosts)
+ for hostTuple in hosts:
+ host = hostTuple[0]
+ addrs = None
+ if len(hostTuple) > 1:
+ addrs = hostTuple[1:]
+ avail = self._check_host([host])
+ if avail:
+ createdCode = self._create_host(host=host, addrs=addrs)
+
+ # update the domain obj
+ if createdCode == ErrorCode.COMMAND_COMPLETED_SUCCESSFULLY:
+ # add host to domain
+ request = commands.UpdateDomain(
+ name=self.name, add=[epp.HostObjSet([host])]
+ )
+
+ try:
+ registry.send(request, cleaned=True)
+ except RegistryError as e:
+ logger.error(
+ "Error adding nameserver, code was %s error was %s"
+ % (e.code, e)
+ )
+
+ try:
+ self.ready()
+ self.save()
+ except Exception as err:
+ logger.info(
+ "nameserver setter checked for create state "
+ "and it did not succeed. Error: %s" % err
+ )
+ # TODO - handle removed nameservers here will need to change the state
+ # then go back to DNS_NEEDED
@Cache
def statuses(self) -> list[str]:
"""
- Get or set the domain `status` elements from the registry.
+ Get the domain `status` elements from the registry.
A domain's status indicates various properties. See Domain.Status.
"""
- # implementation note: the Status object from EPP stores the string in
- # a dataclass property `state`, not to be confused with the `state` field here
- raise NotImplementedError()
+ try:
+ return self._get_property("statuses")
+ except KeyError:
+ logger.error("Can't retrieve status from domain info")
+ return []
@statuses.setter # type: ignore
def statuses(self, statuses: list[str]):
- # TODO: there are a long list of rules in the RFC about which statuses
- # can be combined; check that here and raise errors for invalid combinations -
- # some statuses cannot be set by the client at all
+ """
+ We will not implement this. Statuses are set by the registry
+ when we run delete and client hold, and these are the only statuses
+ we will be triggering.
+ """
raise NotImplementedError()
@Cache
@@ -262,9 +358,13 @@ class Domain(TimeStampedModel, DomainHelper):
@registrant_contact.setter # type: ignore
def registrant_contact(self, contact: PublicContact):
- # get id from PublicContact->.registry_id
- # call UpdateDomain() command with registrant as parameter
- raise NotImplementedError()
+ """Registrant is set when a domain is created,
+ so follow on additions will update the current registrant"""
+
+ logger.info("making registrant contact")
+ self._set_singleton_contact(
+ contact=contact, expectedType=contact.ContactTypeChoices.REGISTRANT
+ )
@Cache
def administrative_contact(self) -> PublicContact:
@@ -273,25 +373,220 @@ class Domain(TimeStampedModel, DomainHelper):
@administrative_contact.setter # type: ignore
def administrative_contact(self, contact: PublicContact):
- # call CreateContact, if contact doesn't exist yet for domain
- # call UpdateDomain with contact,
- # type options are[admin, billing, tech, security]
- # use admin as type parameter for this contact
- raise NotImplementedError()
+ logger.info("making admin contact")
+ if contact.contact_type != contact.ContactTypeChoices.ADMINISTRATIVE:
+ raise ValueError(
+ "Cannot set a registrant contact with a different contact type"
+ )
+ self._make_contact_in_registry(contact=contact)
+ self._update_domain_with_contact(contact, rem=False)
+
+ def get_default_security_contact(self):
+ logger.info("getting default sec contact")
+ contact = PublicContact.get_default_security()
+ contact.domain = self
+ return contact
+
+ def _update_epp_contact(self, contact: PublicContact):
+ """Sends UpdateContact to update the actual contact object,
+ domain object remains unaffected
+ should be used when changing email address
+ or other contact info on an existing domain
+ """
+ updateContact = commands.UpdateContact(
+ id=contact.registry_id,
+ # type: ignore
+ postal_info=self._make_epp_contact_postal_info(contact=contact),
+ email=contact.email,
+ voice=contact.voice,
+ fax=contact.fax,
+ ) # type: ignore
+
+ try:
+ registry.send(updateContact, cleaned=True)
+ except RegistryError as e:
+ logger.error(
+ "Error updating contact, code was %s error was %s" % (e.code, e)
+ )
+ # TODO - ticket 433 human readable error handling here
+
+ def _update_domain_with_contact(self, contact: PublicContact, rem=False):
+ """adds or removes a contact from a domain
+ rem being true indicates the contact will be removed from registry"""
+ logger.info(
+ "_update_domain_with_contact() received type %s " % contact.contact_type
+ )
+ domainContact = epp.DomainContact(
+ contact=contact.registry_id, type=contact.contact_type
+ )
+
+ updateDomain = commands.UpdateDomain(name=self.name, add=[domainContact])
+ if rem:
+ updateDomain = commands.UpdateDomain(name=self.name, rem=[domainContact])
+
+ try:
+ registry.send(updateDomain, cleaned=True)
+ except RegistryError as e:
+ logger.error(
+ "Error changing contact on a domain. Error code is %s error was %s"
+ % (e.code, e)
+ )
+ action = "add"
+ if rem:
+ action = "remove"
+
+ raise Exception(
+ "Can't %s the contact of type %s" % (action, contact.contact_type)
+ )
@Cache
def security_contact(self) -> PublicContact:
"""Get or set the security contact for this domain."""
- # TODO: replace this with a real implementation
- contact = PublicContact.get_default_security()
- contact.domain = self
- contact.email = "mayor@igorville.gov"
- return contact
+ try:
+ contacts = self._get_property("contacts")
+ for contact in contacts:
+ if (
+ "type" in contact.keys()
+ and contact["type"] == PublicContact.ContactTypeChoices.SECURITY
+ ):
+ tempContact = self.get_default_security_contact()
+ tempContact.email = contact["email"]
+ return tempContact
+
+ except Exception as err: # use better error handling
+ logger.info("Couldn't get contact %s" % err)
+
+ # TODO - remove this ideally it should return None,
+ # but error handling needs to be
+ # added on the security email page so that it can handle it being none
+ return self.get_default_security_contact()
+
+ def _add_registrant_to_existing_domain(self, contact: PublicContact):
+ """Used to change the registrant contact on an existing domain"""
+ updateDomain = commands.UpdateDomain(
+ name=self.name, registrant=contact.registry_id
+ )
+ try:
+ registry.send(updateDomain, cleaned=True)
+ except RegistryError as e:
+ logger.error(
+ "Error changing to new registrant error code is %s, error is %s"
+ % (e.code, e)
+ )
+ # TODO-error handling better here?
+
+ def _set_singleton_contact(self, contact: PublicContact, expectedType: str): # noqa
+ """Sets the contacts by adding them to the registry as new contacts,
+ updates the contact if it is already in epp,
+ deletes any additional contacts of the matching type for this domain
+ does not create the PublicContact object, this should be made beforehand
+ (call save() on a public contact to trigger the contact setters
+ which inturn call this function)
+ Will throw error if contact type is not the same as expectType
+ Raises ValueError if expected type doesn't match the contact type"""
+ if expectedType != contact.contact_type:
+ raise ValueError(
+ "Cannot set a contact with a different contact type,"
+ " expected type was %s" % expectedType
+ )
+
+ isRegistrant = contact.contact_type == contact.ContactTypeChoices.REGISTRANT
+ isEmptySecurity = (
+ contact.contact_type == contact.ContactTypeChoices.SECURITY
+ and contact.email == ""
+ )
+
+ # get publicContact objects that have the matching
+ # domain and type but a different id
+ # like in highlander we there can only be one
+ hasOtherContact = (
+ PublicContact.objects.exclude(registry_id=contact.registry_id)
+ .filter(domain=self, contact_type=contact.contact_type)
+ .exists()
+ )
+
+ # if no record exists with this contact type
+ # make contact in registry, duplicate and errors handled there
+ errorCode = self._make_contact_in_registry(contact)
+
+ # contact is already added to the domain, but something may have changed on it
+ alreadyExistsInRegistry = errorCode == ErrorCode.OBJECT_EXISTS
+ # if an error occured besides duplication, stop
+ if (
+ not alreadyExistsInRegistry
+ and errorCode != ErrorCode.COMMAND_COMPLETED_SUCCESSFULLY
+ ):
+ # TODO- ticket #433 look here for error handling
+ raise Exception("Unable to add contact to registry")
+
+ # contact doesn't exist on the domain yet
+ logger.info("_set_singleton_contact()-> contact has been added to the registry")
+
+ # if has conflicting contacts in our db remove them
+ if hasOtherContact:
+ logger.info(
+ "_set_singleton_contact()-> updating domain, removing old contact"
+ )
+
+ existing_contact = (
+ PublicContact.objects.exclude(registry_id=contact.registry_id)
+ .filter(domain=self, contact_type=contact.contact_type)
+ .get()
+ )
+ if isRegistrant:
+ # send update domain only for registant contacts
+ existing_contact.delete()
+ self._add_registrant_to_existing_domain(contact)
+ else:
+ # remove the old contact and add a new one
+ try:
+ self._update_domain_with_contact(contact=existing_contact, rem=True)
+ existing_contact.delete()
+ except Exception as err:
+ logger.error(
+ "Raising error after removing and adding a new contact"
+ )
+ raise (err)
+
+ # update domain with contact or update the contact itself
+ if not isEmptySecurity:
+ if not alreadyExistsInRegistry and not isRegistrant:
+ self._update_domain_with_contact(contact=contact, rem=False)
+ # if already exists just update
+ elif alreadyExistsInRegistry:
+ current_contact = PublicContact.objects.filter(
+ registry_id=contact.registry_id
+ ).get()
+
+ if current_contact.email != contact.email:
+ self._update_epp_contact(contact=contact)
+ else:
+ logger.info("removing security contact and setting default again")
+
+ # get the current contact registry id for security
+ current_contact = PublicContact.objects.filter(
+ registry_id=contact.registry_id
+ ).get()
+
+ # don't let user delete the default without adding a new email
+ if current_contact.email != PublicContact.get_default_security().email:
+ # remove the contact
+ self._update_domain_with_contact(contact=current_contact, rem=True)
+ current_contact.delete()
+ # add new contact
+ security_contact = self.get_default_security_contact()
+ security_contact.save()
@security_contact.setter # type: ignore
def security_contact(self, contact: PublicContact):
- # TODO: replace this with a real implementation
- pass
+ """makes the contact in the registry,
+ for security the public contact should have the org or registrant information
+ from domain information (not domain application)
+ and should have the security email from DomainApplication"""
+ logger.info("making security contact in registry")
+ self._set_singleton_contact(
+ contact, expectedType=contact.ContactTypeChoices.SECURITY
+ )
@Cache
def technical_contact(self) -> PublicContact:
@@ -300,14 +595,24 @@ class Domain(TimeStampedModel, DomainHelper):
@technical_contact.setter # type: ignore
def technical_contact(self, contact: PublicContact):
- raise NotImplementedError()
+ logger.info("making technical contact")
+ self._set_singleton_contact(
+ contact, expectedType=contact.ContactTypeChoices.TECHNICAL
+ )
def is_active(self) -> bool:
- """Is the domain live on the inter webs?"""
- # TODO: implement a check -- should be performant so it can be called for
- # any number of domains on a status page
- # this is NOT as simple as checking if Domain.Status.OK is in self.statuses
- return False
+ """Currently just returns if the state is created,
+ because then it should be live, theoretically.
+ Post mvp this should indicate
+ Is the domain live on the inter webs?
+ could be replaced with request to see if ok status is set
+ """
+ return self.state == self.State.READY
+
+ def delete_request(self):
+ """Delete from host. Possibly a duplicate of _delete_host?"""
+ # TODO fix in ticket #901
+ pass
def transfer(self):
"""Going somewhere. Not implemented."""
@@ -317,17 +622,31 @@ class Domain(TimeStampedModel, DomainHelper):
"""Time to renew. Not implemented."""
raise NotImplementedError()
- @transition(field="state", source=[State.READY], target=State.ONHOLD)
- def place_client_hold(self):
- """This domain should not be active."""
- # This method is changing the state of the domain in registrar
- # TODO: implement EPP call
+ def get_security_email(self):
+ logger.info("get_security_email-> getting the contact ")
+ secContact = self.security_contact
+ return secContact.email
- @transition(field="state", source=[State.ONHOLD], target=State.READY)
- def remove_client_hold(self):
- """This domain is okay to be active."""
- # This method is changing the state of the domain in registrar
- # TODO: implement EPP call
+ def clientHoldStatus(self):
+ return epp.Status(state=self.Status.CLIENT_HOLD, description="", lang="en")
+
+ def _place_client_hold(self):
+ """This domain should not be active.
+ may raises RegistryError, should be caught or handled correctly by caller"""
+ request = commands.UpdateDomain(name=self.name, add=[self.clientHoldStatus()])
+ registry.send(request, cleaned=True)
+
+ def _remove_client_hold(self):
+ """This domain is okay to be active.
+ may raises RegistryError, should be caught or handled correctly by caller"""
+ request = commands.UpdateDomain(name=self.name, rem=[self.clientHoldStatus()])
+ registry.send(request, cleaned=True)
+
+ def _delete_domain(self):
+ """This domain should be deleted from the registry
+ may raises RegistryError, should be caught or handled correctly by caller"""
+ request = commands.DeleteDomain(name=self.name)
+ registry.send(request)
def __str__(self) -> str:
return self.name
@@ -348,9 +667,6 @@ class Domain(TimeStampedModel, DomainHelper):
help_text="Very basic info about the lifecycle of this domain object",
)
- def isActive(self):
- return self.state == Domain.State.CREATED
-
# ForeignKey on UserDomainRole creates a "permissions" member for
# all of the user-roles that are in place for this domain
@@ -391,78 +707,226 @@ class Domain(TimeStampedModel, DomainHelper):
def _get_or_create_domain(self):
"""Try to fetch info about this domain. Create it if it does not exist."""
already_tried_to_create = False
- while True:
+ exitEarly = False
+ count = 0
+ while not exitEarly and count < 3:
try:
+ logger.info("Getting domain info from epp")
req = commands.InfoDomain(name=self.name)
- return registry.send(req, cleaned=True).res_data[0]
+ domainInfo = registry.send(req, cleaned=True).res_data[0]
+ exitEarly = True
+ return domainInfo
except RegistryError as e:
+ count += 1
+
if already_tried_to_create:
+ logger.error("Already tried to create")
+ logger.error(e)
+ logger.error(e.code)
raise e
if e.code == ErrorCode.OBJECT_DOES_NOT_EXIST:
# avoid infinite loop
already_tried_to_create = True
- registrant = self._get_or_create_contact(
- PublicContact.get_default_registrant()
- )
- req = commands.CreateDomain(
- name=self.name,
- registrant=registrant.id,
- auth_info=epp.DomainAuthInfo(
- pw="2fooBAR123fooBaz"
- ), # not a password
- )
- registry.send(req, cleaned=True)
- # no error, so go ahead and update state
- self.state = Domain.State.CREATED
+ self.pendingCreate()
self.save()
else:
+ logger.error(e)
+ logger.error(e.code)
raise e
+ def addRegistrant(self):
+ registrant = PublicContact.get_default_registrant()
+ registrant.domain = self
+ registrant.save() # calls the registrant_contact.setter
+ return registrant.registry_id
+
+ @transition(field="state", source=State.UNKNOWN, target=State.DNS_NEEDED)
+ def pendingCreate(self):
+ logger.info("Changing to dns_needed")
+
+ registrantID = self.addRegistrant()
+
+ req = commands.CreateDomain(
+ name=self.name,
+ registrant=registrantID,
+ auth_info=epp.DomainAuthInfo(pw="2fooBAR123fooBaz"), # not a password
+ )
+
+ try:
+ registry.send(req, cleaned=True)
+
+ except RegistryError as err:
+ if err.code != ErrorCode.OBJECT_EXISTS:
+ raise err
+
+ self.addAllDefaults()
+
+ def addAllDefaults(self):
+ security_contact = self.get_default_security_contact()
+ security_contact.save()
+
+ technical_contact = PublicContact.get_default_technical()
+ technical_contact.domain = self
+ technical_contact.save()
+
+ administrative_contact = PublicContact.get_default_administrative()
+ administrative_contact.domain = self
+ administrative_contact.save()
+
+ @transition(field="state", source=State.READY, target=State.ON_HOLD)
+ def place_client_hold(self):
+ """place a clienthold on a domain (no longer should resolve)"""
+ # TODO - ensure all requirements for client hold are made here
+ # (check prohibited statuses)
+ logger.info("clientHold()-> inside clientHold")
+ self._place_client_hold()
+ # TODO -on the client hold ticket any additional error handling here
+
+ @transition(field="state", source=State.ON_HOLD, target=State.READY)
+ def revert_client_hold(self):
+ """undo a clienthold placed on a domain"""
+
+ logger.info("clientHold()-> inside clientHold")
+ self._remove_client_hold()
+ # TODO -on the client hold ticket any additional error handling here
+
+ @transition(field="state", source=State.ON_HOLD, target=State.DELETED)
+ def deleted(self):
+ """domain is deleted in epp but is saved in our database"""
+ # TODO Domains may not be deleted if:
+ # a child host is being used by
+ # another .gov domains. The host must be first removed
+ # and/or renamed before the parent domain may be deleted.
+ logger.info("pendingCreate()-> inside pending create")
+ self._delete_domain()
+ # TODO - delete ticket any additional error handling here
+
+ @transition(
+ field="state",
+ source=[State.DNS_NEEDED],
+ target=State.READY,
+ )
+ def ready(self):
+ """Transition to the ready state
+ domain should have nameservers and all contacts
+ and now should be considered live on a domain
+ """
+ # TODO - in nameservers tickets 848 and 562
+ # check here if updates need to be made
+ # consider adding these checks as constraints
+ # within the transistion itself
+ nameserverList = self.nameservers
+ logger.info("Changing to ready state")
+ if len(nameserverList) < 2 or len(nameserverList) > 13:
+ raise ValueError("Not ready to become created, cannot transition yet")
+ logger.info("able to transition to ready state")
+
+ def _disclose_fields(self, contact: PublicContact):
+ """creates a disclose object that can be added to a contact Create using
+ .disclose= on the command before sending.
+ if item is security email then make sure email is visable"""
+ isSecurity = contact.contact_type == contact.ContactTypeChoices.SECURITY
+ DF = epp.DiscloseField
+ fields = {DF.FAX, DF.VOICE, DF.ADDR}
+
+ if not isSecurity or (
+ isSecurity and contact.email == PublicContact.get_default_security().email
+ ):
+ fields.add(DF.EMAIL)
+ return epp.Disclose(
+ flag=False,
+ fields=fields,
+ types={DF.ADDR: "loc"},
+ )
+
+ def _make_epp_contact_postal_info(self, contact: PublicContact): # type: ignore
+ return epp.PostalInfo( # type: ignore
+ name=contact.name,
+ addr=epp.ContactAddr(
+ street=[
+ getattr(contact, street)
+ for street in ["street1", "street2", "street3"]
+ if hasattr(contact, street)
+ ], # type: ignore
+ city=contact.city,
+ pc=contact.pc,
+ cc=contact.cc,
+ sp=contact.sp,
+ ),
+ org=contact.org,
+ type="loc",
+ )
+
+ def _make_contact_in_registry(self, contact: PublicContact):
+ """Create the contact in the registry, ignore duplicate contact errors
+ returns int corresponding to ErrorCode values"""
+
+ create = commands.CreateContact(
+ id=contact.registry_id,
+ postal_info=self._make_epp_contact_postal_info(contact=contact),
+ email=contact.email,
+ voice=contact.voice,
+ fax=contact.fax,
+ auth_info=epp.ContactAuthInfo(pw="2fooBAR123fooBaz"),
+ ) # type: ignore
+ # security contacts should only show email addresses, for now
+ create.disclose = self._disclose_fields(contact=contact)
+ try:
+ registry.send(create, cleaned=True)
+ return ErrorCode.COMMAND_COMPLETED_SUCCESSFULLY
+ except RegistryError as err:
+ # don't throw an error if it is just saying this is a duplicate contact
+ if err.code != ErrorCode.OBJECT_EXISTS:
+ logger.error(
+ "Registry threw error for contact id %s"
+ " contact type is %s,"
+ " error code is\n %s"
+ " full error is %s",
+ contact.registry_id,
+ contact.contact_type,
+ err.code,
+ err,
+ )
+ # TODO - 433 Error handling here
+
+ else:
+ logger.warning(
+ "Registrar tried to create duplicate contact for id %s",
+ contact.registry_id,
+ )
+ return err.code
+
+ def _request_contact_info(self, contact: PublicContact):
+ req = commands.InfoContact(id=contact.registry_id)
+ return registry.send(req, cleaned=True).res_data[0]
+
def _get_or_create_contact(self, contact: PublicContact):
"""Try to fetch info about a contact. Create it if it does not exist."""
- while True:
- try:
- req = commands.InfoContact(id=contact.registry_id)
- return registry.send(req, cleaned=True).res_data[0]
- except RegistryError as e:
- if e.code == ErrorCode.OBJECT_DOES_NOT_EXIST:
- create = commands.CreateContact(
- id=contact.registry_id,
- postal_info=epp.PostalInfo( # type: ignore
- name=contact.name,
- addr=epp.ContactAddr(
- street=[
- getattr(contact, street)
- for street in ["street1", "street2", "street3"]
- if hasattr(contact, street)
- ],
- city=contact.city,
- pc=contact.pc,
- cc=contact.cc,
- sp=contact.sp,
- ),
- org=contact.org,
- type="loc",
- ),
- email=contact.email,
- voice=contact.voice,
- fax=contact.fax,
- auth_info=epp.ContactAuthInfo(pw="2fooBAR123fooBaz"),
- )
- # security contacts should only show email addresses, for now
- if (
- contact.contact_type
- == PublicContact.ContactTypeChoices.SECURITY
- ):
- DF = epp.DiscloseField
- create.disclose = epp.Disclose(
- flag=False,
- fields={DF.FAX, DF.VOICE, DF.ADDR},
- types={DF.ADDR: "loc"},
- )
- registry.send(create)
- else:
- raise e
+
+ try:
+ return self._request_contact_info(contact)
+
+ except RegistryError as e:
+ if e.code == ErrorCode.OBJECT_DOES_NOT_EXIST:
+ logger.info(
+ "_get_or_create_contact()-> contact doesn't exist so making it"
+ )
+ contact.domain = self
+ contact.save() # this will call the function based on type of contact
+ return self._request_contact_info(contact=contact)
+ else:
+ logger.error(
+ "Registry threw error for contact id %s"
+ " contact type is %s,"
+ " error code is\n %s"
+ " full error is %s",
+ contact.registry_id,
+ contact.contact_type,
+ e.code,
+ e,
+ )
+
+ raise e
def _update_or_create_host(self, host):
raise NotImplementedError()
@@ -493,25 +957,33 @@ class Domain(TimeStampedModel, DomainHelper):
# remove null properties (to distinguish between "a value of None" and null)
cleaned = {k: v for k, v in cache.items() if v is not ...}
+ # statuses can just be a list no need to keep the epp object
+ if "statuses" in cleaned.keys():
+ cleaned["statuses"] = [status.state for status in cleaned["statuses"]]
# get contact info, if there are any
if (
- fetch_contacts
- and "_contacts" in cleaned
+ # fetch_contacts and
+ "_contacts" in cleaned
and isinstance(cleaned["_contacts"], list)
and len(cleaned["_contacts"])
):
cleaned["contacts"] = []
- for id in cleaned["_contacts"]:
+ for domainContact in cleaned["_contacts"]:
# we do not use _get_or_create_* because we expect the object we
# just asked the registry for still exists --
# if not, that's a problem
- req = commands.InfoContact(id=id)
+
+ # TODO- discuss-should we check if contact is in public contacts
+ # and add it if not- this is really to keep in mine the transisiton
+ req = commands.InfoContact(id=domainContact.contact)
data = registry.send(req, cleaned=True).res_data[0]
# extract properties from response
# (Ellipsis is used to mean "null")
+ # convert this to use PublicContactInstead
contact = {
- "id": id,
+ "id": domainContact.contact,
+ "type": domainContact.type,
"auth_info": getattr(data, "auth_info", ...),
"cr_date": getattr(data, "cr_date", ...),
"disclose": getattr(data, "disclose", ...),
@@ -530,11 +1002,13 @@ class Domain(TimeStampedModel, DomainHelper):
# get nameserver info, if there are any
if (
- fetch_hosts
- and "_hosts" in cleaned
+ # fetch_hosts and
+ "_hosts" in cleaned
and isinstance(cleaned["_hosts"], list)
and len(cleaned["_hosts"])
):
+ # TODO- add elif in cache set it to be the old cache value
+ # no point in removing
cleaned["hosts"] = []
for name in cleaned["_hosts"]:
# we do not use _get_or_create_* because we expect the object we
diff --git a/src/registrar/models/domain_application.py b/src/registrar/models/domain_application.py
index b1230b703..7df51baf4 100644
--- a/src/registrar/models/domain_application.py
+++ b/src/registrar/models/domain_application.py
@@ -378,16 +378,10 @@ class DomainApplication(TimeStampedModel):
help_text="Urbanization (Puerto Rico only)",
)
- type_of_work = models.TextField(
+ about_your_organization = models.TextField(
null=True,
blank=True,
- help_text="Type of work of the organization",
- )
-
- more_organization_information = models.TextField(
- null=True,
- blank=True,
- help_text="More information about your organization",
+ help_text="Information about your organization",
)
authorizing_official = models.ForeignKey(
@@ -411,7 +405,7 @@ class DomainApplication(TimeStampedModel):
blank=True,
help_text="The approved domain",
related_name="domain_application",
- on_delete=models.PROTECT,
+ on_delete=models.SET_NULL,
)
requested_domain = models.OneToOneField(
@@ -477,6 +471,11 @@ class DomainApplication(TimeStampedModel):
except Exception:
return ""
+ def domain_is_not_active(self):
+ if self.approved_domain:
+ return not self.approved_domain.is_active()
+ return True
+
def _send_status_update_email(
self, new_status, email_template, email_template_subject
):
@@ -600,11 +599,22 @@ class DomainApplication(TimeStampedModel):
"emails/domain_request_withdrawn_subject.txt",
)
- @transition(field="status", source=[IN_REVIEW, APPROVED], target=REJECTED)
+ @transition(
+ field="status",
+ source=[IN_REVIEW, APPROVED],
+ target=REJECTED,
+ conditions=[domain_is_not_active],
+ )
def reject(self):
"""Reject an application that has been submitted.
- As a side effect, an email notification is sent, similar to in_review"""
+ As side effects this will delete the domain and domain_information
+ (will cascade), and send an email notification."""
+
+ if self.status == self.APPROVED:
+ self.approved_domain.delete_request()
+ self.approved_domain.delete()
+ self.approved_domain = None
self._send_status_update_email(
"action needed",
@@ -612,14 +622,25 @@ class DomainApplication(TimeStampedModel):
"emails/status_change_rejected_subject.txt",
)
- @transition(field="status", source=[IN_REVIEW, APPROVED], target=INELIGIBLE)
+ @transition(
+ field="status",
+ source=[IN_REVIEW, APPROVED],
+ target=INELIGIBLE,
+ conditions=[domain_is_not_active],
+ )
def reject_with_prejudice(self):
"""The applicant is a bad actor, reject with prejudice.
No email As a side effect, but we block the applicant from editing
any existing domains/applications and from submitting new aplications.
We do this by setting an ineligible status on the user, which the
- permissions classes test against"""
+ permissions classes test against. This will also delete the domain
+ and domain_information (will cascade) when they exist."""
+
+ if self.status == self.APPROVED:
+ self.approved_domain.delete_request()
+ self.approved_domain.delete()
+ self.approved_domain = None
self.creator.restrict_user()
@@ -653,7 +674,7 @@ class DomainApplication(TimeStampedModel):
]
return bool(user_choice and user_choice not in excluded)
- def show_type_of_work(self) -> bool:
+ def show_about_your_organization(self) -> bool:
"""Show this step if this is a special district or interstate."""
user_choice = self.organization_type
return user_choice in [
diff --git a/src/registrar/models/domain_information.py b/src/registrar/models/domain_information.py
index b12039e73..3b93aff48 100644
--- a/src/registrar/models/domain_information.py
+++ b/src/registrar/models/domain_information.py
@@ -13,7 +13,7 @@ logger = logging.getLogger(__name__)
class DomainInformation(TimeStampedModel):
"""A registrant's domain information for that domain, exported from
- DomainApplication. We use these field from DomainApplication with few exceptation
+ DomainApplication. We use these field from DomainApplication with few exceptions
which are 'removed' via pop at the bottom of this file. Most of design for domain
management's user information are based on application, but we cannot change
the application once approved, so copying them that way we can make changes
@@ -134,16 +134,10 @@ class DomainInformation(TimeStampedModel):
verbose_name="Urbanization (Puerto Rico only)",
)
- type_of_work = models.TextField(
+ about_your_organization = models.TextField(
null=True,
blank=True,
- help_text="Type of work of the organization",
- )
-
- more_organization_information = models.TextField(
- null=True,
- blank=True,
- help_text="Further information about the government organization",
+ help_text="Information about your organization",
)
authorizing_official = models.ForeignKey(
@@ -156,7 +150,7 @@ class DomainInformation(TimeStampedModel):
domain = models.OneToOneField(
"registrar.Domain",
- on_delete=models.PROTECT,
+ on_delete=models.CASCADE,
blank=True,
null=True,
# Access this information via Domain as "domain.domain_info"
diff --git a/src/registrar/models/public_contact.py b/src/registrar/models/public_contact.py
index cfed96205..d9ddecad4 100644
--- a/src/registrar/models/public_contact.py
+++ b/src/registrar/models/public_contact.py
@@ -23,8 +23,8 @@ class PublicContact(TimeStampedModel):
"""These are the types of contacts accepted by the registry."""
REGISTRANT = "registrant", "Registrant"
- ADMINISTRATIVE = "administrative", "Administrative"
- TECHNICAL = "technical", "Technical"
+ ADMINISTRATIVE = "admin", "Administrative"
+ TECHNICAL = "tech", "Technical"
SECURITY = "security", "Security"
def save(self, *args, **kwargs):
@@ -149,4 +149,8 @@ class PublicContact(TimeStampedModel):
)
def __str__(self):
- return f"{self.name} <{self.email}>"
+ return (
+ f"{self.name} <{self.email}>"
+ f"id: {self.registry_id} "
+ f"type: {self.contact_type}"
+ )
diff --git a/src/registrar/models/user.py b/src/registrar/models/user.py
index 5cf1dd71f..5b04c628d 100644
--- a/src/registrar/models/user.py
+++ b/src/registrar/models/user.py
@@ -45,7 +45,7 @@ class User(AbstractUser):
def __str__(self):
# this info is pulled from Login.gov
if self.first_name or self.last_name:
- return f"{self.first_name or ''} {self.last_name or ''}"
+ return f"{self.first_name or ''} {self.last_name or ''} {self.email or ''}"
elif self.email:
return self.email
else:
diff --git a/src/registrar/templates/admin/app_list.html b/src/registrar/templates/admin/app_list.html
index 1c7f6007f..49df75beb 100644
--- a/src/registrar/templates/admin/app_list.html
+++ b/src/registrar/templates/admin/app_list.html
@@ -6,23 +6,28 @@