Fixes #1215. Allow secret key to come from file.

This commit is contained in:
Rob Ludwick 2021-01-11 23:37:10 -07:00
parent ab9a6bd3c4
commit 3cfe358102

View File

@ -11,17 +11,20 @@ database setup in this file.
""" """
import sys
import os
import logging import logging
import os
import sys
import tempfile import tempfile
import yaml
from datetime import datetime from datetime import datetime
import yaml
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
def _is_true(x):
return x in [True, "True", "true", "Y", "y", "1"]
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@ -36,11 +39,14 @@ with open(cfg_filename, 'r') as cfg:
# Default action is to run the system in Debug mode # Default action is to run the system in Debug mode
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = CONFIG.get('debug', True) DEBUG = _is_true(os.getenv("INVENTREE_DEBUG", CONFIG.get("debug", True)))
# Configure logging settings # Configure logging settings
log_level = CONFIG.get('log_level', 'DEBUG').upper() log_level = CONFIG.get('log_level', 'DEBUG').upper()
logging.basicConfig(
level=log_level,
format="%(asctime)s %(levelname)s %(message)s",
)
if log_level not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']: if log_level not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
log_level = 'WARNING' log_level = 'WARNING'
@ -59,20 +65,31 @@ LOGGING = {
}, },
} }
logging.basicConfig(
level=log_level,
format='%(asctime)s %(levelname)s %(message)s',
)
# Get a logger instance for this setup file # Get a logger instance for this setup file
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Read the autogenerated key-file if os.getenv("INVENTREE_SECRET_KEY"):
key_file_name = os.path.join(BASE_DIR, 'secret_key.txt') # Secret key passed in directly
logger.info(f'Loading SECRET_KEY from {key_file_name}') SECRET_KEY = os.getenv("INVENTREE_SECRET_KEY").strip()
key_file = open(key_file_name, 'r') logger.info("SECRET_KEY loaded by INVENTREE_SECRET_KEY")
else:
SECRET_KEY = key_file.read().strip() # Secret key passed in by file location
key_file = os.getenv("INVENTREE_SECRET_KEY_FILE")
if key_file:
if os.path.isfile(key_file):
logger.info("SECRET_KEY loaded by INVENTREE_SECRET_KEY_FILE")
else:
logger.error(f"Secret key file {key_file} not found")
exit(-1)
else:
# default secret key location
key_file = os.path.join(BASE_DIR, "secret_key.txt")
logger.info(f"SECRET_KEY loaded from {key_file}")
try:
SECRET_KEY = open(key_file, "r").read().strip()
except Exception:
logger.exception(f"Couldn't load keyfile {key_file}")
sys.exit(-1)
# List of allowed hosts (default = allow all) # List of allowed hosts (default = allow all)
ALLOWED_HOSTS = CONFIG.get('allowed_hosts', ['*']) ALLOWED_HOSTS = CONFIG.get('allowed_hosts', ['*'])
@ -112,7 +129,7 @@ MEDIA_ROOT = os.path.abspath(CONFIG.get('media_root', os.path.join(BASE_DIR, 'me
if DEBUG: if DEBUG:
logger.info("InvenTree running in DEBUG mode") logger.info("InvenTree running in DEBUG mode")
logger.info(f"MEDIA_ROOT: '{MEDIA_ROOT}'") logger.info(f"MEDIA_ROOT: '{MEDIA_ROOT}'")
logger.info(f"STATIC_ROOT: '{STATIC_ROOT}'") logger.info(f"STATIC_ROOT: '{STATIC_ROOT}'")
@ -315,7 +332,7 @@ else:
- However there may be reason to configure the DB via environmental variables - However there may be reason to configure the DB via environmental variables
- The following code lets the user "mix and match" database configuration - The following code lets the user "mix and match" database configuration
""" """
logger.info("Configuring database backend:") logger.info("Configuring database backend:")
# Extract database configuration from the config.yaml file # Extract database configuration from the config.yaml file
@ -341,7 +358,7 @@ else:
# Check that required database configuration options are specified # Check that required database configuration options are specified
reqiured_keys = ['ENGINE', 'NAME'] reqiured_keys = ['ENGINE', 'NAME']
for key in reqiured_keys: for key in reqiured_keys:
if key not in db_config: if key not in db_config:
error_msg = f'Missing required database configuration value {key} in config.yaml' error_msg = f'Missing required database configuration value {key} in config.yaml'