2023-02-18 20:17:16 +03:00
|
|
|
import secrets
|
2023-02-18 20:25:47 +03:00
|
|
|
from pathlib import Path
|
2023-03-24 18:00:31 +03:00
|
|
|
from typing import Literal
|
2023-02-18 20:17:16 +03:00
|
|
|
|
|
|
|
from fastapi.templating import Jinja2Templates
|
|
|
|
from pydantic import BaseSettings
|
|
|
|
|
|
|
|
|
2023-02-27 18:05:04 +03:00
|
|
|
# Directories
|
2023-02-19 15:19:18 +03:00
|
|
|
file_dir = Path(__file__).parent
|
2023-03-10 16:17:23 +03:00
|
|
|
templates_dir = str(file_dir.parent / 'templates')
|
|
|
|
static_dir = str(file_dir.parent / 'static')
|
2023-02-20 11:09:43 +03:00
|
|
|
|
|
|
|
|
2023-02-27 18:05:04 +03:00
|
|
|
# Main configuration
|
2023-02-20 11:09:43 +03:00
|
|
|
class Settings(BaseSettings):
|
2023-02-27 17:49:30 +03:00
|
|
|
debug: bool = False
|
2023-03-24 18:00:31 +03:00
|
|
|
session_key: str = 'secret'
|
|
|
|
csrf_key: str = 'secret'
|
2023-03-03 17:10:17 +03:00
|
|
|
app_host: str = '127.0.0.1'
|
|
|
|
app_port: int = 8000
|
2023-02-20 11:09:43 +03:00
|
|
|
|
2023-02-27 18:05:57 +03:00
|
|
|
|
2023-03-24 18:00:31 +03:00
|
|
|
# Type alias for secret keys settings fields
|
|
|
|
SecretKey = Literal['session_key', 'csrf_key']
|
|
|
|
|
|
|
|
# Settings class instantiating
|
2023-02-20 11:09:43 +03:00
|
|
|
settings = Settings()
|
2023-02-19 15:19:18 +03:00
|
|
|
|
2023-02-27 18:05:04 +03:00
|
|
|
# Jinja templates handler
|
2023-02-18 20:17:16 +03:00
|
|
|
templates = Jinja2Templates(
|
2023-02-19 15:19:18 +03:00
|
|
|
directory=templates_dir,
|
2023-02-18 20:17:16 +03:00
|
|
|
)
|
2023-03-10 16:17:23 +03:00
|
|
|
|
|
|
|
|
2023-03-24 18:00:31 +03:00
|
|
|
def secret_key_check(name: SecretKey) -> None:
|
2023-03-10 16:17:23 +03:00
|
|
|
"""Generates a secret key automatically
|
2023-03-24 18:00:31 +03:00
|
|
|
if an environment variable is not set
|
2023-03-10 16:17:23 +03:00
|
|
|
or contains text `secret`"""
|
|
|
|
|
2023-03-24 18:00:31 +03:00
|
|
|
settings_dict = settings.dict()
|
|
|
|
if settings_dict.get(name) != 'secret':
|
|
|
|
return
|
2023-03-10 16:17:23 +03:00
|
|
|
|
2023-03-24 18:00:31 +03:00
|
|
|
key_file = Path(f'/tmp/{name}')
|
2023-03-10 16:17:23 +03:00
|
|
|
|
2023-03-24 18:00:31 +03:00
|
|
|
if key_file.exists():
|
|
|
|
with key_file.open('rt') as f:
|
|
|
|
key = f.read()
|
2023-03-10 16:17:23 +03:00
|
|
|
|
2023-03-24 18:00:31 +03:00
|
|
|
else:
|
|
|
|
key = secrets.token_hex(32)
|
|
|
|
with key_file.open('wt') as f:
|
|
|
|
f.write(key)
|
2023-03-10 16:17:23 +03:00
|
|
|
|
2023-03-24 18:00:31 +03:00
|
|
|
settings_dict[name] = key
|
2023-03-10 16:17:23 +03:00
|
|
|
|
|
|
|
|
2023-03-24 18:00:31 +03:00
|
|
|
# Calling the function
|
|
|
|
# for session and CSRF keys
|
|
|
|
secret_key_check('session_key')
|
|
|
|
secret_key_check('csrf_key')
|