
- Implemented user authentication with JWT tokens - Created product management endpoints - Added shopping cart functionality - Implemented order management system - Setup database models with SQLAlchemy - Created alembic migrations - Added health check endpoint generated with BackendIM... (backend.im)
65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
from datetime import timedelta
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Body, Depends, HTTPException
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import models, schemas
|
|
from app.api import deps
|
|
from app.core import security
|
|
from app.core.config import settings
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@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 = db.query(models.User).filter(models.User.email == form_data.username).first()
|
|
if not user or not security.verify_password(form_data.password, user.password):
|
|
raise HTTPException(status_code=400, detail="Incorrect email or password")
|
|
elif not user.is_active:
|
|
raise HTTPException(status_code=400, 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.post("/register", response_model=schemas.User)
|
|
def register_user(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
user_in: schemas.UserCreate,
|
|
) -> Any:
|
|
"""
|
|
Register a new user
|
|
"""
|
|
user = db.query(models.User).filter(models.User.email == user_in.email).first()
|
|
if user:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="A user with this email already exists.",
|
|
)
|
|
|
|
hashed_password = security.get_password_hash(user_in.password)
|
|
db_user = models.User(
|
|
email=user_in.email,
|
|
password=hashed_password,
|
|
full_name=user_in.full_name,
|
|
is_active=user_in.is_active,
|
|
is_admin=user_in.is_admin,
|
|
)
|
|
db.add(db_user)
|
|
db.commit()
|
|
db.refresh(db_user)
|
|
return db_user |