from fastapi import APIRouter, Depends, HTTPException, status, BackgroundTasks from fastapi.security import OAuth2PasswordRequestForm from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from datetime import timedelta from app.db.session import get_db from app.models.user import User from app.core.security import get_password_hash, verify_password, create_access_token from app.core.email import send_verification_email import os router = APIRouter() @router.post("/register", status_code=status.HTTP_201_CREATED) async def register( background_tasks: BackgroundTasks, email: str, password: str, full_name: str, db: AsyncSession = Depends(get_db) ): # Email ellenőrzés res = await db.execute(select(User).where(User.email == email)) if res.scalars().first(): raise HTTPException(status_code=400, detail="Ez az email már foglalt") new_user = User( email=email, password_hash=get_password_hash(password), full_name=full_name, is_active=False # Aktiválásig inaktív ) db.add(new_user) await db.commit() # Aktiváló token (egyszerűség kedvéért most a JWT-t használjuk tokenként) token = create_access_token(data={"sub": email}, expires_delta=timedelta(hours=24)) send_verification_email(background_tasks, email, token) return {"message": "Sikeres regisztráció! Ellenőrizd az email fiókodat az aktiváláshoz."} @router.get("/verify/{token}") async def verify_account(token: str, db: AsyncSession = Depends(get_db)): try: payload = jwt.decode(token, os.getenv("SECRET_KEY"), algorithms=[os.getenv("ALGORITHM")]) email = payload.get("sub") except: raise HTTPException(status_code=400, detail="Érvénytelen vagy lejárt token") result = await db.execute(select(User).where(User.email == email)) user = result.scalars().first() if not user: raise HTTPException(status_code=404, detail="Felhasználó nem található") user.is_active = True await db.commit() return {"message": "Fiók sikeresen aktiválva!"} @router.post("/login") async def login( form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db) ): result = await db.execute(select(User).where(User.email == form_data.username)) user = result.scalars().first() if not user or not verify_password(form_data.password, user.password_hash): raise HTTPException(status_code=400, detail="Hibás email vagy jelszó") if not user.is_active: raise HTTPException(status_code=400, detail="Kérjük, aktiváld a fiókodat az emailben küldött linken") access_token = create_access_token(data={"sub": user.email}) return {"access_token": access_token, "token_type": "bearer"}