feat(auth): Add endpoint to get user info by token and fix imports
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2025-08-24 22:26:27 +01:00
parent 8047844ad4
commit 37ebd8f694
2 changed files with 16 additions and 6 deletions

View File

@@ -1,14 +1,22 @@
from fastapi import APIRouter, HTTPException, status
from fastapi import APIRouter, HTTPException, status, Depends
from fastapi.responses import JSONResponse
import httpx
from loguru import logger
from typing import Annotated
from app.core.config import settings
from app.api.v1.schemas.auth import TokenRequest, TokenResponse
# ИСПРАВЛЕНИЕ ЗДЕСЬ
from app.api.v1.schemas.auth import TokenRequest, TokenResponse, UserInfoResponse
# --- ДОБАВЛЕНО ДЛЯ НОВОГО ЭНДПОИНТА ---
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
router = APIRouter()
bearer_scheme = HTTPBearer()
YANDEX_TOKEN_URL = "https://oauth.yandex.ru/token"
# --- ДОБАВЛЕНО ДЛЯ НОВОГО ЭНДПОИНТА ---
YANDEX_USERINFO_URL = "https://login.yandex.ru/info"
@router.post("/token", response_model=TokenResponse, summary="Обмен кода авторизации на токен доступа")
async def exchange_code_for_token(request: TokenRequest):
@@ -28,12 +36,11 @@ async def exchange_code_for_token(request: TokenRequest):
try:
async with httpx.AsyncClient() as client:
response = await client.post(YANDEX_TOKEN_URL, data=payload)
response.raise_for_status() # Вызовет ошибку для статусов 4xx/5xx
response.raise_for_status()
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")
@@ -53,10 +60,13 @@ async def exchange_code_for_token(request: TokenRequest):
detail="An internal server error occurred."
)
# Получает информацию о пользователе Яндекса
# --- НОВЫЙ ЭНДПОИНТ ---
@router.get("/userinfo", response_model=UserInfoResponse, summary="Получение информации о пользователе")
async def get_user_info(credentials: Annotated[HTTPAuthorizationCredentials, Depends(bearer_scheme)]):
"""
Используя access_token, получает информацию о пользователе Яндекса.
Токен должен быть передан в заголовке 'Authorization: Bearer <token>'.
"""
token = credentials.credentials
headers = {'Authorization': f'OAuth {token}'}