
This commit includes: - Project structure and configuration - Database models for tasks, users, and categories - Authentication system with JWT - CRUD endpoints for tasks and categories - Search, filter, and sorting functionality - Health check endpoint - Alembic migration setup - Documentation
76 lines
2.1 KiB
Python
76 lines
2.1 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.core.config import settings
|
|
from app.core.database import get_db
|
|
from app.core.security import create_access_token
|
|
from app.crud.user import (
|
|
authenticate_user,
|
|
create_user,
|
|
get_user_by_email,
|
|
get_user_by_username,
|
|
)
|
|
from app.schemas.token import Token
|
|
from app.schemas.user import User, UserCreate
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/register", response_model=User)
|
|
def register(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
user_in: UserCreate,
|
|
) -> Any:
|
|
"""
|
|
Register a new user.
|
|
"""
|
|
# Check if user with this email already exists
|
|
user = get_user_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",
|
|
)
|
|
|
|
# Check if user with this username already exists
|
|
user = get_user_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",
|
|
)
|
|
|
|
# Create new user
|
|
user = create_user(db, user_in=user_in)
|
|
return user
|
|
|
|
|
|
@router.post("/login", response_model=Token)
|
|
def login_access_token(
|
|
db: Session = Depends(get_db),
|
|
form_data: OAuth2PasswordRequestForm = Depends(),
|
|
) -> Any:
|
|
"""
|
|
OAuth2 compatible token login, get an access token for future requests.
|
|
"""
|
|
user = authenticate_user(db, email=form_data.username, password=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)
|
|
return {
|
|
"access_token": create_access_token(
|
|
subject=str(user.id), expires_delta=access_token_expires
|
|
),
|
|
"token_type": "bearer",
|
|
}
|