Automated Action e0cab8c417 Add comprehensive error handling and debugging for signup issues
- Enhanced CORS configuration with explicit methods and headers
- Added detailed logging for registration attempts and errors
- Added test endpoints for debugging connectivity issues
- Improved error handling in registration with proper rollback
- Added startup logging for better debugging
2025-06-24 18:40:18 +00:00

100 lines
2.8 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr
import logging
from app.db.session import get_db
from app.models.user import User
from app.utils.auth import get_password_hash, verify_password, create_access_token
logger = logging.getLogger(__name__)
router = APIRouter()
@router.get("/test")
async def test_auth():
logger.info("Auth test endpoint called")
return {
"message": "Auth router is working",
"status": "success"
}
class UserCreate(BaseModel):
email: EmailStr
password: str
class UserLogin(BaseModel):
email: EmailStr
password: str
class Token(BaseModel):
access_token: str
token_type: str
class UserResponse(BaseModel):
id: int
email: str
created_at: str
class Config:
orm_mode = True
@router.post("/register", response_model=UserResponse)
async def register(user: UserCreate, db: Session = Depends(get_db)):
try:
logger.info(f"Registration attempt for email: {user.email}")
# Check if user already exists
db_user = db.query(User).filter(User.email == user.email).first()
if db_user:
logger.warning(f"Registration failed - email already exists: {user.email}")
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email already registered"
)
# Hash password and create user
hashed_password = get_password_hash(user.password)
db_user = User(
email=user.email,
password_hash=hashed_password
)
db.add(db_user)
db.commit()
db.refresh(db_user)
logger.info(f"User registered successfully: {user.email}")
return UserResponse(
id=db_user.id,
email=db_user.email,
created_at=str(db_user.created_at)
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Registration error for {user.email}: {str(e)}")
db.rollback()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error during registration"
)
@router.post("/login", response_model=Token)
async def login(user: UserLogin, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.email == user.email).first()
if not db_user or not verify_password(user.password, db_user.password_hash):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(data={"sub": db_user.email})
return {"access_token": access_token, "token_type": "bearer"}