added .cluade
This commit is contained in:
1 parent
f5130b73d7
commit
a3d3c75463
16 files changed
+848
-1
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
카카오 로그인 API 라우터
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.auth.dependencies import get_current_user_optional
|
||||
from app.auth.models import User
|
||||
from app.auth.schemas import AuthStatusResponse, TokenResponse, UserResponse
|
||||
from app.auth.services.jwt import create_access_token
|
||||
from app.auth.services.kakao import kakao_client
|
||||
from app.database.session import get_session
|
||||
|
||||
router = APIRouter(tags=["Auth"])
|
||||
|
||||
|
||||
@router.get("/auth/kakao/login")
|
||||
async def kakao_login():
|
||||
"""
|
||||
카카오 로그인 페이지로 리다이렉트
|
||||
|
||||
프론트엔드에서 이 URL을 호출하면 카카오 로그인 페이지로 이동합니다.
|
||||
"""
|
||||
auth_url = kakao_client.get_authorization_url()
|
||||
return RedirectResponse(url=auth_url)
|
||||
|
||||
|
||||
@router.get("/kakao/callback", response_model=TokenResponse)
|
||||
async def kakao_callback(
|
||||
code: str,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""
|
||||
카카오 로그인 콜백
|
||||
|
||||
카카오 로그인 성공 후 인가 코드를 받아 JWT 토큰을 발급합니다.
|
||||
"""
|
||||
# 1. 인가 코드로 액세스 토큰 획득
|
||||
token_data = await kakao_client.get_access_token(code)
|
||||
|
||||
if "error" in token_data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"카카오 토큰 발급 실패: {token_data.get('error_description', token_data.get('error'))}",
|
||||
)
|
||||
|
||||
access_token = token_data.get("access_token")
|
||||
if not access_token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="액세스 토큰을 받지 못했습니다",
|
||||
)
|
||||
|
||||
# 2. 액세스 토큰으로 사용자 정보 조회
|
||||
user_info = await kakao_client.get_user_info(access_token)
|
||||
|
||||
if "id" not in user_info:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="사용자 정보를 가져오지 못했습니다",
|
||||
)
|
||||
|
||||
kakao_id = str(user_info["id"])
|
||||
kakao_account = user_info.get("kakao_account", {})
|
||||
profile = kakao_account.get("profile", {})
|
||||
|
||||
nickname = profile.get("nickname")
|
||||
email = kakao_account.get("email")
|
||||
profile_image = profile.get("profile_image_url")
|
||||
|
||||
# 3. 기존 회원 확인 또는 신규 가입
|
||||
result = await session.execute(select(User).where(User.kakao_id == kakao_id))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if user is None:
|
||||
# 신규 가입
|
||||
user = User(
|
||||
kakao_id=kakao_id,
|
||||
nickname=nickname,
|
||||
email=email,
|
||||
profile_image=profile_image,
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
await session.refresh(user)
|
||||
else:
|
||||
# 기존 회원 - 마지막 로그인 시간 및 정보 업데이트
|
||||
user.nickname = nickname
|
||||
user.email = email
|
||||
user.profile_image = profile_image
|
||||
user.last_login_at = datetime.now(timezone.utc)
|
||||
await session.commit()
|
||||
await session.refresh(user)
|
||||
|
||||
# 4. JWT 토큰 발급
|
||||
jwt_token = create_access_token({"sub": str(user.id)})
|
||||
|
||||
return TokenResponse(
|
||||
access_token=jwt_token,
|
||||
user=UserResponse.model_validate(user),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/auth/me", response_model=AuthStatusResponse)
|
||||
async def get_auth_status(
|
||||
current_user: User | None = Depends(get_current_user_optional),
|
||||
):
|
||||
"""
|
||||
현재 인증 상태 확인
|
||||
|
||||
프론트엔드에서 로그인 상태를 확인할 때 사용합니다.
|
||||
토큰이 유효하면 사용자 정보를, 아니면 is_authenticated=False를 반환합니다.
|
||||
"""
|
||||
if current_user is None:
|
||||
return AuthStatusResponse(is_authenticated=False)
|
||||
|
||||
return AuthStatusResponse(
|
||||
is_authenticated=True,
|
||||
user=UserResponse.model_validate(current_user),
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
Auth 모듈 의존성 주입
|
||||
"""
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.auth.models import User
|
||||
from app.auth.services.jwt import decode_access_token
|
||||
from app.database.session import get_session
|
||||
|
||||
security = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(security),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> User:
|
||||
"""현재 로그인한 사용자 반환 (필수 인증)"""
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="인증이 필요합니다",
|
||||
)
|
||||
|
||||
payload = decode_access_token(credentials.credentials)
|
||||
if payload is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="유효하지 않은 토큰입니다",
|
||||
)
|
||||
|
||||
user_id = payload.get("sub")
|
||||
if user_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="유효하지 않은 토큰입니다",
|
||||
)
|
||||
|
||||
result = await session.execute(select(User).where(User.id == int(user_id)))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="사용자를 찾을 수 없습니다",
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
async def get_current_user_optional(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(security),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> User | None:
|
||||
"""현재 로그인한 사용자 반환 (선택적 인증)"""
|
||||
if credentials is None:
|
||||
return None
|
||||
|
||||
payload = decode_access_token(credentials.credentials)
|
||||
if payload is None:
|
||||
return None
|
||||
|
||||
user_id = payload.get("sub")
|
||||
if user_id is None:
|
||||
return None
|
||||
|
||||
result = await session.execute(select(User).where(User.id == int(user_id)))
|
||||
return result.scalar_one_or_none()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
Auth 모듈 SQLAlchemy 모델 정의
|
||||
|
||||
카카오 로그인 사용자 정보를 저장합니다.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, Index, Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database.session import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
"""
|
||||
사용자 테이블 (카카오 로그인)
|
||||
|
||||
Attributes:
|
||||
id: 고유 식별자 (자동 증가)
|
||||
kakao_id: 카카오 고유 ID
|
||||
nickname: 카카오 닉네임
|
||||
email: 카카오 이메일 (선택)
|
||||
profile_image: 프로필 이미지 URL
|
||||
created_at: 가입 일시
|
||||
last_login_at: 마지막 로그인 일시
|
||||
"""
|
||||
|
||||
__tablename__ = "user"
|
||||
__table_args__ = (
|
||||
Index("idx_user_kakao_id", "kakao_id"),
|
||||
{
|
||||
"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="고유 식별자",
|
||||
)
|
||||
|
||||
kakao_id: Mapped[str] = mapped_column(
|
||||
String(50),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
comment="카카오 고유 ID",
|
||||
)
|
||||
|
||||
nickname: Mapped[str | None] = mapped_column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
comment="카카오 닉네임",
|
||||
)
|
||||
|
||||
email: Mapped[str | None] = mapped_column(
|
||||
String(255),
|
||||
nullable=True,
|
||||
comment="카카오 이메일",
|
||||
)
|
||||
|
||||
profile_image: Mapped[str | None] = mapped_column(
|
||||
String(500),
|
||||
nullable=True,
|
||||
comment="프로필 이미지 URL",
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.now(),
|
||||
comment="가입 일시",
|
||||
)
|
||||
|
||||
last_login_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
comment="마지막 로그인 일시",
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<User(id={self.id}, kakao_id='{self.kakao_id}', nickname='{self.nickname}')>"
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
Auth 모듈 Pydantic 스키마
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
"""사용자 정보 응답"""
|
||||
|
||||
id: int
|
||||
kakao_id: str
|
||||
nickname: str | None
|
||||
email: str | None
|
||||
profile_image: str | None
|
||||
created_at: datetime
|
||||
last_login_at: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
"""토큰 응답"""
|
||||
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
user: UserResponse
|
||||
|
||||
|
||||
class AuthStatusResponse(BaseModel):
|
||||
"""인증 상태 응답 (프론트엔드용)"""
|
||||
|
||||
is_authenticated: bool
|
||||
user: UserResponse | None = None
|
||||
Whitespace-only changes.
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
JWT 토큰 유틸리티
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from config import security_settings
|
||||
|
||||
|
||||
def create_access_token(data: dict) -> str:
|
||||
"""JWT 액세스 토큰 생성"""
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=security_settings.JWT_EXPIRE_MINUTES)
|
||||
to_encode.update({"exp": expire})
|
||||
return jwt.encode(
|
||||
to_encode,
|
||||
security_settings.JWT_SECRET,
|
||||
algorithm=security_settings.JWT_ALGORITHM,
|
||||
)
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict | None:
|
||||
"""JWT 액세스 토큰 디코딩"""
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
token,
|
||||
security_settings.JWT_SECRET,
|
||||
algorithms=[security_settings.JWT_ALGORITHM],
|
||||
)
|
||||
return payload
|
||||
except JWTError:
|
||||
return None
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
카카오 OAuth API 클라이언트
|
||||
"""
|
||||
|
||||
import aiohttp
|
||||
|
||||
from config import kakao_settings
|
||||
|
||||
|
||||
class KakaoOAuthClient:
|
||||
"""카카오 OAuth API 클라이언트"""
|
||||
|
||||
AUTH_URL = "https://kauth.kakao.com/oauth/authorize"
|
||||
TOKEN_URL = "https://kauth.kakao.com/oauth/token"
|
||||
USER_INFO_URL = "https://kapi.kakao.com/v2/user/me"
|
||||
|
||||
def __init__(self):
|
||||
self.client_id = kakao_settings.KAKAO_CLIENT_ID
|
||||
self.client_secret = kakao_settings.KAKAO_CLIENT_SECRET
|
||||
self.redirect_uri = kakao_settings.KAKAO_REDIRECT_URI
|
||||
|
||||
def get_authorization_url(self) -> str:
|
||||
"""카카오 로그인 페이지 URL 반환"""
|
||||
return (
|
||||
f"{self.AUTH_URL}"
|
||||
f"?client_id={self.client_id}"
|
||||
f"&redirect_uri={self.redirect_uri}"
|
||||
f"&response_type=code"
|
||||
)
|
||||
|
||||
async def get_access_token(self, code: str) -> dict:
|
||||
"""인가 코드로 액세스 토큰 획득"""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
data = {
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": self.client_id,
|
||||
"client_secret": self.client_secret,
|
||||
"redirect_uri": self.redirect_uri,
|
||||
"code": code,
|
||||
}
|
||||
print(f"[kakao] Token request - client_id: {self.client_id}, redirect_uri: {self.redirect_uri}")
|
||||
async with session.post(self.TOKEN_URL, data=data) as response:
|
||||
result = await response.json()
|
||||
print(f"[kakao] Token response: {result}")
|
||||
return result
|
||||
|
||||
async def get_user_info(self, access_token: str) -> dict:
|
||||
"""액세스 토큰으로 사용자 정보 조회"""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
headers = {"Authorization": f"Bearer {access_token}"}
|
||||
async with session.get(self.USER_INFO_URL, headers=headers) as response:
|
||||
return await response.json()
|
||||
|
||||
|
||||
kakao_client = KakaoOAuthClient()
|
||||
Reference in new issue
Block a user