
This commit includes: - Project structure setup with FastAPI - Database models with SQLAlchemy (users, products, categories, orders) - SQLite database configuration - Alembic migration scripts - API endpoints for authentication, users, products, categories, and orders - JWT authentication - Comprehensive documentation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
71 lines
2.0 KiB
Python
71 lines
2.0 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.deps import get_db
|
|
from app.core.config import settings
|
|
from app.core.security import create_access_token
|
|
from app.crud.user import user
|
|
from app.schemas.user import Token, User, UserCreate
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@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.
|
|
"""
|
|
auth_user = user.authenticate(
|
|
db, email=form_data.username, password=form_data.password
|
|
)
|
|
if not auth_user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect email or password",
|
|
)
|
|
if not user.is_active(auth_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(
|
|
auth_user.id, expires_delta=access_token_expires
|
|
),
|
|
"token_type": "bearer",
|
|
}
|
|
|
|
|
|
@router.post("/register", response_model=User)
|
|
def register_new_user(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
user_in: UserCreate,
|
|
) -> Any:
|
|
"""
|
|
Create new user.
|
|
"""
|
|
db_user = user.get_by_email(db, email=user_in.email)
|
|
if db_user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Email already registered",
|
|
)
|
|
|
|
db_user = user.get_by_username(db, username=user_in.username)
|
|
if db_user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Username already registered",
|
|
)
|
|
|
|
return user.create(db, obj_in=user_in) |