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
This commit is contained in:
Automated Action 2025-06-24 18:40:18 +00:00
parent f1d04f9a67
commit e0cab8c417
2 changed files with 79 additions and 26 deletions

View File

@ -1,13 +1,25 @@
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
@ -34,13 +46,19 @@ class UserResponse(BaseModel):
@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,
@ -50,12 +68,23 @@ async def register(user: UserCreate, db: Session = Depends(get_db)):
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)):

26
main.py
View File

@ -2,19 +2,32 @@ from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging
from app.db.session import engine
from app.db.base import Base
from app.routes import auth, videos, transcription, translation, voice_cloning, video_processing
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
# Create database tables
logger.info("Starting application initialization...")
storage_dir = Path("/app/storage/db")
storage_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Created storage directory: {storage_dir}")
Base.metadata.create_all(bind=engine)
logger.info("Database tables created successfully")
yield
except Exception as e:
logger.error(f"Error during application startup: {e}")
raise
app = FastAPI(
@ -28,8 +41,9 @@ app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"],
expose_headers=["*"]
)
# Include routers
@ -59,6 +73,16 @@ async def health_check():
}
@app.get("/test")
async def test_endpoint():
logger.info("Test endpoint called")
return {
"message": "API is working correctly",
"timestamp": "2024-01-01T00:00:00Z",
"status": "success"
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)