Files
mtusi2026lab3/scripts/setup.py
T

22 lines
966 B
Python

"""Generate local credentials once; never print or rotate existing secrets."""
from pathlib import Path
import secrets
import shutil
root = Path(__file__).resolve().parents[1]
directory = root / 'secrets'
directory.mkdir(exist_ok=True)
password_file = directory / 'postgres_password'
url_file = directory / 'database_url'
if password_file.exists() != url_file.exists():
raise SystemExit('Incomplete secrets: restore the missing file; do not rotate an existing database password.')
if not password_file.exists():
password = secrets.token_hex(32)
password_file.write_text(password + '\n', encoding='utf-8')
url_file.write_text('postgresql://messenger:' + password + '@db:5432/messenger\n', encoding='utf-8')
password_file.chmod(0o600)
url_file.chmod(0o600)
if not (root / '.env').exists():
shutil.copyfile(root / '.env.example', root / '.env')
print('Local .env and secrets ready; values are not printed. Existing credentials preserved.')