uuid7으로 필드 및 처리관련 수정
This commit is contained in:
1 parent
aa8d9d7c14
commit
32ae5530b6
26 files changed
+2346
-901
No files matched your search
+18
-5
@@ -72,18 +72,31 @@ async def create_db_tables():
|
||||
import asyncio
|
||||
|
||||
# 모델 import (테이블 메타데이터 등록용)
|
||||
# 주의: User를 먼저 import해야 UserProject가 User를 참조할 수 있음
|
||||
from app.user.models import User # noqa: F401
|
||||
from app.home.models import Image, Project, UserProject # noqa: F401
|
||||
from app.user.models import User, RefreshToken # noqa: F401
|
||||
from app.home.models import Image, Project # noqa: F401
|
||||
from app.lyric.models import Lyric # noqa: F401
|
||||
from app.song.models import Song # noqa: F401
|
||||
from app.song.models import Song, SongTimestamp # noqa: F401
|
||||
from app.video.models import Video # noqa: F401
|
||||
|
||||
# 생성할 테이블 목록 (SocialAccount 제외)
|
||||
tables_to_create = [
|
||||
User.__table__,
|
||||
RefreshToken.__table__,
|
||||
Project.__table__,
|
||||
Image.__table__,
|
||||
Lyric.__table__,
|
||||
Song.__table__,
|
||||
SongTimestamp.__table__,
|
||||
Video.__table__,
|
||||
]
|
||||
|
||||
logger.info("Creating database tables...")
|
||||
|
||||
async with asyncio.timeout(10):
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
await connection.run_sync(
|
||||
lambda conn: Base.metadata.create_all(conn, tables=tables_to_create)
|
||||
)
|
||||
|
||||
|
||||
# FastAPI 의존성용 세션 제너레이터
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from sqladmin import ModelView
|
||||
|
||||
from app.home.models import Image, Project, UserProject
|
||||
from app.home.models import Image, Project
|
||||
|
||||
|
||||
class ProjectAdmin(ModelView, model=Project):
|
||||
@@ -100,44 +100,3 @@ class ImageAdmin(ModelView, model=Image):
|
||||
"img_url": "이미지 URL",
|
||||
"created_at": "생성일시",
|
||||
}
|
||||
|
||||
|
||||
class UserProjectAdmin(ModelView, model=UserProject):
|
||||
name = "사용자-프로젝트"
|
||||
name_plural = "사용자-프로젝트 목록"
|
||||
icon = "fa-solid fa-link"
|
||||
category = "프로젝트 관리"
|
||||
page_size = 20
|
||||
|
||||
column_list = [
|
||||
"id",
|
||||
"user_id",
|
||||
"project_id",
|
||||
]
|
||||
|
||||
column_details_list = [
|
||||
"id",
|
||||
"user_id",
|
||||
"project_id",
|
||||
"user",
|
||||
"project",
|
||||
]
|
||||
|
||||
column_searchable_list = [
|
||||
UserProject.user_id,
|
||||
UserProject.project_id,
|
||||
]
|
||||
|
||||
column_sortable_list = [
|
||||
UserProject.id,
|
||||
UserProject.user_id,
|
||||
UserProject.project_id,
|
||||
]
|
||||
|
||||
column_labels = {
|
||||
"id": "ID",
|
||||
"user_id": "사용자 ID",
|
||||
"project_id": "프로젝트 ID",
|
||||
"user": "사용자",
|
||||
"project": "프로젝트",
|
||||
}
|
||||
@@ -12,6 +12,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import get_session, AsyncSessionLocal
|
||||
from app.home.models import Image
|
||||
from app.user.dependencies.auth import get_current_user
|
||||
from app.user.models import User
|
||||
from app.home.schemas.home_schema import (
|
||||
AutoCompleteRequest,
|
||||
CrawlingRequest,
|
||||
@@ -502,6 +504,7 @@ async def upload_images(
|
||||
files: Optional[list[UploadFile]] = File(
|
||||
default=None, description="이미지 바이너리 파일 목록"
|
||||
),
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> ImageUploadResponse:
|
||||
"""이미지 업로드 (URL + 바이너리 파일)"""
|
||||
@@ -730,6 +733,7 @@ async def upload_images_blob(
|
||||
default=None,
|
||||
description="이미지 바이너리 파일 목록",
|
||||
),
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> ImageUploadResponse:
|
||||
"""이미지 업로드 (URL + Azure Blob Storage)
|
||||
|
||||
|
||||
+26
-140
@@ -4,13 +4,12 @@ Home 모듈 SQLAlchemy 모델 정의
|
||||
이 모듈은 영상 제작 파이프라인의 핵심 데이터 모델을 정의합니다.
|
||||
- Project: 프로젝트(사용자 입력 이력) 관리
|
||||
- Image: 업로드된 이미지 URL 관리
|
||||
- UserProject: User와 Project 간 M:N 관계 중계 테이블
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, List, Optional
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, ForeignKey, Index, Integer, String, Text, func
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database.session import Base
|
||||
@@ -21,122 +20,6 @@ if TYPE_CHECKING:
|
||||
from app.user.models import User
|
||||
from app.video.models import Video
|
||||
|
||||
# =============================================================================
|
||||
# User-Project M:N 관계 중계 테이블
|
||||
# =============================================================================
|
||||
#
|
||||
# 설계 의도:
|
||||
# - User와 Project는 다대다(M:N) 관계입니다.
|
||||
# - 한 사용자는 여러 프로젝트에 참여할 수 있습니다.
|
||||
# - 한 프로젝트에는 여러 사용자가 참여할 수 있습니다.
|
||||
#
|
||||
# 중계 테이블 역할:
|
||||
# - UserProject 테이블이 두 테이블 간의 관계를 연결합니다.
|
||||
# - 각 레코드는 특정 사용자와 특정 프로젝트의 연결을 나타냅니다.
|
||||
# - 추가 속성(role, joined_at)으로 관계의 메타데이터를 저장합니다.
|
||||
#
|
||||
# 외래키 설정:
|
||||
# - user_id: User 테이블의 id를 참조 (ON DELETE CASCADE)
|
||||
# - project_id: Project 테이블의 id를 참조 (ON DELETE CASCADE)
|
||||
# - CASCADE 설정으로 부모 레코드 삭제 시 중계 레코드도 자동 삭제됩니다.
|
||||
#
|
||||
# 관계 방향:
|
||||
# - User.projects → UserProject → Project (사용자가 참여한 프로젝트 목록)
|
||||
# - Project.users → UserProject → User (프로젝트에 참여한 사용자 목록)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class UserProject(Base):
|
||||
"""
|
||||
User-Project M:N 관계 중계 테이블
|
||||
|
||||
사용자와 프로젝트 간의 다대다 관계를 관리합니다.
|
||||
한 사용자는 여러 프로젝트에 참여할 수 있고,
|
||||
한 프로젝트에는 여러 사용자가 참여할 수 있습니다.
|
||||
|
||||
Attributes:
|
||||
id: 고유 식별자 (자동 증가)
|
||||
user_id: 사용자 외래키 (User.id 참조)
|
||||
project_id: 프로젝트 외래키 (Project.id 참조)
|
||||
role: 프로젝트 내 사용자 역할 (owner: 소유자, member: 멤버, viewer: 조회자)
|
||||
joined_at: 프로젝트 참여 일시
|
||||
|
||||
외래키 제약조건:
|
||||
- user_id → user.id (ON DELETE CASCADE)
|
||||
- project_id → project.id (ON DELETE CASCADE)
|
||||
|
||||
유니크 제약조건:
|
||||
- (user_id, project_id) 조합은 유일해야 함 (중복 참여 방지)
|
||||
"""
|
||||
|
||||
__tablename__ = "user_project"
|
||||
__table_args__ = (
|
||||
Index("idx_user_project_user_id", "user_id"),
|
||||
Index("idx_user_project_project_id", "project_id"),
|
||||
Index("idx_user_project_user_project", "user_id", "project_id", unique=True),
|
||||
{
|
||||
"mysql_engine": "InnoDB",
|
||||
"mysql_charset": "utf8mb4",
|
||||
"mysql_collate": "utf8mb4_unicode_ci",
|
||||
},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
primary_key=True,
|
||||
nullable=False,
|
||||
autoincrement=True,
|
||||
comment="고유 식별자",
|
||||
)
|
||||
|
||||
# 외래키: User 테이블 참조
|
||||
# - BigInteger 사용 (User.id가 BigInteger이므로 타입 일치 필요)
|
||||
# - ondelete="CASCADE": User 삭제 시 연결된 UserProject 레코드도 삭제
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("user.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="사용자 외래키 (User.id 참조)",
|
||||
)
|
||||
|
||||
# 외래키: Project 테이블 참조
|
||||
# - Integer 사용 (Project.id가 Integer이므로 타입 일치 필요)
|
||||
# - ondelete="CASCADE": Project 삭제 시 연결된 UserProject 레코드도 삭제
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
ForeignKey("project.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="프로젝트 외래키 (Project.id 참조)",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# Relationships (관계 설정)
|
||||
# ==========================================================================
|
||||
# back_populates: 양방향 관계 설정 (User.user_projects, Project.user_projects)
|
||||
# lazy="selectin": N+1 문제 방지를 위한 즉시 로딩
|
||||
# ==========================================================================
|
||||
user: Mapped["User"] = relationship(
|
||||
"User",
|
||||
back_populates="user_projects",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
project: Mapped["Project"] = relationship(
|
||||
"Project",
|
||||
back_populates="user_projects",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"<UserProject("
|
||||
f"id={self.id}, "
|
||||
f"user_id={self.user_id}, "
|
||||
f"project_id={self.project_id}, "
|
||||
f"role='{self.role}'"
|
||||
f")>"
|
||||
)
|
||||
|
||||
|
||||
class Project(Base):
|
||||
"""
|
||||
@@ -149,16 +32,15 @@ class Project(Base):
|
||||
id: 고유 식별자 (자동 증가)
|
||||
store_name: 고객명 (필수)
|
||||
region: 지역명 (필수, 예: 서울, 부산, 대구 등)
|
||||
task_id: 작업 고유 식별자 (KSUID 형식, 27자)
|
||||
task_id: 작업 고유 식별자 (UUID7 형식, 36자)
|
||||
detail_region_info: 상세 지역 정보 (선택, JSON 또는 텍스트 형식)
|
||||
created_at: 생성 일시 (자동 설정)
|
||||
|
||||
Relationships:
|
||||
owner: 프로젝트 소유자 (User, 1:N 관계)
|
||||
lyrics: 생성된 가사 목록
|
||||
songs: 생성된 노래 목록
|
||||
videos: 최종 영상 결과 목록
|
||||
user_projects: User와의 M:N 관계 (중계 테이블 통한 연결)
|
||||
users: 프로젝트에 참여한 사용자 목록 (Association Proxy)
|
||||
"""
|
||||
|
||||
__tablename__ = "project"
|
||||
@@ -166,6 +48,7 @@ class Project(Base):
|
||||
Index("idx_project_task_id", "task_id"),
|
||||
Index("idx_project_store_name", "store_name"),
|
||||
Index("idx_project_region", "region"),
|
||||
Index("idx_project_user_uuid", "user_uuid"),
|
||||
{
|
||||
"mysql_engine": "InnoDB",
|
||||
"mysql_charset": "utf8mb4",
|
||||
@@ -194,10 +77,27 @@ class Project(Base):
|
||||
)
|
||||
|
||||
task_id: Mapped[str] = mapped_column(
|
||||
String(27),
|
||||
String(36),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
comment="프로젝트 작업 고유 식별자 (KSUID)",
|
||||
comment="프로젝트 작업 고유 식별자 (UUID7)",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# User 1:N 관계 (한 사용자가 여러 프로젝트를 소유)
|
||||
# ==========================================================================
|
||||
user_uuid: Mapped[Optional[str]] = mapped_column(
|
||||
String(36),
|
||||
ForeignKey("user.user_uuid", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
comment="프로젝트 소유자 (User.user_uuid 외래키)",
|
||||
)
|
||||
|
||||
# 소유자 관계 설정 (User.projects와 양방향 연결)
|
||||
owner: Mapped[Optional["User"]] = relationship(
|
||||
"User",
|
||||
back_populates="projects",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
detail_region_info: Mapped[Optional[str]] = mapped_column(
|
||||
@@ -242,20 +142,6 @@ class Project(Base):
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# User M:N 관계 (중계 테이블 UserProject 통한 연결)
|
||||
# ==========================================================================
|
||||
# back_populates: UserProject.project와 양방향 연결
|
||||
# cascade: Project 삭제 시 UserProject 레코드도 삭제 (User는 유지)
|
||||
# lazy="selectin": N+1 문제 방지
|
||||
# ==========================================================================
|
||||
user_projects: Mapped[List["UserProject"]] = relationship(
|
||||
"UserProject",
|
||||
back_populates="project",
|
||||
cascade="all, delete-orphan",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
def truncate(value: str | None, max_len: int = 10) -> str:
|
||||
if value is None:
|
||||
@@ -280,7 +166,7 @@ class Image(Base):
|
||||
|
||||
Attributes:
|
||||
id: 고유 식별자 (자동 증가)
|
||||
task_id: 이미지 업로드 작업 고유 식별자 (KSUID)
|
||||
task_id: 이미지 업로드 작업 고유 식별자 (UUID7)
|
||||
img_name: 이미지명
|
||||
img_url: 이미지 URL (S3, CDN 등의 경로)
|
||||
created_at: 생성 일시 (자동 설정)
|
||||
@@ -305,10 +191,10 @@ class Image(Base):
|
||||
)
|
||||
|
||||
task_id: Mapped[str] = mapped_column(
|
||||
String(27),
|
||||
String(36),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
comment="이미지 업로드 작업 고유 식별자 (KSUID)",
|
||||
comment="이미지 업로드 작업 고유 식별자 (UUID7)",
|
||||
)
|
||||
|
||||
img_name: Mapped[str] = mapped_column(
|
||||
|
||||
@@ -91,7 +91,7 @@ class GenerateUrlsRequest(GenerateRequestInfo):
|
||||
class GenerateUploadResponse(BaseModel):
|
||||
"""파일 업로드 기반 생성 응답 스키마"""
|
||||
|
||||
task_id: str = Field(..., description="작업 고유 식별자 (KSUID)")
|
||||
task_id: str = Field(..., description="작업 고유 식별자 (UUID7)")
|
||||
status: Literal["processing", "completed", "failed"] = Field(
|
||||
..., description="작업 상태"
|
||||
)
|
||||
@@ -102,7 +102,7 @@ class GenerateUploadResponse(BaseModel):
|
||||
class GenerateResponse(BaseModel):
|
||||
"""생성 응답 스키마"""
|
||||
|
||||
task_id: str = Field(..., description="작업 고유 식별자 (KSUID)")
|
||||
task_id: str = Field(..., description="작업 고유 식별자 (UUID7)")
|
||||
status: Literal["processing", "completed", "failed"] = Field(
|
||||
..., description="작업 상태"
|
||||
)
|
||||
@@ -291,7 +291,7 @@ class ImageUploadResponse(BaseModel):
|
||||
}
|
||||
)
|
||||
|
||||
task_id: str = Field(..., description="작업 고유 식별자 (새로 생성된 KSUID)")
|
||||
task_id: str = Field(..., description="작업 고유 식별자 (새로 생성된 UUID7)")
|
||||
total_count: int = Field(..., description="총 업로드된 이미지 개수")
|
||||
url_count: int = Field(..., description="URL로 등록된 이미지 개수")
|
||||
file_count: int = Field(..., description="파일로 업로드된 이미지 개수")
|
||||
|
||||
@@ -31,6 +31,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import get_session
|
||||
from app.home.models import Project
|
||||
from app.user.dependencies.auth import get_current_user
|
||||
from app.user.models import User
|
||||
from app.lyric.models import Lyric
|
||||
from app.lyric.schemas.lyric import (
|
||||
GenerateLyricRequest,
|
||||
@@ -222,6 +224,7 @@ POST /lyric/generate
|
||||
async def generate_lyric(
|
||||
request_body: GenerateLyricRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> GenerateLyricResponse:
|
||||
"""고객 정보를 기반으로 가사를 생성합니다. (백그라운드 처리)"""
|
||||
@@ -391,6 +394,7 @@ GET /lyric/status/019123ab-cdef-7890-abcd-ef1234567890
|
||||
)
|
||||
async def get_lyric_status(
|
||||
task_id: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> LyricStatusResponse:
|
||||
"""task_id로 가사 생성 작업 상태를 조회합니다."""
|
||||
@@ -435,6 +439,7 @@ GET /lyrics/?page=1&page_size=50 # 50개씩 조회
|
||||
async def list_lyrics(
|
||||
page: int = Query(1, ge=1, description="페이지 번호 (1부터 시작)"),
|
||||
page_size: int = Query(20, ge=1, le=100, description="페이지당 데이터 수"),
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> PaginatedResponse[LyricListItem]:
|
||||
"""페이지네이션으로 완료된 가사 목록을 조회합니다."""
|
||||
@@ -478,6 +483,7 @@ GET /lyric/019123ab-cdef-7890-abcd-ef1234567890
|
||||
)
|
||||
async def get_lyric_detail(
|
||||
task_id: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> LyricDetailResponse:
|
||||
"""task_id로 생성된 가사를 조회합니다."""
|
||||
|
||||
+3
-3
@@ -23,7 +23,7 @@ class Lyric(Base):
|
||||
Attributes:
|
||||
id: 고유 식별자 (자동 증가)
|
||||
project_id: 연결된 Project의 id (외래키)
|
||||
task_id: 가사 생성 작업의 고유 식별자 (KSUID 형식)
|
||||
task_id: 가사 생성 작업의 고유 식별자 (UUID7 형식)
|
||||
status: 처리 상태 (pending, processing, completed, failed 등)
|
||||
lyric_prompt: 가사 생성에 사용된 프롬프트
|
||||
lyric_result: 생성된 가사 결과 (LONGTEXT로 긴 가사 지원)
|
||||
@@ -62,10 +62,10 @@ class Lyric(Base):
|
||||
)
|
||||
|
||||
task_id: Mapped[str] = mapped_column(
|
||||
String(27),
|
||||
String(36),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
comment="가사 생성 작업 고유 식별자 (KSUID)",
|
||||
comment="가사 생성 작업 고유 식별자 (UUID7)",
|
||||
)
|
||||
|
||||
status: Mapped[str] = mapped_column(
|
||||
|
||||
@@ -18,6 +18,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import get_session
|
||||
from app.home.models import Project
|
||||
from app.user.dependencies.auth import get_current_user
|
||||
from app.user.models import User
|
||||
from app.lyric.models import Lyric
|
||||
from app.song.models import Song, SongTimestamp
|
||||
from app.song.schemas.song_schema import (
|
||||
@@ -79,6 +81,7 @@ POST /song/generate/019123ab-cdef-7890-abcd-ef1234567890
|
||||
async def generate_song(
|
||||
task_id: str,
|
||||
request_body: GenerateSongRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> GenerateSongResponse:
|
||||
"""가사와 장르를 기반으로 Suno API를 통해 노래를 생성합니다.
|
||||
|
||||
@@ -347,6 +350,7 @@ GET /song/status/abc123...
|
||||
async def get_song_status(
|
||||
song_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> PollingSongResponse:
|
||||
"""song_id로 노래 생성 작업의 상태를 조회합니다.
|
||||
|
||||
+3
-3
@@ -23,7 +23,7 @@ class Song(Base):
|
||||
id: 고유 식별자 (자동 증가)
|
||||
project_id: 연결된 Project의 id (외래키)
|
||||
lyric_id: 연결된 Lyric의 id (외래키)
|
||||
task_id: 노래 생성 작업의 고유 식별자 (KSUID 형식)
|
||||
task_id: 노래 생성 작업의 고유 식별자 (UUID7 형식)
|
||||
suno_task_id: Suno API 작업 고유 식별자 (선택)
|
||||
status: 처리 상태 (processing, uploading, completed, failed)
|
||||
song_prompt: 노래 생성에 사용된 프롬프트
|
||||
@@ -72,10 +72,10 @@ class Song(Base):
|
||||
)
|
||||
|
||||
task_id: Mapped[str] = mapped_column(
|
||||
String(27),
|
||||
String(36),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
comment="노래 생성 작업 고유 식별자 (KSUID)",
|
||||
comment="노래 생성 작업 고유 식별자 (UUID7)",
|
||||
)
|
||||
|
||||
suno_task_id: Mapped[Optional[str]] = mapped_column(
|
||||
|
||||
@@ -5,10 +5,14 @@
|
||||
"""
|
||||
|
||||
import logging
|
||||
import random
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Request, status
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from config import prj_settings
|
||||
@@ -16,7 +20,7 @@ from app.database.session import get_session
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
from app.user.dependencies import get_current_user
|
||||
from app.user.models import User
|
||||
from app.user.models import RefreshToken, User
|
||||
from app.user.schemas.user_schema import (
|
||||
AccessTokenResponse,
|
||||
KakaoCodeRequest,
|
||||
@@ -26,9 +30,56 @@ from app.user.schemas.user_schema import (
|
||||
UserResponse,
|
||||
)
|
||||
from app.user.services import auth_service, kakao_client
|
||||
from app.user.services.jwt import (
|
||||
create_access_token,
|
||||
create_refresh_token,
|
||||
get_access_token_expire_seconds,
|
||||
get_refresh_token_expires_at,
|
||||
get_token_hash,
|
||||
)
|
||||
from app.utils.common import generate_uuid
|
||||
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
# =============================================================================
|
||||
# 테스트용 라우터 (DEBUG 모드에서만 main.py에서 등록됨)
|
||||
# =============================================================================
|
||||
test_router = APIRouter(prefix="/auth/test", tags=["Test Auth"])
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 테스트용 스키마
|
||||
# =============================================================================
|
||||
class TestUserCreateRequest(BaseModel):
|
||||
"""테스트 사용자 생성 요청"""
|
||||
|
||||
nickname: str = "테스트유저"
|
||||
|
||||
|
||||
class TestUserCreateResponse(BaseModel):
|
||||
"""테스트 사용자 생성 응답"""
|
||||
|
||||
user_id: int
|
||||
user_uuid: str
|
||||
nickname: str
|
||||
message: str
|
||||
|
||||
|
||||
class TestTokenRequest(BaseModel):
|
||||
"""테스트 토큰 발급 요청"""
|
||||
|
||||
user_uuid: str
|
||||
|
||||
|
||||
class TestTokenResponse(BaseModel):
|
||||
"""테스트 토큰 발급 응답"""
|
||||
|
||||
access_token: str
|
||||
refresh_token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_in: int
|
||||
|
||||
|
||||
@router.get(
|
||||
"/kakao/login",
|
||||
@@ -245,3 +296,143 @@ async def get_me(
|
||||
현재 로그인한 사용자의 상세 정보를 반환합니다.
|
||||
"""
|
||||
return UserResponse.model_validate(current_user)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 테스트용 엔드포인트 (DEBUG 모드에서만 main.py에서 라우터가 등록됨)
|
||||
# =============================================================================
|
||||
@test_router.post(
|
||||
"/create-user",
|
||||
response_model=TestUserCreateResponse,
|
||||
summary="[테스트] 사용자 직접 생성",
|
||||
description="""
|
||||
**DEBUG 모드에서만 사용 가능합니다.**
|
||||
|
||||
카카오 로그인 없이 테스트용 사용자를 직접 생성합니다.
|
||||
생성된 user_uuid로 `/generate-token` 엔드포인트에서 토큰을 발급받을 수 있습니다.
|
||||
""",
|
||||
)
|
||||
async def create_test_user(
|
||||
body: TestUserCreateRequest,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> TestUserCreateResponse:
|
||||
"""
|
||||
테스트용 사용자 직접 생성
|
||||
|
||||
카카오 로그인 없이 테스트용 사용자를 생성합니다.
|
||||
DEBUG 모드에서만 사용 가능합니다.
|
||||
"""
|
||||
logger.info(f"[TEST] 테스트 사용자 생성 요청 - nickname: {body.nickname}")
|
||||
|
||||
# 고유한 uuid 생성
|
||||
user_uuid = await generate_uuid(session=session, table_name=User)
|
||||
|
||||
# 테스트용 가짜 kakao_id 생성 (충돌 방지를 위해 큰 범위 사용)
|
||||
fake_kakao_id = random.randint(9000000000, 9999999999)
|
||||
|
||||
# 사용자 생성
|
||||
new_user = User(
|
||||
kakao_id=fake_kakao_id,
|
||||
user_uuid=user_uuid,
|
||||
nickname=body.nickname,
|
||||
is_active=True,
|
||||
)
|
||||
session.add(new_user)
|
||||
await session.commit()
|
||||
await session.refresh(new_user)
|
||||
|
||||
logger.info(
|
||||
f"[TEST] 테스트 사용자 생성 완료 - user_id: {new_user.id}, "
|
||||
f"user_uuid: {new_user.user_uuid}"
|
||||
)
|
||||
|
||||
return TestUserCreateResponse(
|
||||
user_id=new_user.id,
|
||||
user_uuid=new_user.user_uuid,
|
||||
nickname=new_user.nickname or body.nickname,
|
||||
message="테스트 사용자가 생성되었습니다.",
|
||||
)
|
||||
|
||||
|
||||
@test_router.post(
|
||||
"/generate-token",
|
||||
response_model=TestTokenResponse,
|
||||
summary="[테스트] 토큰 직접 발급",
|
||||
description="""
|
||||
**DEBUG 모드에서만 사용 가능합니다.**
|
||||
|
||||
user_uuid로 JWT 토큰을 직접 발급합니다.
|
||||
`/create-user`에서 생성한 사용자의 user_uuid를 사용하세요.
|
||||
""",
|
||||
)
|
||||
async def generate_test_token(
|
||||
request: Request,
|
||||
body: TestTokenRequest,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
user_agent: Optional[str] = Header(None, alias="User-Agent"),
|
||||
) -> TestTokenResponse:
|
||||
"""
|
||||
테스트용 토큰 직접 발급
|
||||
|
||||
카카오 로그인 없이 user_uuid로 JWT 토큰을 발급합니다.
|
||||
DEBUG 모드에서만 사용 가능합니다.
|
||||
"""
|
||||
logger.info(f"[TEST] 테스트 토큰 발급 요청 - user_uuid: {body.user_uuid}")
|
||||
|
||||
# 사용자 조회
|
||||
result = await session.execute(
|
||||
select(User).where(User.user_uuid == body.user_uuid)
|
||||
)
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"사용자를 찾을 수 없습니다: {body.user_uuid}",
|
||||
)
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="비활성화된 사용자입니다.",
|
||||
)
|
||||
|
||||
# JWT 토큰 생성
|
||||
access_token = create_access_token(user.user_uuid)
|
||||
refresh_token = create_refresh_token(user.user_uuid)
|
||||
|
||||
# 클라이언트 IP 추출
|
||||
ip_address = request.client.host if request.client else None
|
||||
forwarded_for = request.headers.get("X-Forwarded-For")
|
||||
if forwarded_for:
|
||||
ip_address = forwarded_for.split(",")[0].strip()
|
||||
|
||||
# 리프레시 토큰 DB 저장
|
||||
token_hash = get_token_hash(refresh_token)
|
||||
expires_at = get_refresh_token_expires_at()
|
||||
|
||||
db_refresh_token = RefreshToken(
|
||||
user_id=user.id,
|
||||
user_uuid=user.user_uuid,
|
||||
token_hash=token_hash,
|
||||
expires_at=expires_at,
|
||||
user_agent=user_agent,
|
||||
ip_address=ip_address,
|
||||
)
|
||||
session.add(db_refresh_token)
|
||||
|
||||
# 마지막 로그인 시간 업데이트
|
||||
user.last_login_at = datetime.now(timezone.utc)
|
||||
await session.commit()
|
||||
|
||||
logger.info(
|
||||
f"[TEST] 테스트 토큰 발급 완료 - user_id: {user.id}, "
|
||||
f"user_uuid: {user.user_uuid}"
|
||||
)
|
||||
|
||||
return TestTokenResponse(
|
||||
access_token=access_token,
|
||||
refresh_token=refresh_token,
|
||||
token_type="Bearer",
|
||||
expires_in=get_access_token_expire_seconds(),
|
||||
)
|
||||
@@ -45,7 +45,7 @@ class UserAdmin(ModelView, model=User):
|
||||
form_excluded_columns = [
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"user_projects",
|
||||
"projects",
|
||||
"refresh_tokens",
|
||||
"social_accounts",
|
||||
]
|
||||
|
||||
@@ -58,14 +58,14 @@ async def get_current_user(
|
||||
if payload.get("type") != "access":
|
||||
raise InvalidTokenError("액세스 토큰이 아닙니다.")
|
||||
|
||||
user_ksuid = payload.get("sub")
|
||||
if user_ksuid is None:
|
||||
user_uuid = payload.get("sub")
|
||||
if user_uuid is None:
|
||||
raise InvalidTokenError()
|
||||
|
||||
# 사용자 조회
|
||||
result = await session.execute(
|
||||
select(User).where(
|
||||
User.user_ksuid == user_ksuid,
|
||||
User.user_uuid == user_uuid,
|
||||
User.is_deleted == False, # noqa: E712
|
||||
)
|
||||
)
|
||||
@@ -106,13 +106,13 @@ async def get_current_user_optional(
|
||||
if payload.get("type") != "access":
|
||||
return None
|
||||
|
||||
user_ksuid = payload.get("sub")
|
||||
if user_ksuid is None:
|
||||
user_uuid = payload.get("sub")
|
||||
if user_uuid is None:
|
||||
return None
|
||||
|
||||
result = await session.execute(
|
||||
select(User).where(
|
||||
User.user_ksuid == user_ksuid,
|
||||
User.user_uuid == user_uuid,
|
||||
User.is_deleted == False, # noqa: E712
|
||||
)
|
||||
)
|
||||
|
||||
@@ -111,7 +111,7 @@ class MissingTokenError(AuthException):
|
||||
class UserNotFoundError(AuthException):
|
||||
"""사용자 없음"""
|
||||
|
||||
def __init__(self, message: str = "사용자를 찾을 수 없습니다."):
|
||||
def __init__(self, message: str = "가입되지 않은 사용자 입니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
code="USER_NOT_FOUND",
|
||||
@@ -122,7 +122,7 @@ class UserNotFoundError(AuthException):
|
||||
class UserInactiveError(AuthException):
|
||||
"""비활성화된 계정"""
|
||||
|
||||
def __init__(self, message: str = "비활성화된 계정입니다. 관리자에게 문의하세요."):
|
||||
def __init__(self, message: str = "활성화 상태가 아닌 사용자 입니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
code="USER_INACTIVE",
|
||||
|
||||
+25
-27
@@ -14,7 +14,7 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app.database.session import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.home.models import UserProject
|
||||
from app.home.models import Project
|
||||
|
||||
|
||||
class User(Base):
|
||||
@@ -26,7 +26,7 @@ class User(Base):
|
||||
Attributes:
|
||||
id: 고유 식별자 (자동 증가)
|
||||
kakao_id: 카카오 고유 ID (필수, 유니크)
|
||||
user_ksuid: 사용자 식별을 위한 KSUID (필수, 유니크)
|
||||
user_uuid: 사용자 식별을 위한 UUID7 (필수, 유니크)
|
||||
email: 이메일 주소 (선택, 카카오에서 제공 시)
|
||||
nickname: 카카오 닉네임 (선택)
|
||||
profile_image_url: 카카오 프로필 이미지 URL (선택)
|
||||
@@ -54,8 +54,7 @@ class User(Base):
|
||||
- 실제 데이터는 DB에 유지됨
|
||||
|
||||
Relationships:
|
||||
user_projects: Project와의 M:N 관계 (중계 테이블 통한 연결)
|
||||
projects: 사용자가 참여한 프로젝트 목록 (Association Proxy)
|
||||
projects: 사용자가 소유한 프로젝트 목록 (1:N 관계)
|
||||
|
||||
카카오 API 응답 필드 매핑:
|
||||
- kakao_id: id (카카오 회원번호)
|
||||
@@ -70,7 +69,7 @@ class User(Base):
|
||||
__tablename__ = "user"
|
||||
__table_args__ = (
|
||||
Index("idx_user_kakao_id", "kakao_id"),
|
||||
Index("idx_user_ksuid", "user_ksuid"),
|
||||
Index("idx_user_uuid", "user_uuid"),
|
||||
Index("idx_user_email", "email"),
|
||||
Index("idx_user_phone", "phone"),
|
||||
Index("idx_user_is_active", "is_active"),
|
||||
@@ -105,11 +104,11 @@ class User(Base):
|
||||
comment="카카오 고유 ID (회원번호)",
|
||||
)
|
||||
|
||||
user_ksuid: Mapped[str] = mapped_column(
|
||||
String(27),
|
||||
user_uuid: Mapped[str] = mapped_column(
|
||||
String(36),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
comment="사용자 식별을 위한 KSUID (K-Sortable Unique Identifier)",
|
||||
comment="사용자 식별을 위한 UUID7 (시간순 정렬 가능한 UUID)",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
@@ -231,16 +230,15 @@ class User(Base):
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# Project M:N 관계 (중계 테이블 UserProject 통한 연결)
|
||||
# Project 1:N 관계 (한 사용자가 여러 프로젝트를 소유)
|
||||
# ==========================================================================
|
||||
# back_populates: UserProject.user와 양방향 연결
|
||||
# cascade: User 삭제 시 UserProject 레코드도 삭제 (Project는 유지)
|
||||
# back_populates: Project.owner와 양방향 연결
|
||||
# cascade: 사용자 삭제 시 프로젝트는 유지 (owner가 NULL로 설정됨)
|
||||
# lazy="selectin": N+1 문제 방지
|
||||
# ==========================================================================
|
||||
user_projects: Mapped[List["UserProject"]] = relationship(
|
||||
"UserProject",
|
||||
back_populates="user",
|
||||
cascade="all, delete-orphan",
|
||||
projects: Mapped[List["Project"]] = relationship(
|
||||
"Project",
|
||||
back_populates="owner",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
@@ -291,7 +289,7 @@ class RefreshToken(Base):
|
||||
Attributes:
|
||||
id: 고유 식별자 (자동 증가)
|
||||
user_id: 사용자 외래키 (User.id 참조)
|
||||
user_ksuid: 사용자 KSUID (User.user_ksuid 참조)
|
||||
user_uuid: 사용자 UUID (User.user_uuid 참조)
|
||||
token_hash: 리프레시 토큰의 SHA-256 해시값 (원본 저장 X)
|
||||
expires_at: 토큰 만료 일시
|
||||
is_revoked: 토큰 폐기 여부 (로그아웃 시 True)
|
||||
@@ -309,7 +307,7 @@ class RefreshToken(Base):
|
||||
__tablename__ = "refresh_token"
|
||||
__table_args__ = (
|
||||
Index("idx_refresh_token_user_id", "user_id"),
|
||||
Index("idx_refresh_token_user_ksuid", "user_ksuid"),
|
||||
Index("idx_refresh_token_user_uuid", "user_uuid"),
|
||||
Index("idx_refresh_token_token_hash", "token_hash", unique=True),
|
||||
Index("idx_refresh_token_expires_at", "expires_at"),
|
||||
Index("idx_refresh_token_is_revoked", "is_revoked"),
|
||||
@@ -335,10 +333,10 @@ class RefreshToken(Base):
|
||||
comment="사용자 외래키 (User.id 참조)",
|
||||
)
|
||||
|
||||
user_ksuid: Mapped[str] = mapped_column(
|
||||
String(27),
|
||||
user_uuid: Mapped[str] = mapped_column(
|
||||
String(36),
|
||||
nullable=False,
|
||||
comment="사용자 KSUID (User.user_ksuid 참조)",
|
||||
comment="사용자 UUID (User.user_uuid 참조)",
|
||||
)
|
||||
|
||||
token_hash: Mapped[str] = mapped_column(
|
||||
@@ -438,12 +436,12 @@ class SocialAccount(Base):
|
||||
|
||||
__tablename__ = "social_account"
|
||||
__table_args__ = (
|
||||
Index("idx_social_account_user_id", "user_id"),
|
||||
Index("idx_social_account_user_uuid", "user_uuid"),
|
||||
Index("idx_social_account_platform", "platform"),
|
||||
Index("idx_social_account_is_active", "is_active"),
|
||||
Index(
|
||||
"uq_user_platform_account",
|
||||
"user_id",
|
||||
"user_uuid",
|
||||
"platform",
|
||||
"platform_user_id",
|
||||
unique=True,
|
||||
@@ -466,11 +464,11 @@ class SocialAccount(Base):
|
||||
comment="고유 식별자",
|
||||
)
|
||||
|
||||
user_id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
ForeignKey("user.id", ondelete="CASCADE"),
|
||||
user_uuid: Mapped[str] = mapped_column(
|
||||
String(36),
|
||||
ForeignKey("user.user_uuid", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="사용자 외래키 (User.id 참조)",
|
||||
comment="사용자 외래키 (User.user_uuid 참조)",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
@@ -573,7 +571,7 @@ class SocialAccount(Base):
|
||||
return (
|
||||
f"<SocialAccount("
|
||||
f"id={self.id}, "
|
||||
f"user_id={self.user_id}, "
|
||||
f"user_uuid='{self.user_uuid}', "
|
||||
f"platform='{self.platform}', "
|
||||
f"platform_username='{self.platform_username}', "
|
||||
f"is_active={self.is_active}"
|
||||
|
||||
+20
-20
@@ -24,7 +24,7 @@ from app.user.exceptions import (
|
||||
UserNotFoundError,
|
||||
)
|
||||
from app.user.models import RefreshToken, User
|
||||
from app.utils.common import generate_ksuid
|
||||
from app.utils.common import generate_uuid
|
||||
from app.user.schemas.user_schema import (
|
||||
AccessTokenResponse,
|
||||
KakaoUserInfo,
|
||||
@@ -96,28 +96,28 @@ class AuthService:
|
||||
|
||||
# 5. JWT 토큰 생성
|
||||
logger.info("[AUTH] 5단계: JWT 토큰 생성 시작")
|
||||
access_token = create_access_token(user.user_ksuid)
|
||||
refresh_token = create_refresh_token(user.user_ksuid)
|
||||
logger.debug(f"[AUTH] JWT 토큰 생성 완료 - user_ksuid: {user.user_ksuid}")
|
||||
access_token = create_access_token(user.user_uuid)
|
||||
refresh_token = create_refresh_token(user.user_uuid)
|
||||
logger.debug(f"[AUTH] JWT 토큰 생성 완료 - user_uuid: {user.user_uuid}")
|
||||
|
||||
# 6. 리프레시 토큰 DB 저장
|
||||
logger.info("[AUTH] 6단계: 리프레시 토큰 저장 시작")
|
||||
await self._save_refresh_token(
|
||||
user_id=user.id,
|
||||
user_ksuid=user.user_ksuid,
|
||||
user_uuid=user.user_uuid,
|
||||
token=refresh_token,
|
||||
session=session,
|
||||
user_agent=user_agent,
|
||||
ip_address=ip_address,
|
||||
)
|
||||
logger.debug(f"[AUTH] 리프레시 토큰 저장 완료 - user_id: {user.id}, user_ksuid: {user.user_ksuid}")
|
||||
logger.debug(f"[AUTH] 리프레시 토큰 저장 완료 - user_id: {user.id}, user_uuid: {user.user_uuid}")
|
||||
|
||||
# 7. 마지막 로그인 시간 업데이트
|
||||
user.last_login_at = datetime.now(timezone.utc)
|
||||
await session.commit()
|
||||
|
||||
redirect_url = f"{prj_settings.PROJECT_DOMAIN}"
|
||||
logger.info(f"[AUTH] 카카오 로그인 완료 - user_id: {user.id}, user_ksuid: {user.user_ksuid}, redirect_url: {redirect_url}")
|
||||
logger.info(f"[AUTH] 카카오 로그인 완료 - user_id: {user.id}, user_uuid: {user.user_uuid}, redirect_url: {redirect_url}")
|
||||
logger.debug(f"[AUTH] 응답 토큰 정보 - access_token: {access_token[:30]}..., refresh_token: {refresh_token[:30]}...")
|
||||
|
||||
return LoginResponse(
|
||||
@@ -172,8 +172,8 @@ class AuthService:
|
||||
raise TokenExpiredError()
|
||||
|
||||
# 4. 사용자 확인
|
||||
user_ksuid = payload.get("sub")
|
||||
user = await self._get_user_by_ksuid(user_ksuid, session)
|
||||
user_uuid = payload.get("sub")
|
||||
user = await self._get_user_by_uuid(user_uuid, session)
|
||||
|
||||
if user is None:
|
||||
raise UserNotFoundError()
|
||||
@@ -182,7 +182,7 @@ class AuthService:
|
||||
raise UserInactiveError()
|
||||
|
||||
# 5. 새 액세스 토큰 발급
|
||||
new_access_token = create_access_token(user.user_ksuid)
|
||||
new_access_token = create_access_token(user.user_uuid)
|
||||
|
||||
return AccessTokenResponse(
|
||||
access_token=new_access_token,
|
||||
@@ -264,10 +264,10 @@ class AuthService:
|
||||
|
||||
# 신규 사용자 생성
|
||||
logger.info(f"[AUTH] 신규 사용자 생성 시작 - kakao_id: {kakao_id}")
|
||||
ksuid = await generate_ksuid(session=session, table_name=User)
|
||||
user_uuid = await generate_uuid(session=session, table_name=User)
|
||||
new_user = User(
|
||||
kakao_id=kakao_id,
|
||||
user_ksuid=ksuid,
|
||||
user_uuid=user_uuid,
|
||||
email=kakao_account.email if kakao_account else None,
|
||||
nickname=profile.nickname if profile else None,
|
||||
profile_image_url=profile.profile_image_url if profile else None,
|
||||
@@ -316,7 +316,7 @@ class AuthService:
|
||||
async def _save_refresh_token(
|
||||
self,
|
||||
user_id: int,
|
||||
user_ksuid: str,
|
||||
user_uuid: str,
|
||||
token: str,
|
||||
session: AsyncSession,
|
||||
user_agent: Optional[str] = None,
|
||||
@@ -327,7 +327,7 @@ class AuthService:
|
||||
|
||||
Args:
|
||||
user_id: 사용자 ID
|
||||
user_ksuid: 사용자 KSUID
|
||||
user_uuid: 사용자 UUID
|
||||
token: 리프레시 토큰
|
||||
session: DB 세션
|
||||
user_agent: User-Agent
|
||||
@@ -341,7 +341,7 @@ class AuthService:
|
||||
|
||||
refresh_token = RefreshToken(
|
||||
user_id=user_id,
|
||||
user_ksuid=user_ksuid,
|
||||
user_uuid=user_uuid,
|
||||
token_hash=token_hash,
|
||||
expires_at=expires_at,
|
||||
user_agent=user_agent,
|
||||
@@ -391,23 +391,23 @@ class AuthService:
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
async def _get_user_by_ksuid(
|
||||
async def _get_user_by_uuid(
|
||||
self,
|
||||
user_ksuid: str,
|
||||
user_uuid: str,
|
||||
session: AsyncSession,
|
||||
) -> Optional[User]:
|
||||
"""
|
||||
KSUID로 사용자 조회
|
||||
UUID로 사용자 조회
|
||||
|
||||
Args:
|
||||
user_ksuid: 사용자 KSUID
|
||||
user_uuid: 사용자 UUID
|
||||
session: DB 세션
|
||||
|
||||
Returns:
|
||||
User 객체 또는 None
|
||||
"""
|
||||
result = await session.execute(
|
||||
select(User).where(User.user_ksuid == user_ksuid, User.is_deleted == False) # noqa: E712
|
||||
select(User).where(User.user_uuid == user_uuid, User.is_deleted == False) # noqa: E712
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
@@ -13,12 +13,12 @@ from jose import JWTError, jwt
|
||||
from config import jwt_settings
|
||||
|
||||
|
||||
def create_access_token(user_ksuid: str) -> str:
|
||||
def create_access_token(user_uuid: str) -> str:
|
||||
"""
|
||||
JWT 액세스 토큰 생성
|
||||
|
||||
Args:
|
||||
user_ksuid: 사용자 KSUID
|
||||
user_uuid: 사용자 UUID
|
||||
|
||||
Returns:
|
||||
JWT 액세스 토큰 문자열
|
||||
@@ -27,7 +27,7 @@ def create_access_token(user_ksuid: str) -> str:
|
||||
minutes=jwt_settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
)
|
||||
to_encode = {
|
||||
"sub": user_ksuid,
|
||||
"sub": user_uuid,
|
||||
"exp": expire,
|
||||
"type": "access",
|
||||
}
|
||||
@@ -38,12 +38,12 @@ def create_access_token(user_ksuid: str) -> str:
|
||||
)
|
||||
|
||||
|
||||
def create_refresh_token(user_ksuid: str) -> str:
|
||||
def create_refresh_token(user_uuid: str) -> str:
|
||||
"""
|
||||
JWT 리프레시 토큰 생성
|
||||
|
||||
Args:
|
||||
user_ksuid: 사용자 KSUID
|
||||
user_uuid: 사용자 UUID
|
||||
|
||||
Returns:
|
||||
JWT 리프레시 토큰 문자열
|
||||
@@ -52,7 +52,7 @@ def create_refresh_token(user_ksuid: str) -> str:
|
||||
days=jwt_settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS
|
||||
)
|
||||
to_encode = {
|
||||
"sub": user_ksuid,
|
||||
"sub": user_uuid,
|
||||
"exp": expire,
|
||||
"type": "refresh",
|
||||
}
|
||||
|
||||
+67
-20
@@ -4,24 +4,71 @@ Common Utility Functions
|
||||
공통으로 사용되는 유틸리티 함수들을 정의합니다.
|
||||
|
||||
사용 예시:
|
||||
from app.utils.common import generate_task_id, generate_ksuid
|
||||
from app.utils.common import generate_task_id, generate_uuid
|
||||
|
||||
# task_id 생성
|
||||
task_id = await generate_task_id(session=session, table_name=Project)
|
||||
|
||||
# ksuid 생성
|
||||
ksuid = await generate_ksuid(session=session, table_name=User)
|
||||
# uuid 생성
|
||||
user_uuid = await generate_uuid(session=session, table_name=User)
|
||||
|
||||
Note:
|
||||
페이지네이션 기능은 app.utils.pagination 모듈을 사용하세요:
|
||||
from app.utils.pagination import PaginatedResponse, get_paginated
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional, Type
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from svix_ksuid import Ksuid
|
||||
|
||||
|
||||
def _generate_uuid7_string() -> str:
|
||||
"""UUID7 문자열을 생성합니다.
|
||||
|
||||
UUID7 구조 (RFC 9562):
|
||||
- 48 bits: Unix timestamp (밀리초)
|
||||
- 4 bits: 버전 (7)
|
||||
- 12 bits: 랜덤
|
||||
- 2 bits: variant (10)
|
||||
- 62 bits: 랜덤
|
||||
- 총 128 bits -> 36자 (하이픈 포함)
|
||||
|
||||
Returns:
|
||||
36자리 UUID7 문자열 (xxxxxxxx-xxxx-7xxx-yxxx-xxxxxxxxxxxx)
|
||||
"""
|
||||
# 현재 시간 (밀리초)
|
||||
timestamp_ms = int(time.time() * 1000)
|
||||
|
||||
# 랜덤 바이트 (10바이트 = 80비트)
|
||||
random_bytes = os.urandom(10)
|
||||
|
||||
# UUID7 바이트 구성 (16바이트 = 128비트)
|
||||
# 처음 6바이트: 타임스탬프 (48비트)
|
||||
uuid_bytes = timestamp_ms.to_bytes(6, byteorder="big")
|
||||
|
||||
# 다음 2바이트: 버전(7) + 랜덤 12비트
|
||||
# 0x7000 | (random 12 bits)
|
||||
rand_a = int.from_bytes(random_bytes[0:2], byteorder="big")
|
||||
version_rand = (0x7000 | (rand_a & 0x0FFF)).to_bytes(2, byteorder="big")
|
||||
uuid_bytes += version_rand
|
||||
|
||||
# 다음 2바이트: variant(10) + 랜덤 62비트의 앞 6비트
|
||||
# 0x80 | (random 6 bits) + random 8 bits
|
||||
rand_b = random_bytes[2]
|
||||
variant_rand = bytes([0x80 | (rand_b & 0x3F)]) + random_bytes[3:4]
|
||||
uuid_bytes += variant_rand
|
||||
|
||||
# 나머지 6바이트: 랜덤
|
||||
uuid_bytes += random_bytes[4:10]
|
||||
|
||||
# 16진수로 변환
|
||||
hex_str = uuid_bytes.hex()
|
||||
|
||||
# UUID 형식으로 포맷팅 (8-4-4-4-12)
|
||||
return f"{hex_str[:8]}-{hex_str[8:12]}-{hex_str[12:16]}-{hex_str[16:20]}-{hex_str[20:32]}"
|
||||
|
||||
|
||||
async def generate_task_id(
|
||||
@@ -35,16 +82,16 @@ async def generate_task_id(
|
||||
table_name: task_id 컬럼이 있는 SQLAlchemy 테이블 클래스 (optional)
|
||||
|
||||
Returns:
|
||||
str: 생성된 ksuid 문자열
|
||||
str: 생성된 UUID7 문자열 (36자)
|
||||
|
||||
Usage:
|
||||
# 단순 ksuid 생성
|
||||
# 단순 UUID7 생성
|
||||
task_id = await generate_task_id()
|
||||
|
||||
# 테이블에서 중복 검사 후 생성
|
||||
task_id = await generate_task_id(session=session, table_name=Project)
|
||||
"""
|
||||
task_id = str(Ksuid())
|
||||
task_id = _generate_uuid7_string()
|
||||
|
||||
if session is None or table_name is None:
|
||||
return task_id
|
||||
@@ -58,41 +105,41 @@ async def generate_task_id(
|
||||
if existing is None:
|
||||
return task_id
|
||||
|
||||
task_id = str(Ksuid())
|
||||
task_id = _generate_uuid7_string()
|
||||
|
||||
|
||||
async def generate_ksuid(
|
||||
async def generate_uuid(
|
||||
session: Optional[AsyncSession] = None,
|
||||
table_name: Optional[Type[Any]] = None,
|
||||
) -> str:
|
||||
"""고유한 ksuid를 생성합니다.
|
||||
"""고유한 UUID7을 생성합니다.
|
||||
|
||||
Args:
|
||||
session: SQLAlchemy AsyncSession (optional)
|
||||
table_name: user_ksuid 컬럼이 있는 SQLAlchemy 테이블 클래스 (optional)
|
||||
table_name: user_uuid 컬럼이 있는 SQLAlchemy 테이블 클래스 (optional)
|
||||
|
||||
Returns:
|
||||
str: 생성된 ksuid 문자열
|
||||
str: 생성된 UUID7 문자열 (36자)
|
||||
|
||||
Usage:
|
||||
# 단순 ksuid 생성
|
||||
ksuid = await generate_ksuid()
|
||||
# 단순 UUID7 생성
|
||||
new_uuid = await generate_uuid()
|
||||
|
||||
# 테이블에서 중복 검사 후 생성
|
||||
ksuid = await generate_ksuid(session=session, table_name=User)
|
||||
new_uuid = await generate_uuid(session=session, table_name=User)
|
||||
"""
|
||||
ksuid = str(Ksuid())
|
||||
new_uuid = _generate_uuid7_string()
|
||||
|
||||
if session is None or table_name is None:
|
||||
return ksuid
|
||||
return new_uuid
|
||||
|
||||
while True:
|
||||
result = await session.execute(
|
||||
select(table_name).where(table_name.user_ksuid == ksuid)
|
||||
select(table_name).where(table_name.user_uuid == new_uuid)
|
||||
)
|
||||
existing = result.scalar_one_or_none()
|
||||
|
||||
if existing is None:
|
||||
return ksuid
|
||||
return new_uuid
|
||||
|
||||
ksuid = str(Ksuid())
|
||||
new_uuid = _generate_uuid7_string()
|
||||
@@ -5,14 +5,14 @@ Azure Blob Storage에 파일을 업로드하는 클래스를 제공합니다.
|
||||
파일 경로 또는 바이트 데이터를 직접 업로드할 수 있습니다.
|
||||
|
||||
URL 경로 형식:
|
||||
- 음악: {BASE_URL}/{task_id}/song/{파일명}
|
||||
- 영상: {BASE_URL}/{task_id}/video/{파일명}
|
||||
- 이미지: {BASE_URL}/{task_id}/image/{파일명}
|
||||
- 음악: {BASE_URL}/{user_uuid}/{task_id}/song/{파일명}
|
||||
- 영상: {BASE_URL}/{user_uuid}/{task_id}/video/{파일명}
|
||||
- 이미지: {BASE_URL}/{user_uuid}/{task_id}/image/{파일명}
|
||||
|
||||
사용 예시:
|
||||
from app.utils.upload_blob_as_request import AzureBlobUploader
|
||||
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
|
||||
# 파일 경로로 업로드
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
@@ -79,14 +79,15 @@ class AzureBlobUploader:
|
||||
"""Azure Blob Storage 업로드 클래스
|
||||
|
||||
Azure Blob Storage에 음악, 영상, 이미지 파일을 업로드합니다.
|
||||
URL 형식: {BASE_URL}/{task_id}/{category}/{file_name}?{SAS_TOKEN}
|
||||
URL 형식: {BASE_URL}/{user_uuid}/{task_id}/{category}/{file_name}?{SAS_TOKEN}
|
||||
|
||||
카테고리별 경로:
|
||||
- 음악: {task_id}/song/{file_name}
|
||||
- 영상: {task_id}/video/{file_name}
|
||||
- 이미지: {task_id}/image/{file_name}
|
||||
- 음악: {user_uuid}/{task_id}/song/{file_name}
|
||||
- 영상: {user_uuid}/{task_id}/video/{file_name}
|
||||
- 이미지: {user_uuid}/{task_id}/image/{file_name}
|
||||
|
||||
Attributes:
|
||||
user_uuid: 사용자 고유 식별자 (UUID)
|
||||
task_id: 작업 고유 식별자
|
||||
"""
|
||||
|
||||
@@ -100,17 +101,24 @@ class AzureBlobUploader:
|
||||
".bmp": "image/bmp",
|
||||
}
|
||||
|
||||
def __init__(self, task_id: str):
|
||||
def __init__(self, user_uuid: str, task_id: str):
|
||||
"""AzureBlobUploader 초기화
|
||||
|
||||
Args:
|
||||
user_uuid: 사용자 고유 식별자 (UUID)
|
||||
task_id: 작업 고유 식별자
|
||||
"""
|
||||
self._user_uuid = user_uuid
|
||||
self._task_id = task_id
|
||||
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL
|
||||
self._sas_token = azure_blob_settings.AZURE_BLOB_SAS_TOKEN
|
||||
self._last_public_url: str = ""
|
||||
|
||||
@property
|
||||
def user_uuid(self) -> str:
|
||||
"""사용자 고유 식별자 (UUID)"""
|
||||
return self._user_uuid
|
||||
|
||||
@property
|
||||
def task_id(self) -> str:
|
||||
"""작업 고유 식별자"""
|
||||
@@ -126,12 +134,12 @@ class AzureBlobUploader:
|
||||
# SAS 토큰 앞뒤의 ?, ', " 제거
|
||||
sas_token = self._sas_token.strip("?'\"")
|
||||
return (
|
||||
f"{self._base_url}/{self._task_id}/{category}/{file_name}?{sas_token}"
|
||||
f"{self._base_url}/{self._user_uuid}/{self._task_id}/{category}/{file_name}?{sas_token}"
|
||||
)
|
||||
|
||||
def _build_public_url(self, category: str, file_name: str) -> str:
|
||||
"""공개 URL 생성 (SAS 토큰 제외)"""
|
||||
return f"{self._base_url}/{self._task_id}/{category}/{file_name}"
|
||||
return f"{self._base_url}/{self._user_uuid}/{self._task_id}/{category}/{file_name}"
|
||||
|
||||
async def _upload_bytes(
|
||||
self,
|
||||
@@ -253,7 +261,7 @@ class AzureBlobUploader:
|
||||
async def upload_music(self, file_path: str) -> bool:
|
||||
"""음악 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/song/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
@@ -262,7 +270,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -279,7 +287,7 @@ class AzureBlobUploader:
|
||||
) -> bool:
|
||||
"""음악 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/song/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
@@ -289,7 +297,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -315,7 +323,7 @@ class AzureBlobUploader:
|
||||
async def upload_video(self, file_path: str) -> bool:
|
||||
"""영상 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/video/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
@@ -324,7 +332,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_video(file_path="my_video.mp4")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -341,7 +349,7 @@ class AzureBlobUploader:
|
||||
) -> bool:
|
||||
"""영상 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/video/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
@@ -351,7 +359,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -377,7 +385,7 @@ class AzureBlobUploader:
|
||||
async def upload_image(self, file_path: str) -> bool:
|
||||
"""이미지 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/image/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
@@ -386,7 +394,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_image(file_path="my_image.png")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -406,7 +414,7 @@ class AzureBlobUploader:
|
||||
) -> bool:
|
||||
"""이미지 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/image/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
@@ -416,7 +424,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
with open("my_image.png", "rb") as f:
|
||||
content = f.read()
|
||||
success = await uploader.upload_image_bytes(content, "my_image.png")
|
||||
@@ -445,17 +453,17 @@ class AzureBlobUploader:
|
||||
# import asyncio
|
||||
#
|
||||
# async def main():
|
||||
# uploader = AzureBlobUploader(task_id="task-123")
|
||||
# uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
#
|
||||
# # 음악 업로드 -> {BASE_URL}/task-123/song/my_song.mp3
|
||||
# # 음악 업로드 -> {BASE_URL}/user-abc/task-123/song/my_song.mp3
|
||||
# await uploader.upload_music("my_song.mp3")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# # 영상 업로드 -> {BASE_URL}/task-123/video/my_video.mp4
|
||||
# # 영상 업로드 -> {BASE_URL}/user-abc/task-123/video/my_video.mp4
|
||||
# await uploader.upload_video("my_video.mp4")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# # 이미지 업로드 -> {BASE_URL}/task-123/image/my_image.png
|
||||
# # 이미지 업로드 -> {BASE_URL}/user-abc/task-123/image/my_image.png
|
||||
# await uploader.upload_image("my_image.png")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
|
||||
@@ -23,6 +23,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.session import get_session
|
||||
from app.dependencies.pagination import PaginationParams, get_pagination_params
|
||||
from app.user.dependencies.auth import get_current_user
|
||||
from app.user.models import User
|
||||
from app.home.models import Image, Project
|
||||
from app.lyric.models import Lyric
|
||||
from app.song.models import Song, SongTimestamp
|
||||
@@ -96,6 +98,7 @@ async def generate_video(
|
||||
default="vertical",
|
||||
description="영상 방향 (horizontal: 가로형, vertical: 세로형)",
|
||||
),
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> GenerateVideoResponse:
|
||||
"""Creatomate API를 통해 영상을 생성합니다.
|
||||
|
||||
@@ -489,6 +492,7 @@ GET /video/status/render-id-123...
|
||||
async def get_video_status(
|
||||
creatomate_render_id: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> PollingVideoResponse:
|
||||
"""creatomate_render_id로 영상 생성 작업의 상태를 조회합니다.
|
||||
@@ -629,6 +633,7 @@ GET /video/download/019123ab-cdef-7890-abcd-ef1234567890
|
||||
)
|
||||
async def download_video(
|
||||
task_id: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> DownloadVideoResponse:
|
||||
"""task_id로 Video 상태를 polling하고 completed 시 Project 정보와 영상 URL을 반환합니다."""
|
||||
@@ -743,6 +748,7 @@ GET /videos/?page=1&page_size=10
|
||||
},
|
||||
)
|
||||
async def get_videos(
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
pagination: PaginationParams = Depends(get_pagination_params),
|
||||
) -> PaginatedResponse[VideoListItem]:
|
||||
|
||||
+3
-3
@@ -24,7 +24,7 @@ class Video(Base):
|
||||
project_id: 연결된 Project의 id (외래키)
|
||||
lyric_id: 연결된 Lyric의 id (외래키)
|
||||
song_id: 연결된 Song의 id (외래키)
|
||||
task_id: 영상 생성 작업의 고유 식별자 (KSUID 형식)
|
||||
task_id: 영상 생성 작업의 고유 식별자 (UUID7 형식)
|
||||
status: 처리 상태 (pending, processing, completed, failed 등)
|
||||
result_movie_url: 생성된 영상 URL (S3, CDN 경로)
|
||||
created_at: 생성 일시 (자동 설정)
|
||||
@@ -78,10 +78,10 @@ class Video(Base):
|
||||
)
|
||||
|
||||
task_id: Mapped[str] = mapped_column(
|
||||
String(27),
|
||||
String(36),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
comment="영상 생성 작업 고유 식별자 (KSUID)",
|
||||
comment="영상 생성 작업 고유 식별자 (UUID7)",
|
||||
)
|
||||
|
||||
creatomate_render_id: Mapped[Optional[str]] = mapped_column(
|
||||
|
||||
Reference in new issue
Block a user