Different keys for session and csrf checking middleware, some comments in compose yml and .env

This commit is contained in:
DarkCat09 2023-03-24 19:00:31 +04:00
parent edbf0233ba
commit 3b588d2da5
4 changed files with 39 additions and 23 deletions

View file

@ -1,5 +1,6 @@
import secrets
from pathlib import Path
from typing import Literal
from fastapi.templating import Jinja2Templates
from pydantic import BaseSettings
@ -14,12 +15,16 @@ static_dir = str(file_dir.parent / 'static')
# Main configuration
class Settings(BaseSettings):
debug: bool = False
secret_key: str = 'secret'
session_key: str = 'secret'
csrf_key: str = 'secret'
app_host: str = '127.0.0.1'
app_port: int = 8000
# Instantiate Settings class
# Type alias for secret keys settings fields
SecretKey = Literal['session_key', 'csrf_key']
# Settings class instantiating
settings = Settings()
# Jinja templates handler
@ -28,26 +33,30 @@ templates = Jinja2Templates(
)
def secret_key_check() -> None:
def secret_key_check(name: SecretKey) -> None:
"""Generates a secret key automatically
if the env var `secret_key` is not set
if an environment variable is not set
or contains text `secret`"""
if settings.secret_key == 'secret':
settings_dict = settings.dict()
if settings_dict.get(name) != 'secret':
return
key_file = Path('/tmp/secret_key')
key_file = Path(f'/tmp/{name}')
if key_file.exists():
with key_file.open('rt') as f:
secret_key = f.read()
if key_file.exists():
with key_file.open('rt') as f:
key = f.read()
else:
secret_key = secrets.token_hex(32)
with key_file.open('wt') as f:
f.write(secret_key)
else:
key = secrets.token_hex(32)
with key_file.open('wt') as f:
f.write(key)
settings.secret_key = secret_key
settings_dict[name] = key
# Call the function
secret_key_check()
# Calling the function
# for session and CSRF keys
secret_key_check('session_key')
secret_key_check('csrf_key')

View file

@ -42,9 +42,9 @@ for p in paths:
# Add WTForms CSRF protection middlewares
app.add_middleware(
SessionMiddleware,
secret_key=common.settings.secret_key,
secret_key=common.settings.session_key,
)
app.add_middleware(
CSRFProtectMiddleware,
csrf_secret=common.settings.secret_key,
csrf_secret=common.settings.csrf_key,
)