95 lines
2.7 KiB
Python
95 lines
2.7 KiB
Python
"""Autenticación: hashing de passwords y emisión/verificación de JWT."""
|
|
import os
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Optional
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
from sqlalchemy.orm import Session
|
|
|
|
from database import get_db
|
|
from models import User
|
|
|
|
JWT_SECRET = os.environ.get("JWT_SECRET", "dev-insecure-secret-change-me")
|
|
JWT_ALGORITHM = "HS256"
|
|
JWT_EXPIRE_HOURS = 8
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
# tokenUrl es solo informativo para el flujo OpenAPI; el login real es JSON.
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
try:
|
|
return pwd_context.verify(plain, hashed)
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def create_access_token(user: User) -> str:
|
|
now = datetime.now(timezone.utc)
|
|
payload = {
|
|
"sub": str(user.id),
|
|
"username": user.username,
|
|
"iat": now,
|
|
"exp": now + timedelta(hours=JWT_EXPIRE_HOURS),
|
|
}
|
|
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
|
|
|
|
|
def authenticate_user(db: Session, username: str, password: str) -> Optional[User]:
|
|
user = db.query(User).filter(User.username == username).first()
|
|
if not user or not user.is_active:
|
|
return None
|
|
if not verify_password(password, user.hashed_password):
|
|
return None
|
|
return user
|
|
|
|
|
|
def get_current_user(
|
|
token: Optional[str] = Depends(oauth2_scheme),
|
|
db: Session = Depends(get_db),
|
|
) -> User:
|
|
credentials_exc = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="No autenticado",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
if not token:
|
|
raise credentials_exc
|
|
try:
|
|
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
|
user_id = payload.get("sub")
|
|
if user_id is None:
|
|
raise credentials_exc
|
|
except JWTError:
|
|
raise credentials_exc
|
|
|
|
user = db.query(User).filter(User.id == int(user_id)).first()
|
|
if not user or not user.is_active:
|
|
raise credentials_exc
|
|
return user
|
|
|
|
|
|
ADMIN_USERNAME = os.environ.get("FIRST_ADMIN_USER", "admin")
|
|
|
|
|
|
def is_admin(user: User) -> bool:
|
|
return user.username == ADMIN_USERNAME
|
|
|
|
|
|
def require_admin(user: User = Depends(get_current_user)) -> User:
|
|
if not is_admin(user):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Se requieren privilegios de administrador",
|
|
)
|
|
return user
|