Files
BTC-Portfolio/btc-portfolio/backend/app/services/btc.py
T
Jonathan 85455f3271 Security hardening: secrets, validation, Docker, and error handling
- Add root .gitignore to prevent btc_wallet.py (with RPC credentials) from being committed
- Load JWT SECRET_KEY from environment variable instead of hardcoded value
- Restrict CORS to explicit methods/headers instead of wildcards
- Add Pydantic Field validation (gt=0) to purchase amounts and user credentials
- Add logging to all silent exception handlers in btc.py
- Run backend and frontend Docker containers as non-root appuser
- Add .dockerignore for both backend and frontend
- Pass SECRET_KEY env var through docker-compose; add healthchecks to both services
- Update bcrypt from pinned 3.2.2 to >=4.0.0
- Capture error objects in frontend catch blocks; check admin delete response

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 18:40:41 +01:00

69 lines
2.2 KiB
Python

import logging
import requests
from datetime import datetime, timezone
logger = logging.getLogger(__name__)
def get_btc_history_eur() -> list:
try:
resp = requests.get(
"https://api.coingecko.com/api/v3/coins/bitcoin/market_chart",
params={"vs_currency": "eur", "days": "365", "interval": "daily"},
timeout=15,
)
resp.raise_for_status()
return resp.json().get("prices", []) # [[timestamp_ms, price], ...]
except Exception as e:
logger.error(f"Failed to fetch BTC history: {e}")
return []
def get_btc_ohlc_eur(days: int) -> list:
"""Fetch OHLC candles from CoinGecko. Returns [[ts_ms, open, high, low, close], ...]."""
try:
resp = requests.get(
"https://api.coingecko.com/api/v3/coins/bitcoin/ohlc",
params={"vs_currency": "eur", "days": str(days)},
timeout=20,
)
resp.raise_for_status()
return resp.json() # [[timestamp_ms, open, high, low, close], ...]
except Exception as e:
logger.error(f"Failed to fetch BTC OHLC: {e}")
return []
def aggregate_to_daily(raw: list) -> dict:
"""Collapse intraday OHLC rows into one candle per UTC calendar date.
Returns {date_str: {open, high, low, close}} using first open, max high,
min low, last close per day.
"""
by_date: dict = {}
for row in raw:
ts_ms, o, h, l, c = row
date = datetime.fromtimestamp(ts_ms / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
if date not in by_date:
by_date[date] = {"open": o, "high": h, "low": l, "close": c}
else:
existing = by_date[date]
existing["high"] = max(existing["high"], h)
existing["low"] = min(existing["low"], l)
existing["close"] = c # last close wins
return by_date
def get_btc_price_eur() -> float:
try:
resp = requests.get(
"https://api.coingecko.com/api/v3/simple/price",
params={"ids": "bitcoin", "vs_currencies": "eur"},
timeout=10,
)
resp.raise_for_status()
return float(resp.json()["bitcoin"]["eur"])
except Exception as e:
logger.error(f"Failed to fetch BTC price: {e}")
return 0.0