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

55 lines
1.6 KiB
Python

from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app.api.dependencies import get_current_user, get_db
from app.core.security import generate_token
from app.crud import user
from app.models.user import User
from app.schemas.token import Token
router = APIRouter()
@router.post("/login", response_model=Token)
def login_access_token(
db: Annotated[Session, Depends(get_db)],
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests.
"""
authenticated_user = user.authenticate(
db, email=form_data.username, password=form_data.password
)
if not authenticated_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
if not user.is_active(authenticated_user):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user"
)
# In a real app, you would generate a proper JWT token
# For this demo, we'll just generate a random token
access_token = generate_token()
return {
"access_token": access_token,
"token_type": "bearer",
}
@router.get("/me", response_model=Any)
def read_users_me(
current_user: Annotated[User, Depends(get_current_user)],
) -> Any:
"""
Get current user.
"""
return current_user