Automated Action 8fefbb7c13 Add user authentication to the Todo app
- Created User model and schemas
- Implemented secure password hashing with bcrypt
- Added JWT token-based authentication
- Created user registration and login endpoints
- Added authentication to todo routes
- Updated todos to be associated with users
- Created migration script for the user table
- Updated documentation with auth information
2025-05-19 13:45:22 +00:00

78 lines
2.3 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 import crud, models, schemas
from app.api import deps
from app.core import security
from app.core.config import settings
router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/register", response_model=schemas.User)
def register(
*,
db: Session = Depends(deps.get_db),
user_in: schemas.UserCreate,
) -> Any:
"""
Register a new user
"""
# Check if user with same email exists
user = crud.user.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",
)
# Check if user with same username exists
user = crud.user.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",
)
# Create the user
user = crud.user.create(db, obj_in=user_in)
return user
@router.post("/login", response_model=schemas.Token)
def login_access_token(
db: Session = Depends(deps.get_db),
form_data: OAuth2PasswordRequestForm = Depends(),
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = crud.user.authenticate(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",
)
if not crud.user.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": security.create_access_token(user.id, expires_delta=access_token_expires),
"token_type": "bearer",
}
@router.get("/me", response_model=schemas.User)
def read_users_me(
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get current user
"""
return current_user