Automated Action 6776db0bbd Create REST API with FastAPI and SQLite
- Set up project structure with FastAPI
- Configure SQLAlchemy with SQLite
- Implement user and item models
- Set up Alembic for database migrations
- Create CRUD operations for models
- Implement API endpoints for users and items
- Add authentication functionality
- Add health check endpoint
- Configure Ruff for linting
- Update README with comprehensive documentation
2025-05-22 11:40:52 +00:00

61 lines
1.9 KiB
Python

from typing import Annotated
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from app.api.dependencies.db import get_db
from app.crud import user as user_crud
from app.models.user import User
# This is just a placeholder. In a real application, you would use a proper auth system.
# For demonstration purposes, we'll use a simple approach
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/auth/login")
def get_current_user(
db: Annotated[Session, Depends(get_db)],
token: Annotated[str, Depends(oauth2_scheme)]
) -> User:
"""
Get the current authenticated user.
This is a simplified implementation - in a real app, you would validate JWT tokens.
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
# In a real app, you would decode and validate the JWT token
# For this demo, we'll just fetch the first user from the database
# This is NOT secure and should NOT be used in production
user = db.query(User).first()
if user is None:
raise credentials_exception
return user
def get_current_active_user(
current_user: Annotated[User, Depends(get_current_user)]
) -> User:
"""
Get the current active user.
"""
if not user_crud.is_active(current_user):
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
def get_current_active_superuser(
current_user: Annotated[User, Depends(get_current_user)]
) -> User:
"""
Get the current active superuser.
"""
if not user_crud.is_superuser(current_user):
raise HTTPException(
status_code=403, detail="The user doesn't have enough privileges"
)
return current_user