Automated Action 16cfcd783e Build Chat Application Backend with FastAPI and SQLite
- Set up project structure with FastAPI and SQLite
- Implement user authentication using JWT
- Create database models for users, conversations, and messages
- Implement API endpoints for user management and chat functionality
- Set up WebSocket for real-time messaging
- Add database migrations with Alembic
- Create health check endpoint
- Update README with comprehensive documentation

generated with BackendIM... (backend.im)
2025-05-12 16:37:35 +00:00

81 lines
2.4 KiB
Python

from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app.api.dependencies.auth import get_current_user
from app.core.config import settings
from app.core.security import create_access_token
from app.db.repositories.user import user_repository
from app.db.session import get_db
from app.models.user import User
from app.schemas.token import Token
from app.schemas.user import User as UserSchema, UserCreate
router = APIRouter(tags=["authentication"])
@router.post("/auth/login", response_model=Token)
def login(
db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
) -> Any:
"""
Get the JWT for a user with data from OAuth2 request form body.
"""
user = user_repository.authenticate(
db, email=form_data.username, password=form_data.password
)
if not user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Incorrect email or password",
)
if not user_repository.is_active(user):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Inactive user",
)
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return {
"access_token": create_access_token(user.id, expires_delta=access_token_expires),
"token_type": "bearer",
}
@router.post("/auth/signup", response_model=UserSchema)
def create_user(
*,
db: Session = Depends(get_db),
user_in: UserCreate,
) -> Any:
"""
Create new user.
"""
user = user_repository.get_by_email(db, email=user_in.email)
if user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A user with this email already exists",
)
user = user_repository.get_by_username(db, username=user_in.username)
if user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A user with this username already exists",
)
user = user_repository.create(db, obj_in=user_in)
return user
@router.get("/auth/me", response_model=UserSchema)
def read_users_me(
current_user: User = Depends(get_current_user),
) -> Any:
"""
Get current user.
"""
return current_user