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

+34
View File
@@ -0,0 +1,34 @@
from .redis_manager import RedisManager
from .oauth_storage import GoogleOAuthStorage
# 전역 Redis 매니저 인스턴스
redis_manager = RedisManager()
google_storage = GoogleOAuthStorage(redis_manager)
async def get_redis_manager() -> RedisManager:
"""Redis 매니저 의존성"""
return redis_manager
async def get_google_storage() -> GoogleOAuthStorage:
"""Google 저장소 의존성"""
return google_storage
# 하위 호환성을 위한 별칭
async def get_oauth_storage() -> GoogleOAuthStorage:
"""OAuth 저장소 의존성 (하위 호환성)"""
return google_storage
async def get_youtube_storage() -> GoogleOAuthStorage:
"""YouTube 저장소 의존성 (하위 호환성)"""
return google_storage
__all__ = [
"RedisManager",
"GoogleOAuthStorage",
"redis_manager",
"google_storage",
"get_redis_manager",
"get_google_storage",
"get_oauth_storage", # 하위 호환성
"get_youtube_storage", # 하위 호환성
]
+97
View File
@@ -0,0 +1,97 @@
import json
from typing import Optional, Dict, Any
from .redis_manager import RedisManager
class GoogleOAuthStorage:
"""Google OAuth 전용 Redis 저장소"""
def __init__(self, redis_manager: RedisManager):
self.redis_manager = redis_manager
# ============== state 관리 ==============
async def store_oauth_state(self, state: str, state_data: Dict[str, Any], ttl: int = 300):
"""OAuth state 저장 (기본 5분 TTL)"""
try:
client = await self.redis_manager.get_client()
await client.set(
f"google_oauth_state:{state}",
json.dumps(state_data, ensure_ascii=False),
ex=ttl
)
print(f"✅ OAuth state 저장 완료: {state[:8]}...")
except Exception as e:
print(f"❌ OAuth state 저장 실패: {e}")
raise e
async def get_oauth_state(self, state: str) -> Optional[Dict[str, Any]]:
"""OAuth state 조회"""
try:
client = await self.redis_manager.get_client()
data = await client.get(f"google_oauth_state:{state}")
if data:
result = json.loads(data)
print(f"✅ OAuth state 조회 완료: {state[:8]}...")
return result
else:
print(f"⚠️ OAuth state 없음: {state[:8]}...")
return None
except Exception as e:
print(f"❌ OAuth state 조회 실패: {e}")
return None
async def delete_oauth_state(self, state: str):
"""OAuth state 삭제"""
try:
client = await self.redis_manager.get_client()
result = await client.delete(f"google_oauth_state:{state}")
if result:
print(f"✅ OAuth state 삭제 완료: {state[:8]}...")
else:
print(f"⚠️ 삭제할 OAuth state 없음: {state[:8]}...")
except Exception as e:
print(f"❌ OAuth state 삭제 실패: {e}")
# ================ token 관리 ==============
# front로 정보들을 넘겨주기 위한 token
async def store_temp_token(self, temp_token_id: str, token_data: Dict[str, Any], ttl: int = 300):
"""임시 토큰 저장 (기본 5분 TTL)"""
try:
client = await self.redis_manager.get_client()
await client.set(
f"google_temp_token:{temp_token_id}",
json.dumps(token_data, ensure_ascii=False),
ex=ttl
)
print(f"✅ 임시 토큰 저장 완료: {temp_token_id[:8]}...")
except Exception as e:
print(f"❌ 임시 토큰 저장 실패: {e}")
raise e
async def get_temp_token(self, temp_token_id: str) -> Optional[Dict[str, Any]]:
"""임시 토큰 조회"""
try:
client = await self.redis_manager.get_client()
data = await client.get(f"google_temp_token:{temp_token_id}")
if data:
result = json.loads(data)
print(f"✅ 임시 토큰 조회 완료: {temp_token_id[:8]}...")
return result
else:
print(f"⚠️ 임시 토큰 없음: {temp_token_id[:8]}...")
return None
except Exception as e:
print(f"❌ 임시 토큰 조회 실패: {e}")
return None
async def delete_temp_token(self, temp_token_id: str):
"""임시 토큰 삭제"""
try:
client = await self.redis_manager.get_client()
result = await client.delete(f"google_temp_token:{temp_token_id}")
if result:
print(f"✅ 임시 토큰 삭제 완료: {temp_token_id[:8]}...")
else:
print(f"⚠️ 삭제할 임시 토큰 없음: {temp_token_id[:8]}...")
except Exception as e:
print(f"❌ 임시 토큰 삭제 실패: {e}")
+12
View File
@@ -0,0 +1,12 @@
import redis.asyncio as redis
from app.core.env_setting import EnvSetting
settings = EnvSetting()
env = settings
redis_client = redis.Redis(
host=env.REDIS_HOST,
port=env.REDIS_PORT,
db=env.REDIS_DB,
decode_responses=True
)
+64
View File
@@ -0,0 +1,64 @@
import redis
import redis.asyncio as async_redis
from typing import Optional
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.async_client: Optional[async_redis.Redis] = None
self.sync_client: Optional[redis.Redis] = None
# 비동기 클라이언트 메서드들 (기존)
async def connect(self):
"""Redis 비동기 연결"""
if self.async_client is None:
self.async_client = async_redis.from_url(
self.redis_url,
encoding="utf-8",
decode_responses=True,
max_connections=20,
socket_connect_timeout=5,
socket_timeout=5,
)
return self.async_client
async def close(self):
"""Redis 비동기 연결 종료"""
if self.async_client:
await self.async_client.close()
self.async_client = None
async def get_client(self) -> async_redis.Redis:
"""Redis 비동기 클라이언트 반환"""
if self.async_client is None:
await self.connect()
return self.async_client
# 동기 클라이언트 메서드들 (새로 추가) ( celery 전용 )
def connect_sync(self):
"""Redis 동기 연결"""
if self.sync_client is None:
self.sync_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.sync_client
def close_sync(self):
"""Redis 동기 연결 종료"""
if self.sync_client:
self.sync_client.close()
self.sync_client = None
def get_sync_client(self) -> redis.Redis:
"""Redis 동기 클라이언트 반환"""
if self.sync_client is None:
self.connect_sync()
return self.sync_client