mirror of
https://github.com/bookwyrm-social/bookwyrm.git
synced 2024-12-23 08:36:32 +00:00
Add validation util + test
This commit is contained in:
parent
5c92774a7f
commit
bfe04feca9
2 changed files with 34 additions and 0 deletions
|
@ -3,6 +3,7 @@ import re
|
|||
from django.test import TestCase
|
||||
|
||||
from bookwyrm.utils import regex
|
||||
from bookwyrm.utils.validate import validate_url_domain
|
||||
|
||||
|
||||
class TestUtils(TestCase):
|
||||
|
@ -11,3 +12,20 @@ class TestUtils(TestCase):
|
|||
def test_regex(self):
|
||||
"""Regexes used throughout the app"""
|
||||
self.assertTrue(re.match(regex.DOMAIN, "xn--69aa8bzb.xn--y9a3aq"))
|
||||
|
||||
def test_valid_url_domain(self):
|
||||
"""Check with a valid URL"""
|
||||
self.assertEqual(
|
||||
validate_url_domain("https://your.domain.here/legit-book-url/"),
|
||||
"https://your.domain.here/legit-book-url/",
|
||||
)
|
||||
|
||||
def test_invalid_url_domain(self):
|
||||
"""Check with an invalid URL"""
|
||||
self.assertEqual(
|
||||
validate_url_domain("https://up-to-no-good.tld/bad-actor.exe"), "/"
|
||||
)
|
||||
|
||||
def test_default_url_domain(self):
|
||||
"""Check with a default URL"""
|
||||
self.assertEqual(validate_url_domain("/"), "/")
|
||||
|
|
16
bookwyrm/utils/validate.py
Normal file
16
bookwyrm/utils/validate.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
"""Validations"""
|
||||
from bookwyrm.settings import DOMAIN, USE_HTTPS
|
||||
|
||||
|
||||
def validate_url_domain(url, default="/"):
|
||||
"""Basic check that the URL starts with the instance domain name"""
|
||||
if url in ("/", default):
|
||||
return url
|
||||
|
||||
protocol = "https://" if USE_HTTPS else "http://"
|
||||
origin = f"{protocol}{DOMAIN}"
|
||||
|
||||
if url.startswith(origin):
|
||||
return url
|
||||
|
||||
return default
|
Loading…
Reference in a new issue