44 lines
1.8 KiB
Python
44 lines
1.8 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.dependencies import get_db
|
|
from app.schemas.auth import LoginRequest, LogoutRequest, RefreshRequest, TokenResponse
|
|
from app.services import auth as auth_service
|
|
|
|
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
|
|
|
|
|
@router.post("/login", response_model=TokenResponse)
|
|
async def login(body: LoginRequest, request: Request, db: AsyncSession = Depends(get_db)):
|
|
user = await auth_service.authenticate_user(db, body.username, body.password)
|
|
if user is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
|
|
|
access_token = auth_service.create_access_token(user.id)
|
|
refresh_token = await auth_service.create_session(
|
|
db,
|
|
user.id,
|
|
ip_address=request.client.host if request.client else None,
|
|
user_agent=request.headers.get("User-Agent"),
|
|
)
|
|
return TokenResponse(access_token=access_token, refresh_token=refresh_token)
|
|
|
|
|
|
@router.post("/refresh", response_model=TokenResponse)
|
|
async def refresh(body: RefreshRequest, request: Request, db: AsyncSession = Depends(get_db)):
|
|
result = await auth_service.refresh_session(
|
|
db,
|
|
body.refresh_token,
|
|
ip_address=request.client.host if request.client else None,
|
|
)
|
|
if result is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired refresh token")
|
|
|
|
user, new_refresh_token = result
|
|
access_token = auth_service.create_access_token(user.id)
|
|
return TokenResponse(access_token=access_token, refresh_token=new_refresh_token)
|
|
|
|
|
|
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
|
async def logout(body: LogoutRequest, db: AsyncSession = Depends(get_db)):
|
|
await auth_service.revoke_session(db, body.refresh_token)
|