An open source, non-profit web search engine
Validate domains
Daoud Clarke3c0caa8049ec
diff --git a/mwmbl/utils.py b/mwmbl/utils.pyindex 26c4cb4..c797553 100644--- a/mwmbl/utils.py+++ b/mwmbl/utils.py@@ -2,6 +2,8 @@ import refrom dataclasses import dataclassfrom typing import Sequence+from django.core.exceptions import ValidationError+from mwmbl.indexer.index import tokenize_documentfrom mwmbl.tinysearchengine.indexer import Document, TinyIndex@@ -64,3 +66,18 @@ def parse_url(url: str) -> ParsedUrl:if results is None:raise ValueError(f"Unable to parse URL {url}")return ParsedUrl(results.group(2), results.group(4), results.group(6), results.group(7))+++VALID_DOMAIN_REGEX = re.compile(r"^[\w-]{1,63}(\.[\w-]{1,63})+$")+++def validate_domain(domain_or_url: str):+ if VALID_DOMAIN_REGEX.fullmatch(domain_or_url) is None:+ # See if we can extract a domain from the URL+ try:+ domain = parse_url(domain_or_url).netloc+ except ValueError:+ raise ValidationError("Invalid domain: %(domain)s", params={"domain": domain_or_url})+ if domain is None or VALID_DOMAIN_REGEX.fullmatch(domain) is None:+ raise ValidationError("Invalid domain: %(domain)s", params={"domain": domain_or_url})+diff --git a/mwmbl/views.py b/mwmbl/views.pyindex 090f916..87d7508 100644--- a/mwmbl/views.py+++ b/mwmbl/views.py@@ -1,3 +1,4 @@+import refrom dataclasses import asdictfrom datetime import datetimefrom logging import getLogger@@ -9,7 +10,7 @@ import requestsfrom django.conf import settingsfrom django.contrib.auth.decorators import login_required, permission_requiredfrom django.contrib.auth.mixins import LoginRequiredMixin-from django.forms import ModelForm, ModelChoiceField, RadioSelect+from django.forms import ModelForm, ModelChoiceField, RadioSelect, CharFieldfrom django.http import HttpResponseBadRequestfrom django.shortcuts import render, redirectfrom django.views.decorators.http import require_http_methods@@ -26,7 +27,7 @@ from mwmbl.settings import NUM_EXTRACT_CHARSfrom mwmbl.tinysearchengine.indexer import Document, DocumentState, TinyIndexfrom mwmbl.tinysearchengine.rank import fix_document_statefrom mwmbl.tokenizer import tokenize-from mwmbl.utils import add_term_infos+from mwmbl.utils import add_term_infos, parse_url, validate_domainMAX_CURATED_SCORE = 1_111_111.0@@ -155,6 +156,19 @@ class DomainSubmissionForm(ModelForm):model = DomainSubmissionfields = ["name"]+ name = CharField(validators=[validate_domain])++ def clean_name(self):+ """+ Domain names or URLs are allowed. If a URL is submitted, just extract the domain.+ """+ original_name = self.cleaned_data["name"]+ try:+ domain = parse_url(original_name).netloc+ return domain+ except ValueError:+ return original_name+class DomainSubmissionApprovalForm(ModelForm):class Meta:diff --git a/test/test_utils.py b/test/test_utils.pyindex 54f663a..65ab31e 100644--- a/test/test_utils.py+++ b/test/test_utils.py@@ -1,4 +1,7 @@-from mwmbl.utils import parse_url+import pytest+from django.core.exceptions import ValidationError++from mwmbl.utils import parse_url, validate_domaindef test_parse_url():@@ -8,3 +11,24 @@ def test_parse_url():assert parsed.netloc == "www.google.com"assert parsed.query_string == "?q=python+parse+url+regex"assert parsed.fragment == "#result"+++def test_validate_domain_valid():+ validate_domain("google.com")+ validate_domain("www.google.com")+ validate_domain("www.google.co.uk")+++def test_validate_domain_invalid():+ with pytest.raises(ValidationError):+ validate_domain("google")+++def test_validate_url_domain_invalid():+ with pytest.raises(ValidationError):+ validate_domain("https://google/something")+++def test_validate_with_url():+ validate_domain("https://www.google.com")+ validate_domain("http://www.google.com")