Automated Action f207cc3c64 Create RESTful API service with FastAPI and SQLite
- Set up project structure with FastAPI and dependency files
- Configure SQLAlchemy with SQLite database
- Implement user authentication using JWT tokens
- Create comprehensive API routes for user management
- Add health check endpoint for application monitoring
- Set up Alembic for database migrations
- Add detailed documentation in README.md
2025-06-16 14:56:03 +00:00

88 lines
2.2 KiB
Python

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from sqlalchemy.orm import Session
from app.core.config import settings
from app.db.session import get_db
from app.models.user import User
from app.schemas.token import TokenPayload
# OAuth2 scheme for token authentication
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_PREFIX}/auth/login")
def get_current_user(
db: Session = Depends(get_db),
token: str = Depends(oauth2_scheme),
) -> User:
"""
Get the current user based on the provided JWT token.
Args:
db: Database session.
token: JWT token from the Authorization header.
Returns:
The current authenticated user.
Raises:
HTTPException: If the token is invalid or the user is not found.
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
# Decode JWT token
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)
token_data = TokenPayload(**payload)
if token_data.sub is None:
raise credentials_exception
except JWTError:
raise credentials_exception
# Get the user from the database
user = db.query(User).filter(User.id == token_data.sub).first()
if user is None:
raise credentials_exception
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Inactive user",
)
return user
def get_current_active_superuser(
current_user: User = Depends(get_current_user),
) -> User:
"""
Get the current user and verify they are a superuser.
Args:
current_user: Current authenticated user.
Returns:
The current authenticated superuser.
Raises:
HTTPException: If the user is not a superuser.
"""
if not current_user.is_superuser:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
)
return current_user