Automated Action 10f64177dc Create REST API with FastAPI and SQLite
- Set up FastAPI application with CORS and authentication
- Implement user registration and login with JWT tokens
- Create SQLAlchemy models for users and items
- Add CRUD endpoints for item management
- Configure Alembic for database migrations
- Add health check endpoint
- Include comprehensive API documentation
- Set up proper project structure with routers and schemas
2025-07-17 16:54:25 +00:00

72 lines
2.6 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from datetime import timedelta
from app.db.session import get_db
from app.models.user import User
from app.schemas.user import UserCreate, UserLogin, Token, User as UserSchema
from app.core.auth import verify_password, get_password_hash, create_access_token, verify_token
from app.core.config import settings
router = APIRouter()
security = HTTPBearer()
def get_user_by_email(db: Session, email: str):
return db.query(User).filter(User.email == email).first()
def create_user(db: Session, user: UserCreate):
hashed_password = get_password_hash(user.password)
db_user = User(email=user.email, hashed_password=hashed_password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def authenticate_user(db: Session, email: str, password: str):
user = get_user_by_email(db, email)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db)):
email = verify_token(credentials.credentials)
user = get_user_by_email(db, email)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user
@router.post("/register", response_model=UserSchema)
def register(user: UserCreate, db: Session = Depends(get_db)):
db_user = get_user_by_email(db, user.email)
if db_user:
raise HTTPException(
status_code=400,
detail="Email already registered"
)
return create_user(db, user)
@router.post("/login", response_model=Token)
def login(user_credentials: UserLogin, db: Session = Depends(get_db)):
user = authenticate_user(db, user_credentials.email, user_credentials.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"}
@router.get("/me", response_model=UserSchema)
def read_users_me(current_user: User = Depends(get_current_user)):
return current_user