diff --git a/fzw/settings.py b/fzw/settings.py index b5c3223..cb12c27 100644 --- a/fzw/settings.py +++ b/fzw/settings.py @@ -14,6 +14,8 @@ import dj_database_url # type: ignore +from fzw.util.common import smart_bool, smart_bool_or_none + # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATA_DIR = os.path.join(BASE_DIR, 'data') @@ -26,7 +28,7 @@ SECRET_KEY = os.environ.get('SECRET_KEY', 'abracadabra') # SECURITY WARNING: don't run with debug turned on in production! -DEBUG = bool(int(os.environ.get('DEBUG', '0'))) +DEBUG = smart_bool(os.getenv("DEBUG")) BACKEND_HOST = os.environ.get('BACKEND_HOST', '*') DATABASE_URL = os.environ.get( @@ -178,7 +180,11 @@ }, } -if not DEBUG: +HSTS_MODE_ENABLED = smart_bool_or_none(os.getenv("HSTS_MODE_ENABLED")) +if HSTS_MODE_ENABLED is None: + HSTS_MODE_ENABLED = not DEBUG + +if HSTS_MODE_ENABLED: SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_SSL_REDIRECT = True diff --git a/fzw/util/__init__.py b/fzw/util/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fzw/util/common.py b/fzw/util/common.py new file mode 100644 index 0000000..ec5f059 --- /dev/null +++ b/fzw/util/common.py @@ -0,0 +1,21 @@ +from typing import Any, Optional + +_TRUTHY_VALUES = {"t", "true", "1"} +_FALSY_VALUES = {"f", "false", "0"} + + +def smart_bool_or_none(value: Any) -> Optional[bool]: + if isinstance(value, str): + normalized_value = value.lower() + if normalized_value in _TRUTHY_VALUES: + return True + if normalized_value in _FALSY_VALUES: + return False + return None + if value is None: + return None + return bool(value) + + +def smart_bool(value: Any) -> bool: + return smart_bool_or_none(value) or False diff --git a/tests/util/__init__.py b/tests/util/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/util/test_common.py b/tests/util/test_common.py new file mode 100644 index 0000000..0036a5f --- /dev/null +++ b/tests/util/test_common.py @@ -0,0 +1,55 @@ +import pytest + +from fzw.util.common import smart_bool, smart_bool_or_none + + +@pytest.mark.parametrize( + "input,output", + ( + (False, False), + (True, True), + (0, False), + (1, True), + (1.0, True), + (0.1, True), + ("", False), + ("none", False), + ("nil", False), + ("0", False), + ("false", False), + ("False", False), + ("f", False), + ("1", True), + ("true", True), + ("True", True), + ("t", True), + ), +) +def test_smart_bool(input, output): + assert smart_bool(input) == output + + +@pytest.mark.parametrize( + "input,output", + ( + (False, False), + (True, True), + (0, False), + (1, True), + (1.0, True), + (0.1, True), + ("", None), + ("none", None), + ("nil", None), + ("0", False), + ("false", False), + ("False", False), + ("f", False), + ("1", True), + ("true", True), + ("True", True), + ("t", True), + ), +) +def test_smart_bool_or_none(input, output): + assert smart_bool_or_none(input) == output