All checks were successful
Deploy FluentGerman.ai / deploy (push) Successful in 49s
46 lines
1.7 KiB
Python
46 lines
1.7 KiB
Python
"""FluentGerman.ai — Auth router."""
|
|
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.auth import create_access_token, get_current_user, verify_password
|
|
from app.database import get_db
|
|
from app.models import User
|
|
from app.schemas import LoginRequest, Token, UserOut
|
|
|
|
logger = logging.getLogger("fluentgerman.auth")
|
|
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
|
|
|
|
@router.post("/login", response_model=Token)
|
|
async def login(body: LoginRequest, db: AsyncSession = Depends(get_db)):
|
|
logger.info("Login attempt: username=%s", body.username)
|
|
|
|
result = await db.execute(select(User).where(User.username == body.username))
|
|
user = result.scalar_one_or_none()
|
|
|
|
if not user:
|
|
logger.warning("Login failed: user '%s' not found", body.username)
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
|
|
|
if not verify_password(body.password, user.hashed_password):
|
|
logger.warning("Login failed: wrong password for '%s'", body.username)
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
|
|
|
if not user.is_active:
|
|
logger.warning("Login failed: account '%s' is disabled", body.username)
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account disabled")
|
|
|
|
token = create_access_token({"sub": str(user.id)})
|
|
logger.info("Login success: user=%s admin=%s", user.username, user.is_admin)
|
|
return Token(access_token=token)
|
|
|
|
|
|
@router.get("/me", response_model=UserOut)
|
|
async def me(user: User = Depends(get_current_user)):
|
|
return user
|