add logger
This commit is contained in:
1 parent
1acd8846ab
commit
bf7b53c8e8
41 files changed
+1832
-694
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,141 @@
|
||||
"""
|
||||
User 모듈 커스텀 예외 정의
|
||||
|
||||
인증 및 사용자 관련 에러를 처리하기 위한 예외 클래스들입니다.
|
||||
"""
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
|
||||
class AuthException(HTTPException):
|
||||
"""인증 관련 기본 예외"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
):
|
||||
super().__init__(
|
||||
status_code=status_code,
|
||||
detail={"code": code, "message": message},
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 카카오 OAuth 관련 예외
|
||||
# =============================================================================
|
||||
class InvalidAuthCodeError(AuthException):
|
||||
"""유효하지 않은 인가 코드"""
|
||||
|
||||
def __init__(self, message: str = "유효하지 않은 인가 코드입니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
code="INVALID_CODE",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
class KakaoAuthFailedError(AuthException):
|
||||
"""카카오 인증 실패"""
|
||||
|
||||
def __init__(self, message: str = "카카오 인증에 실패했습니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
code="KAKAO_AUTH_FAILED",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
class KakaoAPIError(AuthException):
|
||||
"""카카오 API 호출 오류"""
|
||||
|
||||
def __init__(self, message: str = "카카오 API 호출 중 오류가 발생했습니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
code="KAKAO_API_ERROR",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# JWT 토큰 관련 예외
|
||||
# =============================================================================
|
||||
class TokenExpiredError(AuthException):
|
||||
"""토큰 만료"""
|
||||
|
||||
def __init__(self, message: str = "토큰이 만료되었습니다. 다시 로그인해주세요."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
code="TOKEN_EXPIRED",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
class InvalidTokenError(AuthException):
|
||||
"""유효하지 않은 토큰"""
|
||||
|
||||
def __init__(self, message: str = "유효하지 않은 토큰입니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
code="INVALID_TOKEN",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
class TokenRevokedError(AuthException):
|
||||
"""취소된 토큰"""
|
||||
|
||||
def __init__(self, message: str = "취소된 토큰입니다. 다시 로그인해주세요."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
code="TOKEN_REVOKED",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
class MissingTokenError(AuthException):
|
||||
"""토큰 누락"""
|
||||
|
||||
def __init__(self, message: str = "인증 토큰이 필요합니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
code="MISSING_TOKEN",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 사용자 관련 예외
|
||||
# =============================================================================
|
||||
class UserNotFoundError(AuthException):
|
||||
"""사용자 없음"""
|
||||
|
||||
def __init__(self, message: str = "사용자를 찾을 수 없습니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
code="USER_NOT_FOUND",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
class UserInactiveError(AuthException):
|
||||
"""비활성화된 계정"""
|
||||
|
||||
def __init__(self, message: str = "비활성화된 계정입니다. 관리자에게 문의하세요."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
code="USER_INACTIVE",
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
class AdminRequiredError(AuthException):
|
||||
"""관리자 권한 필요"""
|
||||
|
||||
def __init__(self, message: str = "관리자 권한이 필요합니다."):
|
||||
super().__init__(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
code="ADMIN_REQUIRED",
|
||||
message=message,
|
||||
)
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
User 모듈 SQLAlchemy 모델 정의
|
||||
|
||||
카카오 소셜 로그인 기반 사용자 관리 모델입니다.
|
||||
|
||||
주의: 이 모델은 현재 개발 중이므로 create_db_tables()에서 import하지 않습니다.
|
||||
테이블 생성이 필요할 때 app/database/session.py의 create_db_tables()에
|
||||
아래 import를 추가하세요:
|
||||
|
||||
from app.user.models import User # noqa: F401
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, DateTime, Index, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database.session import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
"""
|
||||
사용자 테이블 (카카오 소셜 로그인)
|
||||
|
||||
카카오 로그인을 통해 인증된 사용자 정보를 저장합니다.
|
||||
|
||||
Attributes:
|
||||
id: 고유 식별자 (자동 증가)
|
||||
kakao_id: 카카오 고유 ID (필수, 유니크)
|
||||
email: 이메일 주소 (선택, 카카오에서 제공 시)
|
||||
nickname: 카카오 닉네임 (선택)
|
||||
profile_image_url: 카카오 프로필 이미지 URL (선택)
|
||||
thumbnail_image_url: 카카오 썸네일 이미지 URL (선택)
|
||||
is_active: 계정 활성화 상태 (기본 True)
|
||||
is_admin: 관리자 여부 (기본 False)
|
||||
last_login_at: 마지막 로그인 일시
|
||||
created_at: 계정 생성 일시
|
||||
updated_at: 계정 정보 수정 일시
|
||||
|
||||
카카오 API 응답 필드 매핑:
|
||||
- kakao_id: id (카카오 회원번호)
|
||||
- email: kakao_account.email
|
||||
- nickname: kakao_account.profile.nickname 또는 properties.nickname
|
||||
- profile_image_url: kakao_account.profile.profile_image_url
|
||||
- thumbnail_image_url: kakao_account.profile.thumbnail_image_url
|
||||
"""
|
||||
|
||||
__tablename__ = "user"
|
||||
__table_args__ = (
|
||||
Index("idx_user_kakao_id", "kakao_id", unique=True),
|
||||
Index("idx_user_email", "email"),
|
||||
Index("idx_user_is_active", "is_active"),
|
||||
Index("idx_user_created_at", "created_at"),
|
||||
{
|
||||
"mysql_engine": "InnoDB",
|
||||
"mysql_charset": "utf8mb4",
|
||||
"mysql_collate": "utf8mb4_unicode_ci",
|
||||
},
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# 기본 식별자
|
||||
# ==========================================================================
|
||||
id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
primary_key=True,
|
||||
nullable=False,
|
||||
autoincrement=True,
|
||||
comment="고유 식별자",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# 카카오 소셜 로그인 필수 정보
|
||||
# ==========================================================================
|
||||
kakao_id: Mapped[int] = mapped_column(
|
||||
BigInteger,
|
||||
nullable=False,
|
||||
unique=True,
|
||||
comment="카카오 고유 ID (회원번호)",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# 카카오에서 제공하는 사용자 정보 (선택적)
|
||||
# ==========================================================================
|
||||
email: Mapped[Optional[str]] = mapped_column(
|
||||
String(255),
|
||||
nullable=True,
|
||||
comment="이메일 주소 (카카오 계정 이메일, 동의 시 제공)",
|
||||
)
|
||||
|
||||
nickname: Mapped[Optional[str]] = mapped_column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
comment="카카오 닉네임",
|
||||
)
|
||||
|
||||
profile_image_url: Mapped[Optional[str]] = mapped_column(
|
||||
String(2048),
|
||||
nullable=True,
|
||||
comment="카카오 프로필 이미지 URL",
|
||||
)
|
||||
|
||||
thumbnail_image_url: Mapped[Optional[str]] = mapped_column(
|
||||
String(2048),
|
||||
nullable=True,
|
||||
comment="카카오 썸네일 이미지 URL",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# 계정 상태 관리
|
||||
# ==========================================================================
|
||||
is_active: Mapped[bool] = mapped_column(
|
||||
Boolean,
|
||||
nullable=False,
|
||||
default=True,
|
||||
comment="계정 활성화 상태 (비활성화 시 로그인 차단)",
|
||||
)
|
||||
|
||||
is_admin: Mapped[bool] = mapped_column(
|
||||
Boolean,
|
||||
nullable=False,
|
||||
default=False,
|
||||
comment="관리자 권한 여부",
|
||||
)
|
||||
|
||||
# ==========================================================================
|
||||
# 시간 정보
|
||||
# ==========================================================================
|
||||
last_login_at: Mapped[Optional[datetime]] = mapped_column(
|
||||
DateTime,
|
||||
nullable=True,
|
||||
comment="마지막 로그인 일시",
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.now(),
|
||||
comment="계정 생성 일시",
|
||||
)
|
||||
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
comment="계정 정보 수정 일시",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"<User("
|
||||
f"id={self.id}, "
|
||||
f"kakao_id={self.kakao_id}, "
|
||||
f"nickname='{self.nickname}', "
|
||||
f"is_active={self.is_active}"
|
||||
f")>"
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
from app.user.schemas.user_schema import (
|
||||
AccessTokenResponse,
|
||||
KakaoCallbackRequest,
|
||||
KakaoLoginResponse,
|
||||
KakaoTokenResponse,
|
||||
KakaoUserInfo,
|
||||
LoginResponse,
|
||||
RefreshTokenRequest,
|
||||
TokenResponse,
|
||||
UserBriefResponse,
|
||||
UserResponse,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AccessTokenResponse",
|
||||
"KakaoCallbackRequest",
|
||||
"KakaoLoginResponse",
|
||||
"KakaoTokenResponse",
|
||||
"KakaoUserInfo",
|
||||
"LoginResponse",
|
||||
"RefreshTokenRequest",
|
||||
"TokenResponse",
|
||||
"UserBriefResponse",
|
||||
"UserResponse",
|
||||
]
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
User 모듈 Pydantic 스키마 정의
|
||||
|
||||
API 요청/응답 검증을 위한 스키마들입니다.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 카카오 OAuth 스키마
|
||||
# =============================================================================
|
||||
class KakaoLoginResponse(BaseModel):
|
||||
"""카카오 로그인 URL 응답"""
|
||||
|
||||
auth_url: str = Field(..., description="카카오 인증 페이지 URL")
|
||||
|
||||
|
||||
class KakaoCallbackRequest(BaseModel):
|
||||
"""카카오 콜백 요청 (인가 코드)"""
|
||||
|
||||
code: str = Field(..., min_length=1, description="카카오 인가 코드")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# JWT 토큰 스키마
|
||||
# =============================================================================
|
||||
class TokenResponse(BaseModel):
|
||||
"""토큰 발급 응답"""
|
||||
|
||||
access_token: str = Field(..., description="액세스 토큰")
|
||||
refresh_token: str = Field(..., description="리프레시 토큰")
|
||||
token_type: str = Field(default="Bearer", description="토큰 타입")
|
||||
expires_in: int = Field(..., description="액세스 토큰 만료 시간 (초)")
|
||||
|
||||
|
||||
class AccessTokenResponse(BaseModel):
|
||||
"""액세스 토큰 갱신 응답"""
|
||||
|
||||
access_token: str = Field(..., description="액세스 토큰")
|
||||
token_type: str = Field(default="Bearer", description="토큰 타입")
|
||||
expires_in: int = Field(..., description="액세스 토큰 만료 시간 (초)")
|
||||
|
||||
|
||||
class RefreshTokenRequest(BaseModel):
|
||||
"""토큰 갱신 요청"""
|
||||
|
||||
refresh_token: str = Field(..., min_length=1, description="리프레시 토큰")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 사용자 정보 스키마
|
||||
# =============================================================================
|
||||
class UserResponse(BaseModel):
|
||||
"""사용자 정보 응답"""
|
||||
|
||||
id: int = Field(..., description="사용자 ID")
|
||||
kakao_id: int = Field(..., description="카카오 회원번호")
|
||||
email: Optional[str] = Field(None, description="이메일")
|
||||
nickname: Optional[str] = Field(None, description="닉네임")
|
||||
profile_image_url: Optional[str] = Field(None, description="프로필 이미지 URL")
|
||||
thumbnail_image_url: Optional[str] = Field(None, description="썸네일 이미지 URL")
|
||||
is_active: bool = Field(..., description="계정 활성화 상태")
|
||||
is_admin: bool = Field(..., description="관리자 여부")
|
||||
last_login_at: Optional[datetime] = Field(None, description="마지막 로그인 일시")
|
||||
created_at: datetime = Field(..., description="가입 일시")
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class UserBriefResponse(BaseModel):
|
||||
"""사용자 간략 정보 (토큰 응답에 포함)"""
|
||||
|
||||
id: int = Field(..., description="사용자 ID")
|
||||
nickname: Optional[str] = Field(None, description="닉네임")
|
||||
email: Optional[str] = Field(None, description="이메일")
|
||||
profile_image_url: Optional[str] = Field(None, description="프로필 이미지 URL")
|
||||
is_new_user: bool = Field(..., description="신규 가입 여부")
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
"""로그인 응답 (토큰 + 사용자 정보)"""
|
||||
|
||||
access_token: str = Field(..., description="액세스 토큰")
|
||||
refresh_token: str = Field(..., description="리프레시 토큰")
|
||||
token_type: str = Field(default="Bearer", description="토큰 타입")
|
||||
expires_in: int = Field(..., description="액세스 토큰 만료 시간 (초)")
|
||||
user: UserBriefResponse = Field(..., description="사용자 정보")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 내부 사용 스키마 (카카오 API 응답 파싱)
|
||||
# =============================================================================
|
||||
class KakaoTokenResponse(BaseModel):
|
||||
"""카카오 토큰 응답 (내부 사용)"""
|
||||
|
||||
access_token: str
|
||||
token_type: str
|
||||
refresh_token: Optional[str] = None
|
||||
expires_in: int
|
||||
scope: Optional[str] = None
|
||||
refresh_token_expires_in: Optional[int] = None
|
||||
|
||||
|
||||
class KakaoProfile(BaseModel):
|
||||
"""카카오 프로필 정보 (내부 사용)"""
|
||||
|
||||
nickname: Optional[str] = None
|
||||
profile_image_url: Optional[str] = None
|
||||
thumbnail_image_url: Optional[str] = None
|
||||
is_default_image: Optional[bool] = None
|
||||
|
||||
|
||||
class KakaoAccount(BaseModel):
|
||||
"""카카오 계정 정보 (내부 사용)"""
|
||||
|
||||
email: Optional[str] = None
|
||||
profile: Optional[KakaoProfile] = None
|
||||
|
||||
|
||||
class KakaoUserInfo(BaseModel):
|
||||
"""카카오 사용자 정보 (내부 사용)"""
|
||||
|
||||
id: int
|
||||
kakao_account: Optional[KakaoAccount] = None
|
||||
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Reference in new issue
Block a user