Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Validate domains

Daoud Clarke3c0caa8049ec
diff --git a/mwmbl/utils.py b/mwmbl/utils.py
index 26c4cb4..c797553 100644
--- a/mwmbl/utils.py
+++ b/mwmbl/utils.py
@@ -2,6 +2,8 @@ import re
from dataclasses import dataclass
from typing import Sequence
+from django.core.exceptions import ValidationError
+
from mwmbl.indexer.index import tokenize_document
from 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.py
index 090f916..87d7508 100644
--- a/mwmbl/views.py
+++ b/mwmbl/views.py
@@ -1,3 +1,4 @@
+import re
from dataclasses import asdict
from datetime import datetime
from logging import getLogger
@@ -9,7 +10,7 @@ import requests
from django.conf import settings
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin
-from django.forms import ModelForm, ModelChoiceField, RadioSelect
+from django.forms import ModelForm, ModelChoiceField, RadioSelect, CharField
from django.http import HttpResponseBadRequest
from django.shortcuts import render, redirect
from django.views.decorators.http import require_http_methods
@@ -26,7 +27,7 @@ from mwmbl.settings import NUM_EXTRACT_CHARS
from mwmbl.tinysearchengine.indexer import Document, DocumentState, TinyIndex
from mwmbl.tinysearchengine.rank import fix_document_state
from mwmbl.tokenizer import tokenize
-from mwmbl.utils import add_term_infos
+from mwmbl.utils import add_term_infos, parse_url, validate_domain
MAX_CURATED_SCORE = 1_111_111.0
@@ -155,6 +156,19 @@ class DomainSubmissionForm(ModelForm):
model = DomainSubmission
fields = ["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.py
index 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_domain
def 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")