first commit

This commit is contained in:
bluebamus committed 2025-10-31 15:56:42 +09:00
1 parent 78da3838f0
commit 09c86adf7b
486 files changed
+47300

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
from pydantic import BaseModel
from typing import Optional
class TokenRequest(BaseModel):
access_token: str
refresh_token: Optional[str] = None
+134
View File
@@ -0,0 +1,134 @@
import uuid
from typing import Dict, Optional
from datetime import datetime, timezone
from fastapi import HTTPException
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from .utils import load_client_config
from .redis import RedisOAuthStorage, get_oauth_storage
class OAuthService:
def __init__(self, oauth_storage: RedisOAuthStorage):
self.oauth_storage = oauth_storage
self.scopes = [
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"openid"
]
self.client_secret = "client_secret.json"
self.redirect_uri = "http://localhost:8000/social/google/callback"
async def login_url(self, return_url: Optional[str] = None):
'''Google OAuth 로그인 URL 생성'''
try:
client_config = load_client_config(self.client_secret)
flow = Flow.from_client_config(
client_config,
scopes=self.scopes,
redirect_uri=self.redirect_uri
)
# 고유한 state 생성 ( CSRF 공격 방지 )
state = str(uuid.uuid4())
# Redis에 flow 데이터 저장 (return_url 포함)
flow_data = {
"client_config": client_config,
"scopes": self.scopes,
"redirect_uri": self.redirect_uri,
"return_url": return_url,
"created_at": datetime.now(timezone.utc).isoformat()
}
await self.oauth_storage.store_oauth_state(state, flow_data)
# 인증 URL 생성
auth_url, _ = flow.authorization_url(
access_type="offline",
include_granted_scopes="true",
state=state,
prompt='consent'
)
return {
"auth_url": auth_url,
"state": state,
"return_url": return_url,
"message": "Google 로그인 URL이 생성되었습니다."
}
except Exception as e:
print(f"Google OAuth URL 생성 오류: {e}")
raise HTTPException(
status_code=500,
detail=f"Google OAuth URL 생성 오류: {str(e)}"
)
async def callback(self, state: str, code: str):
'''Google OAuth 콜백 처리'''
# Redis에서 flow 데이터 조회
flow_data = await self.oauth_storage.get_oauth_state(state)
if not flow_data:
raise HTTPException(400, "유효하지 않은 state 토큰입니다.")
try:
# Flow 재생성
flow = Flow.from_client_config(
flow_data["client_config"],
scopes=flow_data["scopes"],
redirect_uri=flow_data["redirect_uri"]
)
# 인증 코드로 토큰 교환
flow.fetch_token(code=code)
credentials = flow.credentials
# 사용자 정보 가져오기
user_info = self._get_user_info(credentials)
# 토큰 데이터 준비
token_data = {
"access_token": credentials.token,
"refresh_token": credentials.refresh_token,
"expires_at": credentials.expiry.isoformat() if credentials.expiry else None,
"scopes": credentials.scopes,
"user_info": user_info,
"return_url": flow_data.get("return_url")
}
# 임시 토큰 ID 생성하여 저장
temp_token_id = str(uuid.uuid4())
await self.oauth_storage.store_temp_token(temp_token_id, token_data)
return {
"message": "Google 로그인 성공",
"temp_token_id": temp_token_id,
"return_url": flow_data.get("return_url"),
"user_info": user_info,
"credentials": {
"access_token": credentials.token,
"refresh_token": credentials.refresh_token,
"expires_at": credentials.expiry.isoformat() if credentials.expiry else None,
"scopes": credentials.scopes
}
}
except Exception as e:
raise HTTPException(status_code=400, detail=f"Google 인증 처리 오류: {str(e)}")
def _get_user_info(self, credentials):
'''Google 사용자 정보 조회'''
try:
service = build('oauth2', 'v2', credentials=credentials)
user_info = service.userinfo().get().execute()
return user_info
except Exception as e:
print(f"사용자 정보 조회 실패: {e}")
return {"error": "사용자 정보 조회 실패"}
async def get_token_by_temp_id(self, temp_token_id: str):
'''임시 토큰 ID로 실제 토큰 정보 조회'''
token_data = await self.oauth_storage.get_temp_token(temp_token_id)
if not token_data:
raise HTTPException(400, "유효하지 않은 토큰 ID입니다.")
return token_data
+128
View File
@@ -0,0 +1,128 @@
import redis.asyncio as redis
import json
from typing import Optional, Dict, Any
from datetime import timedelta
from app.core.env_setting import EnvSetting
settings = EnvSetting()
class RedisManager:
def __init__(self, redis_url: Optional[str] = None):
self.redis_url = redis_url or settings.RedisManager_URL
self.client : Optional[redis.Redis] = None
async def connect(self):
'''Redis 연결'''
if self.client is None:
self.client = redis.from_url(
self.redis_url,
encoding="utf-8",
decode_responses=True,
max_connections=20,
socket_connect_timeout=5,
socket_timeout=5,
)
return self.client
async def close(self):
'''Redis 연결 종료'''
if self.client:
await self.client.close()
self.client = None
async def get_client(self) -> redis.Redis:
'''Redis 클라이언트 반환'''
if self.client is None:
await self.connect()
return self.client
class RedisOAuthStorage:
"""OAuth 관련 Redis 저장소"""
def __init__(self, redis_manager: RedisManager):
self.redis_manager = redis_manager
self.state_prefix = "oauth:state:"
self.temp_token_prefix = "oauth:temp_token:"
self.updated_token_prefix = "oauth:updated_token:"
async def store_oauth_state(self, state: str, flow_data: Dict[str, Any], ttl: int = 600):
"""OAuth 상태 저장 (기본 10분 TTL)"""
client = await self.redis_manager.get_client()
key = f"{self.state_prefix}{state}"
await client.setex(key, ttl, json.dumps(flow_data))
async def get_oauth_state(self, state: str) -> Optional[Dict[str, Any]]:
"""OAuth 상태 조회 및 삭제"""
client = await self.redis_manager.get_client()
key = f"{self.state_prefix}{state}"
data = await client.get(key)
if data:
await client.delete(key) # 일회용이므로 삭제
return json.loads(data)
return None
async def store_temp_token(self, temp_token_id: str, token_data: Dict[str, Any], ttl: int = 3600):
"""임시 토큰 저장 (기본 1시간 TTL)"""
client = await self.redis_manager.get_client()
key = f"{self.temp_token_prefix}{temp_token_id}"
await client.setex(key, ttl, json.dumps(token_data))
async def get_temp_token(self, temp_token_id: str) -> Optional[Dict[str, Any]]:
"""임시 토큰 조회 및 삭제"""
client = await self.redis_manager.get_client()
key = f"{self.temp_token_prefix}{temp_token_id}"
data = await client.get(key)
if data:
await client.delete(key) # 일회용이므로 삭제
return json.loads(data)
return None
async def store_updated_token(self, token_key: str, token_data: Dict[str, Any], ttl: int = 3600):
"""갱신된 토큰 저장"""
client = await self.redis_manager.get_client()
key = f"{self.updated_token_prefix}{token_key}"
await client.setex(key, ttl, json.dumps(token_data))
class RedisYouTubeStorage:
"""YouTube 관련 Redis 저장소"""
def __init__(self, redis_manager: RedisManager):
self.redis_manager = redis_manager
self.channels_prefix = "youtube:channels:"
self.service_prefix = "youtube:service:"
async def get_cached_channels(self, cache_key: str) -> Optional[Dict[str, Any]]:
"""캐시된 채널 정보 조회"""
client = await self.redis_manager.get_client()
key = f"{self.channels_prefix}{cache_key}"
data = await client.get(key)
if data:
return json.loads(data)
return None
async def cache_channels(self, cache_key: str, channels_data: Dict[str, Any], ttl: int = 1800):
"""채널 정보 캐싱 (기본 30분 TTL)"""
client = await self.redis_manager.get_client()
key = f"{self.channels_prefix}{cache_key}"
await client.setex(key, ttl, json.dumps(channels_data))
# 전역 Redis 매니저 인스턴스
redis_manager = RedisManager()
oauth_storage = RedisOAuthStorage(redis_manager)
youtube_storage = RedisYouTubeStorage(redis_manager)
async def get_redis_manager() -> RedisManager:
"""Redis 매니저 의존성"""
return redis_manager
async def get_oauth_storage() -> RedisOAuthStorage:
"""OAuth 저장소 의존성"""
return oauth_storage
async def get_youtube_storage() -> RedisYouTubeStorage:
"""YouTube 저장소 의존성"""
return youtube_storage
+56
View File
@@ -0,0 +1,56 @@
from fastapi import APIRouter, Query, Depends
from fastapi.responses import RedirectResponse
from typing import Optional
from .dto import TokenRequest
from .service import GoogleService, get_google_service
router = APIRouter()
@router.get("/social/google/login")
async def get_google_auth_url(
return_url: str = Query(..., description="로그인 후 돌아갈 URL"),
google_service: GoogleService = Depends(get_google_service)
):
"""Google OAuth 로그인 URL 생성"""
return await google_service.login_url(return_url)
@router.get("/social/google/callback")
async def handle_google_callback(
code: str = Query(..., description="Google에서 제공하는 인증 코드"),
state: str = Query(..., description="CSRF 보호용 state 파라미터"),
error: Optional[str] = Query(None, description="Google 인증 에러"),
google_service: GoogleService = Depends(get_google_service)
):
"""Google OAuth 콜백 처리 후 FE로 리다이렉트"""
if error:
# 에러 시 FE 에러 페이지로
return RedirectResponse(url=f"http://localhost:3300/auth/error?error={error}")
try:
result = await google_service.callback(state, code)
temp_token_id = result["temp_token_id"]
return_url = result.get("return_url")
print(f"return_url: {return_url}")
# 성공 시 FE 성공 페이지로 temp_token_id와 함께 리다이렉트
return RedirectResponse(url=f"{return_url}?token={temp_token_id}")
except Exception as e:
# 처리 실패 시 FE 에러 페이지로
return RedirectResponse(url=f"{return_url}?message={str(e)}")
@router.get("/social/google/token/{temp_token_id}")
async def get_token_info(
temp_token_id: str,
google_service: GoogleService = Depends(get_google_service)
):
"""임시 토큰 ID로 실제 토큰 정보 조회"""
return await google_service.get_token_info(temp_token_id)
@router.post("/youtube/channel/info")
async def get_youtube_channel_info(
req: TokenRequest,
google_service: GoogleService = Depends(get_google_service)
):
"""사용자의 YouTube 채널 정보 조회"""
return await google_service.get_all_youtube_channel_info(req.access_token, req.refresh_token)
+34
View File
@@ -0,0 +1,34 @@
from typing import Optional
from fastapi import Depends
from .oauth import OAuthService
from .youtube import YoutubeService
from .redis import RedisOAuthStorage, RedisYouTubeStorage, get_oauth_storage, get_youtube_storage
class GoogleService:
'''Google 통합 관리 서비스'''
def __init__(self, oauth_storage: RedisOAuthStorage, youtube_storage: RedisYouTubeStorage):
self.oauth = OAuthService(oauth_storage)
self.youtube = YoutubeService(youtube_storage, oauth_storage)
async def login_url(self, return_url: str):
'''Google OAuth 로그인 URL 생성'''
return await self.oauth.login_url(return_url)
async def callback(self, state: str, code: str):
'''Google OAuth 콜백 처리'''
return await self.oauth.callback(state, code)
async def get_token_info(self, temp_token_id: str):
'''임시 토큰 ID로 토큰 정보 조회'''
return await self.oauth.get_token_by_temp_id(temp_token_id)
async def get_all_youtube_channel_info(self, access_token: str, refresh_token: Optional[str] = None):
'''YouTube 모든 채널 정보 조회'''
return await self.youtube.get_all_channel_info(access_token, refresh_token)
# GoogleService 의존성 주입
async def get_google_service(
oauth_storage: RedisOAuthStorage = Depends(get_oauth_storage),
youtube_storage: RedisYouTubeStorage = Depends(get_youtube_storage)
) -> GoogleService:
return GoogleService(oauth_storage, youtube_storage)
+16
View File
@@ -0,0 +1,16 @@
import json
import os
from fastapi import HTTPException
def load_client_config(client_secret_path: str = None):
if client_secret_path is None:
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
client_secret_path = os.path.join(base_dir, "client_secret.json")
try:
with open(client_secret_path, "r") as f:
return json.load(f)
except FileNotFoundError:
raise HTTPException(500, f"client_secret.json 파일을 찾을 수 없습니다. 경로: {client_secret_path}")
except json.JSONDecodeError:
raise HTTPException(500, f"client_secret.json 형식 오류. 경로: {client_secret_path}")
+117
View File
@@ -0,0 +1,117 @@
import json
from typing import Optional
from fastapi import HTTPException, Depends
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request as GoogleRequest
from .utils import load_client_config
from .redis import RedisYouTubeStorage, RedisOAuthStorage, get_youtube_storage, get_oauth_storage
class YoutubeService:
def __init__(self, youtube_storage: RedisYouTubeStorage, oauth_storage: RedisOAuthStorage):
self.youtube_storage = youtube_storage
self.oauth_storage = oauth_storage
self.scopes = [
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"openid"
]
self.client_secret = "client_secret.json"
async def _create_youtube_service(self, access_token: str, refresh_token: Optional[str] = None):
'''YouTube API 서비스 생성'''
try:
client_config = load_client_config(self.client_secret)
# Credentials 객체 생성
credentials = Credentials(
token=access_token,
refresh_token=refresh_token,
token_uri="https://oauth2.googleapis.com/token",
client_id=client_config["web"]["client_id"],
client_secret=client_config["web"]["client_secret"],
scopes=self.scopes
)
# 토큰 만료 시 자동 갱신
if credentials.expired and credentials.refresh_token:
credentials.refresh(GoogleRequest())
# 갱신된 토큰을 Redis에 저장
updated_token_data = {
"access_token": credentials.token,
"refresh_token": credentials.refresh_token,
"expires_at": credentials.expiry.isoformat() if credentials.expiry else None
}
await self.oauth_storage.store_updated_token(access_token[:10], updated_token_data)
# YouTube API 서비스 생성
youtube = build('youtube', 'v3', credentials=credentials)
return youtube
except Exception as e:
raise HTTPException(status_code=401, detail=f"YouTube 서비스 생성 오류: {str(e)}")
async def get_all_channel_info(self, access_token: str, refresh_token: Optional[str] = None):
'''YouTube 모든 채널 정보 조회'''
try:
# 캐시 키 생성
cache_key = access_token[:10]
# 캐시된 데이터 확인
cached_data = await self.youtube_storage.get_cached_channels(cache_key)
if cached_data:
return cached_data
youtube = await self._create_youtube_service(access_token, refresh_token)
# 내 채널 정보 조회
response = youtube.channels().list(
part='snippet,statistics,contentDetails',
mine=True
).execute()
if not response.get('items'):
raise HTTPException(status_code=404, detail="YouTube 채널을 찾을 수 없습니다. YouTube 채널을 먼저 생성해주세요.")
# 모든 채널 정보를 리스트로 반환
channels = []
for channel in response['items']:
channel_info = {
"channel_id": channel['id'],
"channel_title": channel['snippet']['title'],
"description": channel['snippet']['description'],
"custom_url": channel['snippet'].get('customUrl', ''),
"published_at": channel['snippet']['publishedAt'],
"thumbnail": channel['snippet']['thumbnails'].get('default', {}).get('url'),
"high_res_thumbnail": channel['snippet']['thumbnails'].get('high', {}).get('url'),
"subscriber_count": channel['statistics'].get('subscriberCount', '0'),
"video_count": channel['statistics'].get('videoCount', '0'),
"view_count": channel['statistics'].get('viewCount', '0'),
"uploads_playlist_id": channel['contentDetails']['relatedPlaylists']['uploads'],
"country": channel['snippet'].get('country', ''),
"default_language": channel['snippet'].get('defaultLanguage', '')
}
channels.append(channel_info)
result = {
"total_channels": len(channels),
"channels": channels
}
# 결과를 Redis에 캐싱
await self.youtube_storage.cache_channels(cache_key, result)
return result
except HttpError as e:
error_content = json.loads(e.content.decode('utf-8'))
error_message = error_content.get('error', {}).get('message', str(e))
raise HTTPException(status_code=e.resp.status, detail=f"채널 정보 조회 실패: {error_message}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"채널 정보 조회 오류: {str(e)}")