Code cleanup

This commit is contained in:
zandercymatics 2024-01-09 13:31:32 -07:00
parent 91ed4a598c
commit ab6cbb93c6
No known key found for this signature in database
GPG key ID: FF4636ABEC9682B7
5 changed files with 59 additions and 26 deletions

View file

@ -8,11 +8,8 @@ from django import forms
from django.core.validators import RegexValidator, MaxLengthValidator from django.core.validators import RegexValidator, MaxLengthValidator
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from api.views import DOMAIN_API_MESSAGES
from registrar.models import Contact, DomainApplication, DraftDomain, Domain from registrar.models import Contact, DomainApplication, DraftDomain, Domain
from registrar.templatetags.url_helpers import public_site_url from registrar.templatetags.url_helpers import public_site_url
from registrar.utility import errors
from registrar.utility.enums import ValidationErrorReturnType from registrar.utility.enums import ValidationErrorReturnType
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -386,7 +383,9 @@ class AlternativeDomainForm(RegistrarForm):
def clean_alternative_domain(self): def clean_alternative_domain(self):
"""Validation code for domain names.""" """Validation code for domain names."""
requested = self.cleaned_data.get("alternative_domain", None) requested = self.cleaned_data.get("alternative_domain", None)
validated = DraftDomain.validate_and_handle_errors(requested, ValidationErrorReturnType.FORM_VALIDATION_ERROR) validated = DraftDomain.validate_and_handle_errors(
requested, ValidationErrorReturnType.FORM_VALIDATION_ERROR, prevent_blank=False
)
return validated return validated
alternative_domain = forms.CharField( alternative_domain = forms.CharField(

View file

@ -2,6 +2,7 @@ import logging
import sys import sys
from typing import List from typing import List
from registrar.utility.enums import LogCode from registrar.utility.enums import LogCode
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

View file

@ -57,30 +57,44 @@ class DomainHelper:
return domain return domain
@classmethod @classmethod
def validate_and_handle_errors(cls, domain, error_return_type, display_success = False): def validate_and_handle_errors(cls, domain, error_return_type, prevent_blank=True, display_success=False):
"""Runs validate() and catches possible exceptions.""" """
Validates the provided domain and handles any validation errors.
This method attempts to validate the domain using the `validate` method. If validation fails,
it catches the exception and returns an appropriate error response. The type of the error response
(JSON response or form validation error) is determined by the `error_return_type` parameter.
If validation is successful and `display_success` is True, it returns a success response.
Otherwise, it returns the validated domain.
Args:
domain (str): The domain to validate.
error_return_type (ValidationErrorReturnType): The type of error response to return if validation fails.
prevent_blank (bool, optional): Whether to return an exception if the input is blank. Defaults to True.
display_success (bool, optional): Whether to return a success response if validation is successful. Defaults to False.
Returns:
The error response if validation fails,
the success response if validation is successful and `display_success` is True,
or the validated domain otherwise.
""" # noqa
try: try:
validated = cls.validate(domain) validated = cls.validate(domain)
except errors.BlankValueError: except errors.BlankValueError:
return DomainHelper._return_form_error_or_json_response( if not prevent_blank:
error_return_type, code="required" return DomainHelper._return_form_error_or_json_response(error_return_type, code="required")
) else:
return validated
except errors.ExtraDotsError: except errors.ExtraDotsError:
return DomainHelper._return_form_error_or_json_response( return DomainHelper._return_form_error_or_json_response(error_return_type, code="extra_dots")
error_return_type, code="extra_dots"
)
except errors.DomainUnavailableError: except errors.DomainUnavailableError:
return DomainHelper._return_form_error_or_json_response( return DomainHelper._return_form_error_or_json_response(error_return_type, code="unavailable")
error_return_type, code="unavailable"
)
except errors.RegistrySystemError: except errors.RegistrySystemError:
return DomainHelper._return_form_error_or_json_response( return DomainHelper._return_form_error_or_json_response(error_return_type, code="error")
error_return_type, code="error"
)
except errors.InvalidDomainError: except errors.InvalidDomainError:
return DomainHelper._return_form_error_or_json_response( return DomainHelper._return_form_error_or_json_response(error_return_type, code="invalid")
error_return_type, code="invalid"
)
else: else:
if display_success: if display_success:
return DomainHelper._return_form_error_or_json_response( return DomainHelper._return_form_error_or_json_response(
@ -91,13 +105,29 @@ class DomainHelper:
@staticmethod @staticmethod
def _return_form_error_or_json_response(return_type: ValidationErrorReturnType, code, available=False): def _return_form_error_or_json_response(return_type: ValidationErrorReturnType, code, available=False):
"""
Returns an error response based on the `return_type`.
If `return_type` is `FORM_VALIDATION_ERROR`, raises a form validation error.
If `return_type` is `JSON_RESPONSE`, returns a JSON response with 'available', 'code', and 'message' fields.
If `return_type` is neither, raises a ValueError.
Args:
return_type (ValidationErrorReturnType): The type of error response.
code (str): The error code for the error message.
available (bool, optional): Availability, only used for JSON responses. Defaults to False.
Returns:
A JSON response or a form validation error.
Raises:
ValueError: If `return_type` is neither `FORM_VALIDATION_ERROR` nor `JSON_RESPONSE`.
""" # noqa
match return_type: match return_type:
case ValidationErrorReturnType.FORM_VALIDATION_ERROR: case ValidationErrorReturnType.FORM_VALIDATION_ERROR:
raise forms.ValidationError(DOMAIN_API_MESSAGES[code], code=code) raise forms.ValidationError(DOMAIN_API_MESSAGES[code], code=code)
case ValidationErrorReturnType.JSON_RESPONSE: case ValidationErrorReturnType.JSON_RESPONSE:
return JsonResponse( return JsonResponse({"available": available, "code": code, "message": DOMAIN_API_MESSAGES[code]})
{"available": available, "code": code, "message": DOMAIN_API_MESSAGES[code]}
)
case _: case _:
raise ValueError("Invalid return type specified") raise ValueError("Invalid return type specified")

View file

@ -5,6 +5,7 @@ from enum import Enum
class ValidationErrorReturnType(Enum): class ValidationErrorReturnType(Enum):
"""Determines the return value of the validate_and_handle_errors class""" """Determines the return value of the validate_and_handle_errors class"""
JSON_RESPONSE = "JSON_RESPONSE" JSON_RESPONSE = "JSON_RESPONSE"
FORM_VALIDATION_ERROR = "FORM_VALIDATION_ERROR" FORM_VALIDATION_ERROR = "FORM_VALIDATION_ERROR"

View file

@ -16,9 +16,11 @@ class DomainUnavailableError(ValueError):
class RegistrySystemError(ValueError): class RegistrySystemError(ValueError):
pass pass
class InvalidDomainError(ValueError): class InvalidDomainError(ValueError):
pass pass
class ActionNotAllowed(Exception): class ActionNotAllowed(Exception):
"""User accessed an action that is not """User accessed an action that is not
allowed by the current state""" allowed by the current state"""