Added and fixed Create auction API endpoint. Added middleware, session-based authentication and logout endpoint
This commit is contained in:
127
app/routers/auctions.py
Normal file
127
app/routers/auctions.py
Normal file
@ -0,0 +1,127 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
from ..models import Auction, Vehicle, VehicleEquipment, Equipment, User
|
||||
from ..database import get_db
|
||||
from ..security import verify_access_token # Ensure this is imported correctly
|
||||
from fastapi.logger import logger
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Define Pydantic models for data validation
|
||||
|
||||
class VehicleCreate(BaseModel):
|
||||
brand: str
|
||||
model: str
|
||||
variant: Optional[str]
|
||||
year: int
|
||||
kilometers: int
|
||||
condition: str
|
||||
location: str
|
||||
latitude: Optional[float]
|
||||
longitude: Optional[float]
|
||||
gasType: str
|
||||
images: str
|
||||
description: str
|
||||
service: str
|
||||
inspectedAt: Optional[str] # ISO format for datetime
|
||||
equipment_ids: List[int] # List of equipment IDs
|
||||
|
||||
|
||||
class AuctionCreate(BaseModel):
|
||||
askingPrice: float
|
||||
description: Optional[str]
|
||||
vehicle: VehicleCreate
|
||||
|
||||
async def get_current_user_id(request: Request, db: AsyncSession = Depends(get_db)):
|
||||
user_id = verify_access_token(request)
|
||||
|
||||
# Fetch user from database to check their role
|
||||
result = await db.execute(select(User).filter(User.id == user_id))
|
||||
user = result.scalars().first()
|
||||
#print(f"\n user " + str(user.role))
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found."
|
||||
)
|
||||
|
||||
if not user.role.PRIVATE: # Only allow private users to create auctions
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only private users can create an auction."
|
||||
)
|
||||
|
||||
logger.info(f"\nCurrent user ID: {user.id}\n Current user role: {user.role}\n")
|
||||
#logger.debug(f"\nCurrent user ID: {user.id}\n Current user role: {user.role}\n")
|
||||
return user.id
|
||||
|
||||
|
||||
# API route to create an auction
|
||||
@router.post("/api/v1/test")
|
||||
async def testFuncForDB(request: Request,user_id: int = Depends(get_current_user_id), db: AsyncSession = Depends(get_db)):
|
||||
print("HIIIIIIIIIIIIIIIIIIT")
|
||||
result = await db.execute(select(User).filter(User.id == user_id))
|
||||
user = result.scalars().first()
|
||||
if user:
|
||||
email = user.email
|
||||
else:
|
||||
email = "User not found"
|
||||
|
||||
return {"message": "Test function for DB", "email": email}
|
||||
|
||||
|
||||
# API route to create an auction
|
||||
@router.post("/api/v1/auction")
|
||||
async def create_auction(auction_data: AuctionCreate, db: AsyncSession = Depends(get_db), user_id: int = Depends(get_current_user_id)):
|
||||
# Create Vehicle
|
||||
vehicle_data = auction_data.vehicle
|
||||
vehicle = Vehicle(
|
||||
brand=vehicle_data.brand,
|
||||
model=vehicle_data.model,
|
||||
variant=vehicle_data.variant,
|
||||
year=vehicle_data.year,
|
||||
kilometers=vehicle_data.kilometers,
|
||||
condition=vehicle_data.condition,
|
||||
location=vehicle_data.location,
|
||||
latitude=vehicle_data.latitude,
|
||||
longitude=vehicle_data.longitude,
|
||||
gasType=vehicle_data.gasType,
|
||||
images=vehicle_data.images,
|
||||
description=vehicle_data.description,
|
||||
service=vehicle_data.service,
|
||||
inspectedAt=vehicle_data.inspectedAt,
|
||||
)
|
||||
|
||||
# Add vehicle to the database
|
||||
db.add(vehicle)
|
||||
await db.commit()
|
||||
await db.refresh(vehicle)
|
||||
|
||||
# Add vehicle equipment
|
||||
for equipment_id in vehicle_data.equipment_ids:
|
||||
result = await db.execute(select(Equipment).filter(Equipment.id == equipment_id))
|
||||
equipment = result.scalars().first()
|
||||
if not equipment:
|
||||
raise HTTPException(status_code=404, detail=f"Equipment with ID {equipment_id} not found")
|
||||
vehicle_equipment = VehicleEquipment(vehicle_id=vehicle.id, equipment_id=equipment.id)
|
||||
db.add(vehicle_equipment)
|
||||
|
||||
# Create Auction
|
||||
auction = Auction(
|
||||
vehicleId=vehicle.id,
|
||||
userId=user_id, # This comes from the authenticated user
|
||||
askingPrice=auction_data.askingPrice,
|
||||
description=auction_data.description,
|
||||
)
|
||||
|
||||
# Add auction to the database
|
||||
db.add(auction)
|
||||
await db.commit()
|
||||
await db.refresh(auction)
|
||||
|
||||
return {"message": "Auction created successfully", "auction": auction, "vehicle": vehicle}
|
||||
Reference in New Issue
Block a user