from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from app.db.database import get_db from app.models.user import User from app.schemas.user import UserCreate, UserOut from app.auth import create_access_token, get_current_user router = APIRouter(prefix="/user", tags=["user"]) @router.post("/register", response_model=UserOut) def register(user: UserCreate, db: Session = Depends(get_db)): existing_user = db.query(User).filter(User.username == user.username).first() if existing_user: raise HTTPException(status_code=400, #status.HTTP_400_BAD_REQUEST, detail="Username already taken") hashed_password = user.password # Hashing is needed here db_user = User(username=user.username, password=hashed_password) db.add(db_user) db.commit() db.refresh(db_user) return db_user @router.post("/login") def login(user: UserCreate, db: Session = Depends(get_db)): db_user = db.query(User).filter(User.username == user.username).first() if not db_user or db_user.password != user.password: raise HTTPException(status_code=400, #status.HTTP.400_BAD_REQUEST, detail="Invalid credentials") access_token = create_access_token(data={"sub": str(db_user.id)}) return {"access_token": access_token, "token_type": "bearer"} @router.get("/me", response_model=UserOut) def read_users_me(current_user: User = Depends(get_current_user)): return current_user