Files
eamco_service/app/auth.py
Edwin Eames 07865480c7 Initial commit: Add EAMCO Service API
- Add FastAPI service for managing oil delivery services
- Implement service scheduling and management endpoints
- Add customer service history tracking
- Include database models for services, customers, and auto-delivery
- Add authentication and authorization middleware
- Configure Docker support for local, dev, and prod environments
- Add comprehensive .gitignore for Python projects
2026-02-01 19:02:13 -05:00

42 lines
1.3 KiB
Python

import logging
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from database import get_db
from app.models.auth import Auth_User
logger = logging.getLogger(__name__)
security = HTTPBearer()
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db)
) -> Auth_User:
"""
Validates the Bearer token and returns the authenticated user.
Raises HTTPException 401 if token is invalid or user not found.
"""
token = credentials.credentials
user = db.query(Auth_User).filter(Auth_User.api_key == token).first()
if not user:
logger.warning("Authentication failed: invalid API key")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication token",
headers={"WWW-Authenticate": "Bearer"},
)
if user.active != 1:
logger.warning(f"Authentication failed: user {user.username} is inactive")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User account is inactive",
headers={"WWW-Authenticate": "Bearer"},
)
return user