first commit
This commit is contained in:
1 parent
78da3838f0
commit
09c86adf7b
486 files changed
+47300
No files matched your search
@@ -0,0 +1,33 @@
|
||||
from passlib.context import CryptContext
|
||||
from cryptography.fernet import Fernet
|
||||
from app.core.env_setting import EnvSetting
|
||||
|
||||
settings = EnvSetting()
|
||||
env_setting = settings
|
||||
# 비밀번호 해싱을 위한 설정
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
# 대칭키 암호화를 위한 키
|
||||
CRYPTO_SECRET_KEY = env_setting.CRYPTO_SECRET_KEY
|
||||
fernet = Fernet(CRYPTO_SECRET_KEY)
|
||||
|
||||
class Crypto:
|
||||
@staticmethod
|
||||
def hash_password(password: str) -> str:
|
||||
"""비밀번호를 bcrypt로 해싱합니다."""
|
||||
return pwd_context.hash(password)
|
||||
|
||||
@staticmethod
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""입력된 비밀번호가 해시와 일치하는지 확인합니다."""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
@staticmethod
|
||||
def encrypt_token(token: str) -> str:
|
||||
"""토큰을 대칭키 암호화로 암호화합니다."""
|
||||
return fernet.encrypt(token.encode()).decode()
|
||||
|
||||
@staticmethod
|
||||
def decrypt_token(encrypted_token: str) -> str:
|
||||
"""암호화된 토큰을 복호화합니다."""
|
||||
return fernet.decrypt(encrypted_token.encode()).decode()
|
||||
@@ -0,0 +1,96 @@
|
||||
import functools
|
||||
import inspect
|
||||
from typing import Any, Callable, TypeVar
|
||||
from fastapi import HTTPException
|
||||
from app.shared.response.best_rest_api_response import BaseRestApiResponse
|
||||
from app.shared.exception.custom_exception import BaseCustomException
|
||||
|
||||
F = TypeVar('F', bound=Callable[..., Any])
|
||||
|
||||
def response_wrapper(func: F) -> F:
|
||||
"""
|
||||
모든 반환값을 BaseRestApiResponse 형태로 자동 변환하는 데코레이터
|
||||
|
||||
- 성공 시: BaseRestApiResponse.success로 래핑
|
||||
- 실패 시: BaseRestApiResponse.failure로 래핑 (status_code → error_code, message → error_message)
|
||||
"""
|
||||
# 비동기 함수 래핑
|
||||
@functools.wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
try:
|
||||
result = await func(*args, **kwargs)
|
||||
|
||||
if isinstance(result, BaseRestApiResponse):
|
||||
return result
|
||||
|
||||
# 반환값에 상관없이 성공 시 래핑
|
||||
return BaseRestApiResponse.success(data=result)
|
||||
|
||||
except BaseCustomException as e:
|
||||
return BaseRestApiResponse.failure(
|
||||
error_code=e.error_code,
|
||||
error_message=e.error_message,
|
||||
http_status_code=e.http_status_code
|
||||
)
|
||||
except HTTPException as e:
|
||||
return BaseRestApiResponse.failure(
|
||||
error_code=str(e.status_code), # status_code를 error_code로
|
||||
error_message=str(e.detail), # detail을 error_message로
|
||||
http_status_code=e.status_code
|
||||
)
|
||||
except Exception as e:
|
||||
return BaseRestApiResponse.failure(
|
||||
error_code="500",
|
||||
error_message=str(e),
|
||||
http_status_code=500
|
||||
)
|
||||
|
||||
# 동기 함수 래핑
|
||||
@functools.wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
|
||||
if isinstance(result, BaseRestApiResponse):
|
||||
return result
|
||||
|
||||
# 성공 응답으로 래핑 (반환값이 뭐든 상관없이)
|
||||
return BaseRestApiResponse.success(data=result)
|
||||
|
||||
except BaseCustomException as e:
|
||||
return BaseRestApiResponse.failure(
|
||||
error_code=e.error_code,
|
||||
error_message=e.error_message,
|
||||
http_status_code=e.http_status_code
|
||||
)
|
||||
|
||||
except HTTPException as e:
|
||||
return BaseRestApiResponse.failure(
|
||||
error_code=str(e.status_code), # status_code를 error_code로
|
||||
error_message=str(e.detail), # detail을 error_message로
|
||||
http_status_code=e.status_code
|
||||
)
|
||||
except Exception as e:
|
||||
return BaseRestApiResponse.failure(
|
||||
error_code="500",
|
||||
error_message=str(e),
|
||||
http_status_code=500
|
||||
)
|
||||
|
||||
if inspect.iscoroutinefunction(func):
|
||||
return async_wrapper
|
||||
else:
|
||||
return sync_wrapper
|
||||
|
||||
'''
|
||||
사용방법
|
||||
@app.get("/s")
|
||||
@response_wrapper
|
||||
def success():
|
||||
return "hi"
|
||||
|
||||
@app.get("/f")
|
||||
@response_wrapper
|
||||
def failure():
|
||||
raise HTTPException(status_code=400, detail="error")
|
||||
'''
|
||||
@@ -0,0 +1,113 @@
|
||||
from fastapi import HTTPException
|
||||
|
||||
class BaseCustomException(HTTPException):
|
||||
"""커스텀 예외의 기본 클래스"""
|
||||
|
||||
def __init__(self, error_code: str, error_message: str, http_status_code: int = 400):
|
||||
super().__init__(status_code=http_status_code, detail=error_message)
|
||||
self.error_code = error_code
|
||||
self.error_message = error_message
|
||||
self.http_status_code = http_status_code
|
||||
|
||||
# ===========================================
|
||||
# 비즈니스 로직 관련 예외들
|
||||
# ===========================================
|
||||
|
||||
class UserIdAlreadyExistsError(BaseCustomException):
|
||||
"""사용자 ID 중복 예외"""
|
||||
|
||||
def __init__(self, message: str = "이미 존재하는 유저 아이디입니다."):
|
||||
super().__init__(
|
||||
error_code="USER_ID_ALREADY_EXISTS",
|
||||
error_message=message,
|
||||
http_status_code=409
|
||||
)
|
||||
|
||||
class UserNotFoundError(BaseCustomException):
|
||||
"""사용자 찾을 수 없음 예외"""
|
||||
|
||||
def __init__(self, message: str = "사용자를 찾을 수 없습니다."):
|
||||
super().__init__(
|
||||
error_code="USER_NOT_FOUND",
|
||||
error_message=message,
|
||||
http_status_code=404
|
||||
)
|
||||
|
||||
class PasswordIncorrectError(BaseCustomException):
|
||||
"""비밀번호 올바르지 않음 예외"""
|
||||
|
||||
def __init__(self, message: str = "비밀번호가 올바르지 않습니다."):
|
||||
super().__init__(
|
||||
error_code="PASSWORD_INCORRECT",
|
||||
error_message=message,
|
||||
http_status_code=400
|
||||
)
|
||||
|
||||
|
||||
# ===========================================
|
||||
# 소셜 로그인 관련 예외들
|
||||
# ===========================================
|
||||
|
||||
class OAuthConfigurationError(BaseCustomException):
|
||||
"""OAuth 설정 오류"""
|
||||
def __init__(self, message: str = "OAuth 설정에 오류가 있습니다."):
|
||||
super().__init__(
|
||||
error_code="OAUTH_CONFIGURATION_ERROR",
|
||||
error_message=message,
|
||||
http_status_code=500
|
||||
)
|
||||
|
||||
class OAuthStateInvalidError(BaseCustomException):
|
||||
"""OAuth State 검증 실패"""
|
||||
def __init__(self, message: str = "OAuth state가 유효하지 않습니다."):
|
||||
super().__init__(
|
||||
error_code="OAUTH_STATE_INVALID",
|
||||
error_message=message,
|
||||
http_status_code=400
|
||||
)
|
||||
|
||||
class OAuthTokenExchangeError(BaseCustomException):
|
||||
"""OAuth 토큰 교환 실패"""
|
||||
def __init__(self, message: str = "OAuth 토큰 교환에 실패했습니다."):
|
||||
super().__init__(
|
||||
error_code="OAUTH_TOKEN_EXCHANGE_ERROR",
|
||||
error_message=message,
|
||||
http_status_code=400
|
||||
)
|
||||
|
||||
class OAuthUserInfoError(BaseCustomException):
|
||||
"""OAuth 사용자 정보 추출 실패"""
|
||||
def __init__(self, message: str = "사용자 정보를 가져올 수 없습니다."):
|
||||
super().__init__(
|
||||
error_code="OAUTH_USER_INFO_ERROR",
|
||||
error_message=message,
|
||||
http_status_code=400
|
||||
)
|
||||
|
||||
class OAuthTempTokenError(BaseCustomException):
|
||||
"""임시 토큰 관련 오류"""
|
||||
def __init__(self, message: str = "임시 토큰이 유효하지 않거나 만료되었습니다."):
|
||||
super().__init__(
|
||||
error_code="OAUTH_TEMP_TOKEN_ERROR",
|
||||
error_message=message,
|
||||
http_status_code=400
|
||||
)
|
||||
|
||||
class ItemNotFoundError(BaseCustomException):
|
||||
def __init__(self, message: str = "업체를 찾을 수 없습니다."):
|
||||
super().__init__(
|
||||
error_code="item_not_found",
|
||||
error_message=message,
|
||||
http_status_code=400
|
||||
)
|
||||
|
||||
class OrderNotFoundError(Exception):
|
||||
def __init__(self, message: str = "해당 주문을 찾을 수 없습니다."):
|
||||
self.message = message
|
||||
super().__init__(self.message)
|
||||
|
||||
|
||||
class VideoNotFoundError(Exception):
|
||||
def __init__(self, message: str = "해당 주문에 대한 영상을 찾을 수 없습니다."):
|
||||
self.message = message
|
||||
super().__init__(self.message)
|
||||
@@ -0,0 +1,51 @@
|
||||
import logging
|
||||
import sys
|
||||
import os
|
||||
|
||||
def setup_logger(name: str) -> logging.Logger:
|
||||
logger = logging.getLogger(name)
|
||||
|
||||
# 이미 설정된 로거는 다시 설정하지 않음
|
||||
if not logger.handlers:
|
||||
# 환경 변수에서 로그 레벨 가져오기 (기본값: INFO)
|
||||
log_level_name = os.environ.get('LOG_LEVEL', 'INFO')
|
||||
log_level = getattr(logging, log_level_name, logging.INFO)
|
||||
|
||||
# 콘솔 핸들러 설정
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(log_level)
|
||||
|
||||
class CustomFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
if len(record.getMessage()) > 30:
|
||||
self._style._fmt = '[%(asctime)s] [%(levelname)s] [%(name)s]\n%(message)s'
|
||||
else:
|
||||
self._style._fmt = '[%(asctime)s] [%(levelname)s] [%(name)s] - %(message)s'
|
||||
return super().format(record)
|
||||
|
||||
formatter = CustomFormatter()
|
||||
console_handler.setFormatter(formatter)
|
||||
logger.addHandler(console_handler)
|
||||
logger.setLevel(log_level)
|
||||
|
||||
# SQLAlchemy 로깅 레벨 설정
|
||||
if name == "__main__":
|
||||
# SQLAlchemy의 과도한 로깅 제한
|
||||
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
|
||||
|
||||
return logger
|
||||
|
||||
'''
|
||||
####### 사용 방법 #######
|
||||
from utils.logger import setup_logger
|
||||
logger = setup_logger(__name__)
|
||||
logger.info("Hello, World!")
|
||||
|
||||
|
||||
####### 출력 형식 #######
|
||||
[2025-05-13 12:00:00] [INFO] [__main__] - Hello, World!
|
||||
|
||||
# 메시지가 긴 경우
|
||||
[2025-05-13 12:00:00] [INFO] [__main__]
|
||||
Hello, World!
|
||||
'''
|
||||
@@ -0,0 +1,69 @@
|
||||
from app.core.redis.redis_manager import RedisManager
|
||||
import json
|
||||
from app.shared.logger import setup_logger
|
||||
from typing import Optional
|
||||
|
||||
logger = setup_logger(__name__)
|
||||
|
||||
|
||||
class Process:
|
||||
"""Redis 상태 저장 및 조회 (예: 진행률 트래킹)"""
|
||||
|
||||
def __init__(self, redis_manager: RedisManager):
|
||||
self.redis = redis_manager
|
||||
|
||||
async def init_task_status(self, task_id: str) -> None:
|
||||
"""처음 상태 초기화"""
|
||||
status = {
|
||||
"metadata": False,
|
||||
"lyrics": False,
|
||||
"songs": False,
|
||||
"images": False,
|
||||
"movies": False,
|
||||
"combined": False
|
||||
}
|
||||
r = await self.redis.get_client()
|
||||
await r.set(f"task_progress:{task_id}", json.dumps(status))
|
||||
|
||||
async def set_task_step_done(self, task_id: str, step_name: str) -> None:
|
||||
"""단계별 상태 True로 업데이트"""
|
||||
r = await self.redis.get_client()
|
||||
key = f"task_progress:{task_id}"
|
||||
data = await r.get(key)
|
||||
|
||||
if not data:
|
||||
await self.init_task_status(task_id)
|
||||
data = await r.get(key)
|
||||
|
||||
if not data:
|
||||
logger.error(f"[set_task_step_done] Redis에 상태가 저장되지 않았습니다. key={key}")
|
||||
return
|
||||
|
||||
try:
|
||||
if isinstance(data, bytes):
|
||||
data = data.decode()
|
||||
status_data = json.loads(data)
|
||||
except Exception as e:
|
||||
logger.exception(f"[set_task_step_done] JSON decode 실패: {e}")
|
||||
return
|
||||
|
||||
# 단계 상태 업데이트
|
||||
status_data[step_name] = True
|
||||
await r.set(key, json.dumps(status_data)) # ✅ await 추가
|
||||
|
||||
async def get_task_status(self, task_id: str) -> dict:
|
||||
"""전체 상태 조회"""
|
||||
r = await self.redis.get_client()
|
||||
key = f"task_progress:{task_id}"
|
||||
data = await r.get(key)
|
||||
|
||||
if not data:
|
||||
return {}
|
||||
|
||||
try:
|
||||
if isinstance(data, bytes):
|
||||
data = data.decode()
|
||||
return json.loads(data)
|
||||
except Exception as e:
|
||||
logger.exception(f"[get_task_status] JSON decode error for {key}: {e}")
|
||||
return {}
|
||||
@@ -0,0 +1,32 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional, TypeVar, Generic
|
||||
from pydantic import BaseModel, field_serializer
|
||||
T = TypeVar('T')
|
||||
class BaseRestApiResponse(BaseModel, Generic[T]):
|
||||
ok: bool
|
||||
http_status_code: int
|
||||
data: Optional[T]
|
||||
error_code: Optional[str] = None
|
||||
error_message: Optional[str] = None
|
||||
timestamp: datetime = None
|
||||
@field_serializer('timestamp')
|
||||
def serialize_timestamp(self, timestamp: datetime, _info):
|
||||
return timestamp.isoformat()
|
||||
@staticmethod
|
||||
def success(data: T, http_status_code: int = 200) -> 'BaseRestApiResponse[T]':
|
||||
return BaseRestApiResponse(
|
||||
ok=True,
|
||||
http_status_code=http_status_code,
|
||||
data=data,
|
||||
timestamp=datetime.now()
|
||||
)
|
||||
@staticmethod
|
||||
def failure(error_code: str, error_message: str, http_status_code: int = 400) -> 'BaseRestApiResponse[None]':
|
||||
return BaseRestApiResponse(
|
||||
ok=False,
|
||||
http_status_code=http_status_code,
|
||||
data=None,
|
||||
error_code=error_code,
|
||||
error_message=error_message,
|
||||
timestamp=datetime.now()
|
||||
)
|
||||
Reference in new issue
Block a user