Initial clean commit of the project
This commit is contained in:
54
app/api/v1/endpoints/auth.py
Normal file
54
app/api/v1/endpoints/auth.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi.responses import JSONResponse
|
||||
import httpx
|
||||
from loguru import logger
|
||||
|
||||
from app.core.config import settings
|
||||
from app.api.v1.schemas.auth import TokenRequest, TokenResponse
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
YANDEX_TOKEN_URL = "https://oauth.yandex.ru/token"
|
||||
|
||||
@router.post("/token", response_model=TokenResponse, summary="Обмен кода авторизации на токен доступа")
|
||||
async def exchange_code_for_token(request: TokenRequest):
|
||||
"""
|
||||
Принимает временный 'code' от фронтенда, обменивает его на 'access_token'
|
||||
у Яндекса и возвращает токен клиенту.
|
||||
"""
|
||||
logger.info("Attempting to exchange authorization code for an access token.")
|
||||
|
||||
payload = {
|
||||
'grant_type': 'authorization_code',
|
||||
'code': request.code,
|
||||
'client_id': settings.YANDEX_CLIENT_ID,
|
||||
'client_secret': settings.YANDEX_CLIENT_SECRET
|
||||
}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(YANDEX_TOKEN_URL, data=payload)
|
||||
response.raise_for_status() # Вызовет ошибку для статусов 4xx/5xx
|
||||
|
||||
token_data = response.json()
|
||||
logger.success("Successfully received access token from Yandex.")
|
||||
|
||||
# Возвращаем только нужные нам поля
|
||||
return TokenResponse(
|
||||
access_token=token_data.get("access_token"),
|
||||
token_type=token_data.get("token_type", "bearer")
|
||||
)
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
error_details = e.response.json()
|
||||
logger.error(f"Yandex OAuth error: {e.response.status_code} - {error_details}")
|
||||
raise HTTPException(
|
||||
status_code=e.response.status_code,
|
||||
detail=f"Yandex OAuth error: {error_details.get('error_description', 'Unknown error')}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.opt(exception=True).error("An unexpected error occurred during token exchange.")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="An internal server error occurred."
|
||||
)
|
||||
Reference in New Issue
Block a user