Backend finished

Co-authored-by: Álvaro <alvaro6gv@users.noreply.github.com>
This commit is contained in:
2025-11-10 19:49:26 +01:00
parent a2e823c4c3
commit d2f3cad487
18 changed files with 330 additions and 1 deletions

View File

View File

@@ -0,0 +1,22 @@
from pydantic_settings import BaseSettings
from dotenv import load_dotenv
import os
load_dotenv()
class Settings(BaseSettings):
DB_URL: str = os.getenv('DB_URL')
SECRET_KEY: str = os.getenv('SECRET_KEY')
ALGORITHM: str = os.getenv('ALGORITHM', 'HS256')
EXPIRATION: int = int(os.getenv('EXPIRATION', 86400))
TOTP_INTERVAL: int = int(os.getenv('TOTP_INTERVAL', 30))
TOTP_DIGITS: int = int(os.getenv('TOTP_DIGITS', 6))
TOTP_ALGORITHM: str = os.getenv('TOTP_ALGORITHM', 'SHA1')
TOTP_ISSUER: str = os.getenv('TOTP_ISSUER', 'SSII2FA')
TOTP_NAME_PREFIX: str = os.getenv('TOTP_NAME_PREFIX', 'user')
class Config:
env_file = ".env"
settings = Settings()

View File

@@ -0,0 +1,35 @@
from passlib.context import CryptContext
from datetime import datetime, timedelta, timezone
from app.core.config import settings
import jwt
from fastapi import HTTPException, status
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def generate_jwt(data: dict, expires: timedelta | None = None):
to_encode = data.copy()
if expires:
expire = datetime.now(timezone.utc) + expires
else:
expire = datetime.now(timezone.utc) + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def verify_jwt(token: str):
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
return payload
except jwt.PyJWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token inválido o expirado",
headers={"WWW-Authenticate": "Bearer"},
)