-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathdomain.py
More file actions
1416 lines (1150 loc) · 54 KB
/
Copy pathdomain.py
File metadata and controls
1416 lines (1150 loc) · 54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from datetime import date
import logging
from contextvars import ContextVar
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render, get_object_or_404
from django.urls import reverse
from django.views.generic import DeleteView, DetailView, UpdateView
from django.views.generic.edit import FormMixin
from django.conf import settings
from registrar.utility.errors import APIError, RegistrySystemError
from registrar.decorators import (
HAS_PORTFOLIO_DOMAINS_VIEW_ALL,
IS_DOMAIN_MANAGER,
IS_DOMAIN_MANAGER_AND_NOT_PORTFOLIO_MEMBER,
IS_PORTFOLIO_MEMBER_AND_DOMAIN_MANAGER,
IS_STAFF,
IS_STAFF_MANAGING_DOMAIN,
grant_access,
)
from registrar.forms.domain import DomainSuborganizationForm, DomainRenewalForm
from registrar.models import (
Domain,
DomainRequest,
DomainInformation,
DomainInvitation,
PortfolioInvitation,
UserDomainRole,
PublicContact,
)
from registrar.models.user_portfolio_permission import UserPortfolioPermission
from registrar.models.utility.portfolio_helper import UserPortfolioRoleChoices
from registrar.utility.enums import DefaultEmail
from registrar.utility.errors import (
GenericError,
GenericErrorCodes,
NameserverError,
NameserverErrorCodes as nsErrorCodes,
DsDataError,
DsDataErrorCodes,
SecurityEmailError,
SecurityEmailErrorCodes,
)
from registrar.models.utility.contact_error import ContactError
from registrar.utility.waffle import flag_is_active_for_user
from registrar.views.utility.invitation_helper import (
get_org_membership,
get_requested_user,
handle_invitation_exceptions,
)
from registrar.services.dns_host_service import DnsHostService
from ..forms import (
SeniorOfficialContactForm,
DomainOrgNameAddressForm,
DomainAddUserForm,
DomainSecurityEmailForm,
NameserverFormset,
DomainDnssecForm,
DomainDsdataFormset,
DomainDsdataForm,
)
from epplibwrapper import (
common,
extensions,
RegistryError,
)
from ..utility.email import send_templated_email, EmailSendingError
from ..utility.email_invitations import (
send_domain_invitation_email,
send_domain_manager_removal_emails_to_domain_managers,
send_portfolio_invitation_email,
)
from django import forms
logger = logging.getLogger(__name__)
context_dns_record = ContextVar("context_dns_record", default=None)
class DomainBaseView(PermissionRequiredMixin, DetailView):
"""
Base View for the Domain. Handles getting and setting the domain
in session cache on GETs. Also provides methods for getting
and setting the domain in cache
"""
model = Domain
pk_url_kwarg = "domain_pk"
context_object_name = "domain"
def get(self, request, *args, **kwargs):
self._get_domain(request)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
def _get_domain(self, request):
"""
get domain from session cache or from db and set
to self.object
set session to self for downstream functions to
update session cache
"""
self.session = request.session
# domain:private_key is the session key to use for
# caching the domain in the session
domain_pk = "domain:" + str(self.kwargs.get("domain_pk"))
cached_domain = self.session.get(domain_pk)
if cached_domain:
self.object = cached_domain
else:
self.object = self.get_object()
self._update_session_with_domain()
def _update_session_with_domain(self):
"""
update domain in the session cache
"""
domain_pk = "domain:" + str(self.kwargs.get("domain_pk"))
self.session[domain_pk] = self.object
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = self.request.user
context["is_analyst_or_superuser"] = user.has_perm("registrar.analyst_access_permission") or user.has_perm(
"registrar.full_access_permission"
)
context["is_domain_manager"] = UserDomainRole.objects.filter(user=user, domain=self.object).exists()
context["is_portfolio_user"] = self.can_access_domain_via_portfolio(self.object.pk)
context["is_editable"] = self.is_editable()
# Stored in a variable for the linter
action = "analyst_action"
action_location = "analyst_action_location"
# Flag to see if an analyst is attempting to make edits
if action in self.request.session:
context[action] = self.request.session[action]
if action_location in self.request.session:
context[action_location] = self.request.session[action_location]
return context
def is_editable(self):
"""Returns whether domain is editable in the context of the view"""
domain_editable = self.object.is_editable()
if not domain_editable:
return False
# if user is domain manager or analyst or admin, return True
if (
self.can_access_other_user_domains(self.object.id)
or UserDomainRole.objects.filter(user=self.request.user, domain=self.object).exists()
):
return True
return False
def can_access_domain_via_portfolio(self, pk):
"""Most views should not allow permission to portfolio users.
If particular views allow access to the domain pages, they will need to override
this function.
"""
return False
def has_permission(self):
"""Check if this user has access to this domain.
The user is in self.request.user and the domain needs to be looked
up from the domain's primary key in self.kwargs["domain_pk"]
"""
pk = self.kwargs["domain_pk"]
# test if domain in editable state
if not self.in_editable_state(pk):
return False
# if we need to check more about the nature of role, do it here.
return True
def in_editable_state(self, pk):
"""Is the domain in an editable state"""
requested_domain = None
if Domain.objects.filter(id=pk).exists():
requested_domain = Domain.objects.get(id=pk)
# if domain is editable return true
if requested_domain and requested_domain.is_editable():
return True
return False
def can_access_other_user_domains(self, pk):
"""Checks to see if an authorized user (staff or superuser)
can access a domain that they did not create or was invited to.
"""
# Check if the user is permissioned...
user_is_analyst_or_superuser = self.request.user.has_perm(
"registrar.analyst_access_permission"
) or self.request.user.has_perm("registrar.full_access_permission")
if not user_is_analyst_or_superuser:
return False
# Check if the user is attempting a valid edit action.
# In other words, if the analyst/admin did not click
# the 'Manage Domain' button in /admin,
# then they cannot access this page.
session = self.request.session
can_do_action = (
"analyst_action" in session
and "analyst_action_location" in session
and session["analyst_action_location"] == pk
)
if not can_do_action:
return False
# Analysts may manage domains, when they are in these statuses:
valid_domain_statuses = [
DomainRequest.DomainRequestStatus.APPROVED,
DomainRequest.DomainRequestStatus.IN_REVIEW,
DomainRequest.DomainRequestStatus.REJECTED,
DomainRequest.DomainRequestStatus.ACTION_NEEDED,
# Edge case - some domains do not have
# a status or DomainInformation... aka a status of 'None'.
# It is necessary to access those to correct errors.
None,
]
requested_domain = None
if DomainInformation.objects.filter(id=pk).exists():
requested_domain = DomainInformation.objects.get(id=pk)
# if no domain information or domain request exist, the user
# should be able to manage the domain; however, if domain information
# and domain request exist, and domain request is not in valid status,
# user should not be able to manage domain
if (
requested_domain
and requested_domain.domain_request
and requested_domain.domain_request.status not in valid_domain_statuses
):
return False
# Valid session keys exist,
# the user is permissioned,
# and it is in a valid status
return True
class DomainFormBaseView(DomainBaseView, FormMixin):
"""
Form Base View for the Domain. Handles getting and setting
domain in cache when dealing with domain forms. Provides
implementations of post, form_valid and form_invalid.
"""
def post(self, request, *args, **kwargs):
"""Form submission posts to this view.
This post method harmonizes using DomainBaseView and FormMixin
"""
self._get_domain(request)
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
# updates session cache with domain
self._update_session_with_domain()
# superclass has the redirect
return super().form_valid(form)
def form_invalid(self, form):
# updates session cache with domain
self._update_session_with_domain()
# superclass has the redirect
return super().form_invalid(form)
def get_domain_info_from_domain(self) -> DomainInformation | None:
"""
Grabs the underlying domain_info object based off of self.object.name.
Returns None if nothing is found.
"""
_domain_info = DomainInformation.objects.filter(domain__name=self.object.name)
current_domain_info = None
if _domain_info.exists() and _domain_info.count() == 1:
current_domain_info = _domain_info.get()
else:
logger.error("Could get domain_info. No domain info exists, or duplicates exist.")
return current_domain_info
def send_update_notification(self, form, force_send=False):
"""Send a notification to all domain managers that an update has occured
for a single domain. Uses update_to_approved_domain.txt template.
If there are no changes to the form, emails will NOT be sent unless force_send
is set to True.
"""
# send notification email for changes to any of these forms
form_label_dict = {
DomainSecurityEmailForm: "Security email",
DomainDnssecForm: "DNSSEC / DS Data",
DomainDsdataFormset: "DNSSEC / DS Data",
DomainOrgNameAddressForm: "Organization details",
SeniorOfficialContactForm: "Senior official",
NameserverFormset: "Name servers",
}
# forms of these types should not send notifications if they're part of a portfolio/Organization
check_for_portfolio = {
DomainOrgNameAddressForm,
SeniorOfficialContactForm,
}
is_analyst_action = "analyst_action" in self.session and "analyst_action_location" in self.session
should_notify = False
if form.__class__ in form_label_dict:
if is_analyst_action:
logger.debug("No notification sent: Action was conducted by an analyst")
else:
# these types of forms can cause notifications
should_notify = True
if form.__class__ in check_for_portfolio:
# some forms shouldn't cause notifications if they are in a portfolio
info = self.get_domain_info_from_domain()
is_org_user = self.request.user.is_org_user(self.request)
if is_org_user and (not info or info.portfolio):
logger.debug("No notification sent: Domain is part of a portfolio")
should_notify = False
else:
# don't notify for any other types of forms
should_notify = False
if should_notify and (form.has_changed() or force_send):
context = {
"domain": self.object.name,
"user": self.request.user,
"date": date.today(),
"changes": form_label_dict[form.__class__],
}
self.email_domain_managers(
self.object,
"emails/update_to_approved_domain.txt",
"emails/update_to_approved_domain_subject.txt",
context,
)
else:
logger.info(f"No notification sent for {form.__class__}.")
def email_domain_managers(self, domain: Domain, template: str, subject_template: str, context={}):
"""Send a single email built from a template to all managers for a given domain.
template_name and subject_template_name are relative to the same template
context as Django's HTML templates. context gives additional information
that the template may use.
context is a dictionary containing any information needed to fill in values
in the provided template, exactly the same as with send_templated_email.
Will log a warning if the email fails to send for any reason, but will not raise an error.
"""
manager_roles = UserDomainRole.objects.filter(domain=domain.pk, role=UserDomainRole.Roles.MANAGER)
for role in manager_roles:
manager = role.user
context["recipient"] = manager
try:
send_templated_email(template, subject_template, to_addresses=[manager.email], context=context)
except EmailSendingError as err:
logger.error(
"Failed to send notification email:\n"
f" Subject template: {subject_template}\n"
f" To: {manager.email}\n"
f" Domain: {domain.name}\n"
f" Error: {err}",
exc_info=True,
)
@grant_access(IS_DOMAIN_MANAGER, IS_STAFF_MANAGING_DOMAIN, HAS_PORTFOLIO_DOMAINS_VIEW_ALL)
class DomainView(DomainBaseView):
"""Domain detail overview page"""
template_name = "domain_detail.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
default_emails = DefaultEmail.get_all_emails()
context["hidden_security_emails"] = default_emails
context["user_portfolio_permission"] = UserPortfolioPermission.objects.filter(
user=self.request.user, portfolio=self.request.session.get("portfolio")
).first()
security_email = self.object.get_security_email()
if security_email is None or security_email in default_emails:
context["security_email"] = None
return context
context["security_email"] = security_email
return context
def can_access_domain_via_portfolio(self, pk):
"""Most views should not allow permission to portfolio users.
If particular views allow permissions, they will need to override
this function."""
portfolio = self.request.session.get("portfolio")
if self.request.user.has_any_domains_portfolio_permission(portfolio):
if Domain.objects.filter(id=pk).exists():
domain = Domain.objects.get(id=pk)
if domain.domain_info.portfolio == portfolio:
return True
return False
def in_editable_state(self, pk):
"""Override in_editable_state from DomainPermission
Allow detail page to be viewable"""
requested_domain = None
if Domain.objects.filter(id=pk).exists():
requested_domain = Domain.objects.get(id=pk)
# return true if the domain exists, this will allow the detail page to load
if requested_domain:
return True
return False
def _get_domain(self, request):
"""
override get_domain for this view so that domain overview
always resets the cache for the domain object
"""
self.session = request.session
self.object = self.get_object()
self._update_session_with_domain()
@grant_access(IS_DOMAIN_MANAGER, IS_STAFF_MANAGING_DOMAIN)
class DomainRenewalView(DomainBaseView):
"""Domain detail overview page."""
template_name = "domain_renewal.html"
def get_context_data(self, **kwargs):
"""Grabs the security email information and adds security_email to the renewal form context
sets it to None if it uses a default email"""
context = super().get_context_data(**kwargs)
default_emails = DefaultEmail.get_all_emails()
context["hidden_security_emails"] = default_emails
security_email = self.object.get_security_email()
context["security_email"] = security_email
return context
def in_editable_state(self, pk):
"""Override in_editable_state from DomainPermission
Allow renewal form to be accessed
returns boolean"""
requested_domain = None
if Domain.objects.filter(id=pk).exists():
requested_domain = Domain.objects.get(id=pk)
return (
requested_domain
and requested_domain.is_editable()
and (requested_domain.is_expiring() or requested_domain.is_expired())
)
def post(self, request, domain_pk):
domain = get_object_or_404(Domain, id=domain_pk)
form = DomainRenewalForm(request.POST)
if form.is_valid():
# check for key in the post request data
if "submit_button" in request.POST:
try:
domain.renew_domain()
messages.success(request, "This domain has been renewed for one year.")
except Exception:
messages.error(
request,
"This domain has not been renewed for one year, "
"please email help@get.gov if this problem persists.",
)
return HttpResponseRedirect(reverse("domain", kwargs={"domain_pk": domain_pk}))
# if not valid, render the template with error messages
# passing editable and is_editable for re-render
return render(
request,
"domain_renewal.html",
{
"domain": domain,
"form": form,
"is_editable": True,
"is_domain_manager": True,
},
)
@grant_access(IS_DOMAIN_MANAGER, IS_STAFF_MANAGING_DOMAIN)
class DomainOrgNameAddressView(DomainFormBaseView):
"""Organization view"""
model = Domain
template_name = "domain_org_name_address.html"
context_object_name = "domain"
form_class = DomainOrgNameAddressForm
def get_form_kwargs(self, *args, **kwargs):
"""Add domain_info.organization_name instance to make a bound form."""
form_kwargs = super().get_form_kwargs(*args, **kwargs)
form_kwargs["instance"] = self.object.domain_info
return form_kwargs
def get_success_url(self):
"""Redirect to the overview page for the domain."""
return reverse("domain-org-name-address", kwargs={"domain_pk": self.object.pk})
def form_valid(self, form):
"""The form is valid, save the organization name and mailing address."""
self.send_update_notification(form)
form.save()
messages.success(self.request, "The organization information for this domain has been updated.")
# superclass has the redirect
return super().form_valid(form)
def has_permission(self):
"""Override for the has_permission class to exclude portfolio users"""
# Org users shouldn't have access to this page
is_org_user = self.request.user.is_org_user(self.request)
portfolio = self.request.session.get("portfolio")
if portfolio and is_org_user:
return False
else:
return super().has_permission()
@grant_access(IS_PORTFOLIO_MEMBER_AND_DOMAIN_MANAGER, IS_STAFF_MANAGING_DOMAIN)
class DomainSubOrganizationView(DomainFormBaseView):
"""Suborganization view"""
model = Domain
template_name = "domain_suborganization.html"
context_object_name = "domain"
form_class = DomainSuborganizationForm
def has_permission(self):
"""Override for the has_permission class to exclude non-portfolio users"""
# non-org users shouldn't have access to this page
is_org_user = self.request.user.is_org_user(self.request)
portfolio = self.request.session.get("portfolio")
if portfolio and is_org_user:
return super().has_permission()
else:
return False
def get_context_data(self, **kwargs):
"""Adds custom context."""
context = super().get_context_data(**kwargs)
if self.object and self.object.domain_info and self.object.domain_info.sub_organization:
context["suborganization_name"] = self.object.domain_info.sub_organization.name
return context
def get_form_kwargs(self, *args, **kwargs):
"""Add domain_info.organization_name instance to make a bound form."""
form_kwargs = super().get_form_kwargs(*args, **kwargs)
form_kwargs["instance"] = self.object.domain_info
return form_kwargs
def get_success_url(self):
"""Redirect to the overview page for the domain."""
return reverse("domain-suborganization", kwargs={"domain_pk": self.object.pk})
def form_valid(self, form):
"""The form is valid, save the organization name and mailing address."""
form.save()
messages.success(self.request, "The suborganization name for this domain has been updated.")
# superclass has the redirect
return super().form_valid(form)
@grant_access(IS_DOMAIN_MANAGER_AND_NOT_PORTFOLIO_MEMBER, IS_STAFF_MANAGING_DOMAIN)
class DomainSeniorOfficialView(DomainFormBaseView):
"""Domain senior official editing view."""
model = Domain
template_name = "domain_senior_official.html"
context_object_name = "domain"
form_class = SeniorOfficialContactForm
def get_form_kwargs(self, *args, **kwargs):
"""Add domain_info.senior_official instance to make a bound form."""
form_kwargs = super().get_form_kwargs(*args, **kwargs)
form_kwargs["instance"] = self.object.domain_info.senior_official
domain_info = self.get_domain_info_from_domain()
invalid_fields = [DomainRequest.OrganizationChoices.FEDERAL, DomainRequest.OrganizationChoices.TRIBAL]
is_federal_or_tribal = domain_info and (domain_info.generic_org_type in invalid_fields)
form_kwargs["disable_fields"] = is_federal_or_tribal
return form_kwargs
def get_context_data(self, **kwargs):
"""Adds custom context."""
context = super().get_context_data(**kwargs)
context["generic_org_type"] = self.object.domain_info.generic_org_type
return context
def get_success_url(self):
"""Redirect to the overview page for the domain."""
return reverse("domain-senior-official", kwargs={"domain_pk": self.object.pk})
def form_valid(self, form):
"""The form is valid, save the senior official."""
# Set the domain information in the form so that it can be accessible
# to associate a new Contact, if a new Contact is needed
# in the save() method
form.set_domain_info(self.object.domain_info)
form.save()
self.send_update_notification(form)
messages.success(self.request, "The senior official for this domain has been updated.")
# superclass has the redirect
return super().form_valid(form)
def has_permission(self):
"""Override for the has_permission class to exclude portfolio users"""
# Org users shouldn't have access to this page
is_org_user = self.request.user.is_org_user(self.request)
portfolio = self.request.session.get("portfolio")
if portfolio and is_org_user:
return False
else:
return super().has_permission()
@grant_access(IS_DOMAIN_MANAGER, IS_STAFF_MANAGING_DOMAIN)
class DomainDNSView(DomainBaseView):
"""DNS Information View."""
template_name = "domain_dns.html"
valid_domains = ["igorville.gov", "domainops.gov"]
def get_context_data(self, **kwargs):
"""Adds custom context."""
context = super().get_context_data(**kwargs)
context["dns_prototype_flag"] = flag_is_active_for_user(self.request.user, "dns_prototype_flag")
context["is_valid_domain"] = self.object.name in self.valid_domains
return context
class PrototypeDomainDNSRecordForm(forms.Form):
"""Form for adding DNS records in prototype."""
name = forms.CharField(label="DNS record name (A record)", required=True, help_text="DNS record name")
content = forms.GenericIPAddressField(
label="IPv4 Address",
required=True,
protocol="IPv4",
)
ttl = forms.ChoiceField(
label="TTL",
choices=[
(1, "Automatic"),
(60, "1 minute"),
(300, "5 minutes"),
(1800, "30 minutes"),
(3600, "1 hour"),
(7200, "2 hours"),
(18000, "5 hours"),
(43200, "12 hours"),
(86400, "1 day"),
],
initial=1,
)
@grant_access(IS_STAFF)
class PrototypeDomainDNSRecordView(DomainFormBaseView):
template_name = "prototype_domain_dns.html"
form_class = PrototypeDomainDNSRecordForm
valid_domains = ["igorville.gov", "domainops.gov", "dns.gov"]
dns_host_service = DnsHostService()
def __init__(self):
self.dns_record = None
def get_context_data(self, **kwargs):
"""Adds custom context."""
context = super().get_context_data(**kwargs)
context["dns_record"] = context_dns_record.get()
return context
def has_permission(self):
has_permission = super().has_permission()
if not has_permission:
return False
flag_enabled = flag_is_active_for_user(self.request.user, "dns_prototype_flag")
if not flag_enabled:
return False
self.object = self.get_object()
if self.object.name not in self.valid_domains:
return False
return True
def get_success_url(self):
return reverse("prototype-domain-dns", kwargs={"domain_pk": self.object.pk})
def find_by_name(self, items, name):
"""Find an item by name in a list of dictionaries."""
return next((item.get("id") for item in items if item.get("name") == name), None)
def post(self, request, *args, **kwargs): # noqa: C901
"""Handle form submission."""
self.object = self.get_object()
form = self.get_form()
errors = []
if form.is_valid():
try:
if settings.IS_PRODUCTION and self.object.name != "igorville.gov":
raise Exception(f"create dns record was called for domain {self.name}")
if not settings.IS_PRODUCTION and self.object.name not in self.valid_domains:
raise Exception(
f"Can only create DNS records for: {self.valid_domains}."
" Create one in a test environment if it doesn't already exist."
)
record_data = {
"type": "A",
"name": form.cleaned_data["name"], # record name
"content": form.cleaned_data["content"], # IPv4
"ttl": int(form.cleaned_data["ttl"]),
"comment": "Test record",
}
account_name = f"account-{self.object.name}"
zone_name = f"{self.object.name}" # must be a domain name
zone_id = ""
try:
_, zone_id, nameservers = self.dns_host_service.dns_setup(account_name, zone_name)
except APIError as e:
logger.error(f"API error in view: {str(e)}")
if zone_id:
# post nameservers to registry
try:
self._register_nameservers(zone_name, nameservers)
except RegistrySystemError as e:
logger.error(f"Unable to register nameservers {e}")
try:
record_response = self.dns_host_service.create_record(zone_id, record_data)
logger.info(f"Created DNS record: {record_response['result']}")
self.dns_record = record_response["result"]
dns_name = record_response["result"]["name"]
messages.success(request, f"DNS A record '{dns_name}' created successfully.")
except APIError as e:
logger.error(f"API error in view: {str(e)}")
context_dns_record.set(self.dns_record)
finally:
if errors:
messages.error(request, f"Request errors: {errors}")
return super().post(request)
@grant_access(IS_DOMAIN_MANAGER, IS_STAFF_MANAGING_DOMAIN)
class DomainNameserversView(DomainFormBaseView):
"""Domain nameserver editing view."""
template_name = "domain_nameservers.html"
form_class = NameserverFormset
model = Domain
def get_initial(self):
"""The initial value for the form (which is a formset here)."""
nameservers = self.object.nameservers
initial_data = []
if nameservers is not None:
# Add existing nameservers as initial data
initial_data.extend({"server": name, "ip": ",".join(ip)} for name, ip in nameservers)
# Ensure 2 fields in the case we have no data
if len(initial_data) == 0:
initial_data.append({})
return initial_data
def get_success_url(self):
"""Redirect to the nameservers page for the domain."""
return reverse("domain-dns-nameservers", kwargs={"domain_pk": self.object.pk})
def get_context_data(self, **kwargs):
"""Adjust context from FormMixin for formsets."""
context = super().get_context_data(**kwargs)
# use "formset" instead of "form" for the key
context["formset"] = context.pop("form")
return context
def get_form(self, **kwargs):
"""Override the labels and required fields every time we get a formset."""
formset = super().get_form(**kwargs)
for i, form in enumerate(formset):
form.fields["server"].label += f" {i+1}"
form.fields["domain"].initial = self.object.name
return formset
def post(self, request, *args, **kwargs):
"""Form submission posts to this view.
This post method harmonizes using DomainBaseView and FormMixin
"""
self._get_domain(request)
formset = self.get_form()
if "btn-cancel-click" in request.POST:
url = self.get_success_url()
return HttpResponseRedirect(url)
if formset.is_valid():
logger.debug("formset is valid")
return self.form_valid(formset)
else:
logger.debug("formset is invalid")
logger.debug(formset.errors)
return self.form_invalid(formset)
def form_valid(self, formset):
"""The formset is valid, perform something with it."""
self.request.session["nameservers_form_domain"] = self.object
initial_state = self.object.state
# Set the nameservers from the formset
nameservers = []
for form in formset:
try:
ip_string = form.cleaned_data["ip"]
# ip_string will be None or a string of IP addresses
# comma-separated
ip_list = []
if ip_string:
# Split the string into a list using a comma as the delimiter
ip_list = ip_string.split(",")
as_tuple = (
form.cleaned_data["server"],
ip_list,
)
nameservers.append(as_tuple)
except KeyError:
# no server information in this field, skip it
pass
try:
self.object.nameservers = nameservers
except NameserverError as Err:
# NamserverErrors *should* be caught in form; if reached here,
# there was an uncaught error in submission (through EPP)
messages.error(self.request, NameserverError(code=nsErrorCodes.BAD_DATA))
logger.error(f"Nameservers error: {Err}")
# TODO: registry is not throwing an error when no connection
except RegistryError as Err:
if Err.is_connection_error():
messages.error(
self.request,
GenericError(code=GenericErrorCodes.CANNOT_CONTACT_REGISTRY),
)
logger.error(f"Registry connection error: {Err}")
else:
messages.error(self.request, NameserverError(code=nsErrorCodes.BAD_DATA))
logger.error(f"Registry error: {Err}")
else:
if initial_state == Domain.State.READY:
self.send_update_notification(formset)
messages.success(
self.request,
"The name servers for this domain have been updated. "
"Note that DNS changes could take anywhere from a few minutes to "
"48 hours to propagate across the internet.",
)
# superclass has the redirect
return super().form_valid(formset)
@grant_access(IS_DOMAIN_MANAGER, IS_STAFF_MANAGING_DOMAIN)
class DomainDNSSECView(DomainFormBaseView):
"""Domain DNSSEC editing view."""
template_name = "domain_dnssec.html"
form_class = DomainDnssecForm
def get_context_data(self, **kwargs):
"""The initial value for the form (which is a formset here)."""
context = super().get_context_data(**kwargs)
has_dnssec_records = self.object.dnssecdata is not None
context["has_dnssec_records"] = has_dnssec_records
context["dnssec_enabled"] = self.request.session.pop("dnssec_enabled", False)
return context
def get_success_url(self):
"""Redirect to the DNSSEC page for the domain."""
return reverse("domain-dns-dnssec", kwargs={"domain_pk": self.object.pk})
def post(self, request, *args, **kwargs):
"""Form submission posts to this view."""
self._get_domain(request)
form = self.get_form()
if form.is_valid():
if "disable_dnssec" in request.POST:
try:
self.object.dnssecdata = {}
except RegistryError as err:
errmsg = "Error removing existing DNSSEC record(s)."
logger.error(errmsg + ": " + err)
messages.error(self.request, errmsg)
else:
self.send_update_notification(form, force_send=True)
return self.form_valid(form)
@grant_access(IS_DOMAIN_MANAGER, IS_STAFF_MANAGING_DOMAIN)
class DomainDsDataView(DomainFormBaseView):
"""Domain DNSSEC ds data editing view."""
template_name = "domain_dsdata.html"
form_class = DomainDsdataFormset
form = DomainDsdataForm
def get_initial(self):
"""The initial value for the form (which is a formset here)."""
dnssecdata: extensions.DNSSECExtension = self.object.dnssecdata
initial_data = []
if dnssecdata is not None and dnssecdata.dsData is not None:
# Add existing nameservers as initial data
initial_data.extend(
{
"key_tag": record.keyTag,
"algorithm": record.alg,
"digest_type": record.digestType,
"digest": record.digest,
}
for record in dnssecdata.dsData
)
return initial_data
def get_success_url(self):
"""Redirect to the DS data page for the domain."""
return reverse("domain-dns-dnssec-dsdata", kwargs={"domain_pk": self.object.pk})
def get_context_data(self, **kwargs):
"""Adjust context from FormMixin for formsets."""
context = super().get_context_data(**kwargs)
# use "formset" instead of "form" for the key
context["formset"] = context.pop("form")
return context