feat(auth): Add endpoint to get user info by token and fix imports
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
@@ -1,14 +1,22 @@
|
|||||||
from fastapi import APIRouter, HTTPException, status
|
from fastapi import APIRouter, HTTPException, status, Depends
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
import httpx
|
import httpx
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
from app.core.config import settings
|
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()
|
router = APIRouter()
|
||||||
|
bearer_scheme = HTTPBearer()
|
||||||
|
|
||||||
YANDEX_TOKEN_URL = "https://oauth.yandex.ru/token"
|
YANDEX_TOKEN_URL = "https://oauth.yandex.ru/token"
|
||||||
|
# --- ДОБАВЛЕНО ДЛЯ НОВОГО ЭНДПОИНТА ---
|
||||||
|
YANDEX_USERINFO_URL = "https://login.yandex.ru/info"
|
||||||
|
|
||||||
@router.post("/token", response_model=TokenResponse, summary="Обмен кода авторизации на токен доступа")
|
@router.post("/token", response_model=TokenResponse, summary="Обмен кода авторизации на токен доступа")
|
||||||
async def exchange_code_for_token(request: TokenRequest):
|
async def exchange_code_for_token(request: TokenRequest):
|
||||||
@@ -28,12 +36,11 @@ async def exchange_code_for_token(request: TokenRequest):
|
|||||||
try:
|
try:
|
||||||
async with httpx.AsyncClient() as client:
|
async with httpx.AsyncClient() as client:
|
||||||
response = await client.post(YANDEX_TOKEN_URL, data=payload)
|
response = await client.post(YANDEX_TOKEN_URL, data=payload)
|
||||||
response.raise_for_status() # Вызовет ошибку для статусов 4xx/5xx
|
response.raise_for_status()
|
||||||
|
|
||||||
token_data = response.json()
|
token_data = response.json()
|
||||||
logger.success("Successfully received access token from Yandex.")
|
logger.success("Successfully received access token from Yandex.")
|
||||||
|
|
||||||
# Возвращаем только нужные нам поля
|
|
||||||
return TokenResponse(
|
return TokenResponse(
|
||||||
access_token=token_data.get("access_token"),
|
access_token=token_data.get("access_token"),
|
||||||
token_type=token_data.get("token_type", "bearer")
|
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."
|
detail="An internal server error occurred."
|
||||||
)
|
)
|
||||||
|
|
||||||
# Получает информацию о пользователе Яндекса
|
# --- НОВЫЙ ЭНДПОИНТ ---
|
||||||
@router.get("/userinfo", response_model=UserInfoResponse, summary="Получение информации о пользователе")
|
@router.get("/userinfo", response_model=UserInfoResponse, summary="Получение информации о пользователе")
|
||||||
async def get_user_info(credentials: Annotated[HTTPAuthorizationCredentials, Depends(bearer_scheme)]):
|
async def get_user_info(credentials: Annotated[HTTPAuthorizationCredentials, Depends(bearer_scheme)]):
|
||||||
|
"""
|
||||||
|
Используя access_token, получает информацию о пользователе Яндекса.
|
||||||
|
Токен должен быть передан в заголовке 'Authorization: Bearer <token>'.
|
||||||
|
"""
|
||||||
token = credentials.credentials
|
token = credentials.credentials
|
||||||
headers = {'Authorization': f'OAuth {token}'}
|
headers = {'Authorization': f'OAuth {token}'}
|
||||||
|
|
||||||
|
|||||||
0
tests/test_auth.py
Normal file
0
tests/test_auth.py
Normal file
Reference in New Issue
Block a user