
- Add user authentication with JWT tokens - Implement task CRUD operations with status and priority - Set up SQLite database with SQLAlchemy ORM - Create Alembic migrations for database schema - Add comprehensive API documentation - Include health check endpoint and CORS configuration - Structure codebase with proper separation of concerns
38 lines
1.4 KiB
Python
38 lines
1.4 KiB
Python
from datetime import timedelta
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
from app.db.session import get_db
|
|
from app.schemas.user import UserCreate, User, Token
|
|
from app.services.user import create_user, authenticate_user, get_user_by_email
|
|
from app.core.security import create_access_token
|
|
from app.core.config import settings
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/register", response_model=User)
|
|
def register(user: UserCreate, db: Session = Depends(get_db)):
|
|
db_user = get_user_by_email(db, email=user.email)
|
|
if db_user:
|
|
raise HTTPException(status_code=400, detail="Email already registered")
|
|
return create_user(db=db, user=user)
|
|
|
|
|
|
@router.post("/login", response_model=Token)
|
|
def login(
|
|
form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)
|
|
):
|
|
user = authenticate_user(db, form_data.username, form_data.password)
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect email or password",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
|
|
access_token = create_access_token(
|
|
data={"sub": user.email}, expires_delta=access_token_expires
|
|
)
|
|
return {"access_token": access_token, "token_type": "bearer"}
|