51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
"""
|
|
Shared dependencies for API Service routes.
|
|
Provides JWT-based authentication via get_current_user.
|
|
"""
|
|
|
|
from fastapi import Depends, HTTPException, Security, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
|
|
from shared.models import get_db, User
|
|
from auth_service.app.utils.security import decode_access_token
|
|
|
|
security = HTTPBearer()
|
|
|
|
|
|
async def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Security(security),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> User:
|
|
"""Validate JWT and return the current User ORM instance."""
|
|
payload = decode_access_token(credentials.credentials)
|
|
if payload is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid or expired token",
|
|
)
|
|
|
|
user_id = payload.get("sub")
|
|
if not user_id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid token payload",
|
|
)
|
|
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
|
|
if user is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="User not found",
|
|
)
|
|
if not user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="User account is deactivated",
|
|
)
|
|
|
|
return user
|