app backend prima
This commit is contained in:
0
app/core/__init__.py
Normal file
0
app/core/__init__.py
Normal file
44
app/core/config.py
Normal file
44
app/core/config.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from pathlib import Path
|
||||
|
||||
# Determina il percorso del file .env (nella root del progetto)
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
||||
ENV_FILE = BASE_DIR / ".env"
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Configurazione applicazione caricata da variabili d'ambiente"""
|
||||
|
||||
# Database
|
||||
DATABASE_URL: str = "postgresql://user:password@localhost:5432/terrain_monitor"
|
||||
|
||||
# JWT
|
||||
SECRET_KEY: str
|
||||
ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
# MQTT
|
||||
MQTT_BROKER_HOST: str = "localhost"
|
||||
MQTT_BROKER_PORT: int = 1883
|
||||
# Topic pattern: terrain/{cliente_id}/{sito_id}/alarms
|
||||
# Wildcards: + (single level), # (multi level)
|
||||
MQTT_TOPIC_ALARMS: str = "terrain/+/+/alarms"
|
||||
MQTT_TOPIC_TELEMETRY: str = "terrain/+/+/telemetry" # Dati sensori periodici
|
||||
MQTT_TOPIC_STATUS: str = "terrain/+/+/status" # Stato sensori/gateway
|
||||
MQTT_USERNAME: str = ""
|
||||
MQTT_PASSWORD: str = ""
|
||||
|
||||
# Firebase
|
||||
FIREBASE_CREDENTIALS_PATH: str = "./firebase-credentials.json"
|
||||
|
||||
# Application
|
||||
DEBUG: bool = False
|
||||
APP_NAME: str = "Terrain Monitor API"
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=str(ENV_FILE),
|
||||
env_file_encoding='utf-8'
|
||||
)
|
||||
|
||||
|
||||
settings = Settings()
|
||||
19
app/core/database.py
Normal file
19
app/core/database.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_engine(settings.DATABASE_URL)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Dependency per ottenere una sessione database"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
45
app/core/firebase.py
Normal file
45
app/core/firebase.py
Normal file
@@ -0,0 +1,45 @@
|
||||
import logging
|
||||
import firebase_admin
|
||||
from firebase_admin import credentials
|
||||
from pathlib import Path
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
firebase_app = None
|
||||
|
||||
|
||||
def init_firebase():
|
||||
"""Inizializza Firebase Admin SDK"""
|
||||
global firebase_app
|
||||
|
||||
if firebase_app is not None:
|
||||
logger.info("Firebase già inizializzato")
|
||||
return firebase_app
|
||||
|
||||
try:
|
||||
# Percorso al file di credenziali
|
||||
cred_path = Path(__file__).parent.parent.parent / "firebase-credentials.json"
|
||||
|
||||
if not cred_path.exists():
|
||||
logger.error(f"File credenziali Firebase non trovato: {cred_path}")
|
||||
raise FileNotFoundError(f"firebase-credentials.json non trovato in {cred_path}")
|
||||
|
||||
# Inizializza con le credenziali
|
||||
cred = credentials.Certificate(str(cred_path))
|
||||
firebase_app = firebase_admin.initialize_app(cred)
|
||||
|
||||
logger.info("Firebase Admin SDK inizializzato con successo")
|
||||
return firebase_app
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Errore nell'inizializzazione di Firebase: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def get_firebase_app():
|
||||
"""Ottiene l'istanza di Firebase App"""
|
||||
if firebase_app is None:
|
||||
return init_firebase()
|
||||
return firebase_app
|
||||
46
app/core/security.py
Normal file
46
app/core/security.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verifica una password contro il suo hash"""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Genera l'hash di una password"""
|
||||
# bcrypt ha un limite di 72 byte, tronchiamo se necessario
|
||||
# Questo è sicuro perché 72 byte forniscono comunque entropia sufficiente
|
||||
if len(password.encode('utf-8')) > 72:
|
||||
password = password.encode('utf-8')[:72].decode('utf-8', errors='ignore')
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
||||
"""Crea un JWT token"""
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
else:
|
||||
expire = datetime.now(timezone.utc) + timedelta(
|
||||
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> Optional[dict]:
|
||||
"""Decodifica e valida un JWT token"""
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
return payload
|
||||
except JWTError:
|
||||
return None
|
||||
Reference in New Issue
Block a user