feat: OAuth 2.0 백엔드 시스템 구현 완료
Phase 1 & 2 완료: - 프로젝트 기본 구조 설정 - Docker Compose 환경 구성 (MongoDB, Redis, Backend, Frontend) - FastAPI 기반 OAuth 2.0 백엔드 구현 주요 기능: - JWT 기반 인증 시스템 - 3단계 권한 체계 (System Admin/Group Admin/User) - 사용자 관리 CRUD API - 애플리케이션 관리 CRUD API - OAuth 2.0 Authorization Code Flow - Refresh Token 관리 - 인증 히스토리 추적 API 엔드포인트: - /auth/* - 인증 관련 (register, login, logout, refresh) - /users/* - 사용자 관리 - /applications/* - 애플리케이션 관리 - /oauth/* - OAuth 2.0 플로우 보안 기능: - bcrypt 비밀번호 해싱 - JWT 토큰 인증 - CORS 설정 - Rate limiting 준비 🤖 Generated with Claude Code Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
4
oauth/backend/app/services/__init__.py
Normal file
4
oauth/backend/app/services/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
"""Service layer for business logic"""
|
||||
|
||||
from .auth_service import AuthService
|
||||
from .token_service import TokenService
|
||||
135
oauth/backend/app/services/auth_service.py
Normal file
135
oauth/backend/app/services/auth_service.py
Normal file
@ -0,0 +1,135 @@
|
||||
"""Authentication service"""
|
||||
|
||||
from typing import Optional
|
||||
from datetime import datetime, timedelta
|
||||
from bson import ObjectId
|
||||
from app.utils.database import get_database
|
||||
from app.utils.security import verify_password, hash_password
|
||||
from app.models.user import UserCreate, User, UserInDB, UserRole
|
||||
from app.models.auth_history import AuthHistoryCreate, AuthAction
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AuthService:
|
||||
"""Service for handling authentication logic"""
|
||||
|
||||
@staticmethod
|
||||
async def authenticate_user(username: str, password: str) -> Optional[UserInDB]:
|
||||
"""Authenticate a user with username/email and password"""
|
||||
db = get_database()
|
||||
|
||||
# Try to find user by username or email
|
||||
user = await db.users.find_one({
|
||||
"$or": [
|
||||
{"username": username},
|
||||
{"email": username}
|
||||
]
|
||||
})
|
||||
|
||||
if not user:
|
||||
return None
|
||||
|
||||
if not verify_password(password, user["hashed_password"]):
|
||||
return None
|
||||
|
||||
return UserInDB(**user)
|
||||
|
||||
@staticmethod
|
||||
async def create_user(user_data: UserCreate) -> User:
|
||||
"""Create a new user"""
|
||||
db = get_database()
|
||||
|
||||
# Check if user already exists
|
||||
existing_user = await db.users.find_one({
|
||||
"$or": [
|
||||
{"email": user_data.email},
|
||||
{"username": user_data.username}
|
||||
]
|
||||
})
|
||||
|
||||
if existing_user:
|
||||
raise ValueError("User with this email or username already exists")
|
||||
|
||||
# Hash password
|
||||
hashed_password = hash_password(user_data.password)
|
||||
|
||||
# Prepare user document
|
||||
user_doc = {
|
||||
**user_data.model_dump(exclude={"password"}),
|
||||
"hashed_password": hashed_password,
|
||||
"created_at": datetime.utcnow(),
|
||||
"updated_at": datetime.utcnow()
|
||||
}
|
||||
|
||||
# Insert user
|
||||
result = await db.users.insert_one(user_doc)
|
||||
user_doc["_id"] = result.inserted_id
|
||||
|
||||
return User(**user_doc)
|
||||
|
||||
@staticmethod
|
||||
async def get_user_by_id(user_id: str) -> Optional[User]:
|
||||
"""Get user by ID"""
|
||||
db = get_database()
|
||||
|
||||
try:
|
||||
user = await db.users.find_one({"_id": ObjectId(user_id)})
|
||||
if user:
|
||||
return User(**user)
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting user by ID: {e}")
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
async def log_auth_action(
|
||||
user_id: str,
|
||||
action: AuthAction,
|
||||
ip_address: str,
|
||||
user_agent: Optional[str] = None,
|
||||
application_id: Optional[str] = None,
|
||||
result: str = "success",
|
||||
details: Optional[dict] = None
|
||||
):
|
||||
"""Log authentication action"""
|
||||
db = get_database()
|
||||
|
||||
history_doc = {
|
||||
"user_id": user_id,
|
||||
"application_id": application_id,
|
||||
"action": action.value,
|
||||
"ip_address": ip_address,
|
||||
"user_agent": user_agent,
|
||||
"result": result,
|
||||
"details": details,
|
||||
"created_at": datetime.utcnow()
|
||||
}
|
||||
|
||||
await db.auth_history.insert_one(history_doc)
|
||||
|
||||
@staticmethod
|
||||
async def create_admin_user():
|
||||
"""Create default admin user if not exists"""
|
||||
from app.config import settings
|
||||
|
||||
db = get_database()
|
||||
|
||||
# Check if admin exists
|
||||
admin = await db.users.find_one({"email": settings.admin_email})
|
||||
|
||||
if not admin:
|
||||
admin_data = UserCreate(
|
||||
email=settings.admin_email,
|
||||
username="admin",
|
||||
password=settings.admin_password,
|
||||
full_name="System Administrator",
|
||||
role=UserRole.SYSTEM_ADMIN
|
||||
)
|
||||
|
||||
try:
|
||||
await AuthService.create_user(admin_data)
|
||||
logger.info("Admin user created successfully")
|
||||
except ValueError:
|
||||
logger.info("Admin user already exists")
|
||||
201
oauth/backend/app/services/token_service.py
Normal file
201
oauth/backend/app/services/token_service.py
Normal file
@ -0,0 +1,201 @@
|
||||
"""Token management service"""
|
||||
|
||||
from typing import Optional, Dict, Any
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from bson import ObjectId
|
||||
from app.utils.database import get_database
|
||||
from app.utils.security import create_access_token, create_refresh_token, decode_token
|
||||
from app.models.user import Token
|
||||
import logging
|
||||
import secrets
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TokenService:
|
||||
"""Service for handling token operations"""
|
||||
|
||||
@staticmethod
|
||||
async def create_tokens(user_id: str, user_data: Dict[str, Any]) -> Token:
|
||||
"""Create access and refresh tokens for a user"""
|
||||
# Create access token
|
||||
access_token = create_access_token(
|
||||
data={
|
||||
"sub": user_id,
|
||||
"username": user_data.get("username"),
|
||||
"role": user_data.get("role"),
|
||||
"email": user_data.get("email")
|
||||
}
|
||||
)
|
||||
|
||||
# Create refresh token
|
||||
refresh_token = create_refresh_token(
|
||||
data={
|
||||
"sub": user_id,
|
||||
"username": user_data.get("username")
|
||||
}
|
||||
)
|
||||
|
||||
# Store refresh token in database
|
||||
await TokenService.store_refresh_token(user_id, refresh_token)
|
||||
|
||||
return Token(
|
||||
access_token=access_token,
|
||||
refresh_token=refresh_token,
|
||||
token_type="bearer"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def store_refresh_token(user_id: str, token: str):
|
||||
"""Store refresh token in database"""
|
||||
db = get_database()
|
||||
|
||||
from app.config import settings
|
||||
expires_at = datetime.utcnow() + timedelta(
|
||||
days=settings.jwt_refresh_token_expire_days
|
||||
)
|
||||
|
||||
token_doc = {
|
||||
"token": token,
|
||||
"user_id": user_id,
|
||||
"created_at": datetime.utcnow(),
|
||||
"expires_at": expires_at,
|
||||
"is_active": True
|
||||
}
|
||||
|
||||
await db.refresh_tokens.insert_one(token_doc)
|
||||
|
||||
@staticmethod
|
||||
async def verify_refresh_token(token: str) -> Optional[str]:
|
||||
"""Verify refresh token and return user_id"""
|
||||
db = get_database()
|
||||
|
||||
# Decode token
|
||||
payload = decode_token(token)
|
||||
if not payload or payload.get("type") != "refresh":
|
||||
return None
|
||||
|
||||
# Check if token exists in database
|
||||
token_doc = await db.refresh_tokens.find_one({
|
||||
"token": token,
|
||||
"is_active": True
|
||||
})
|
||||
|
||||
if not token_doc:
|
||||
return None
|
||||
|
||||
# Check if token is expired
|
||||
if token_doc["expires_at"] < datetime.utcnow():
|
||||
# Mark token as inactive
|
||||
await db.refresh_tokens.update_one(
|
||||
{"_id": token_doc["_id"]},
|
||||
{"$set": {"is_active": False}}
|
||||
)
|
||||
return None
|
||||
|
||||
return payload.get("sub")
|
||||
|
||||
@staticmethod
|
||||
async def revoke_refresh_token(token: str):
|
||||
"""Revoke a refresh token"""
|
||||
db = get_database()
|
||||
|
||||
await db.refresh_tokens.update_one(
|
||||
{"token": token},
|
||||
{"$set": {"is_active": False}}
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def revoke_all_user_tokens(user_id: str):
|
||||
"""Revoke all refresh tokens for a user"""
|
||||
db = get_database()
|
||||
|
||||
await db.refresh_tokens.update_many(
|
||||
{"user_id": user_id},
|
||||
{"$set": {"is_active": False}}
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def create_authorization_code(
|
||||
user_id: str,
|
||||
client_id: str,
|
||||
redirect_uri: str,
|
||||
scope: str,
|
||||
state: Optional[str] = None
|
||||
) -> str:
|
||||
"""Create and store authorization code"""
|
||||
db = get_database()
|
||||
|
||||
code = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.utcnow() + timedelta(minutes=10) # Code valid for 10 minutes
|
||||
|
||||
code_doc = {
|
||||
"code": code,
|
||||
"user_id": user_id,
|
||||
"client_id": client_id,
|
||||
"redirect_uri": redirect_uri,
|
||||
"scope": scope,
|
||||
"state": state,
|
||||
"created_at": datetime.utcnow(),
|
||||
"expires_at": expires_at,
|
||||
"used": False
|
||||
}
|
||||
|
||||
await db.authorization_codes.insert_one(code_doc)
|
||||
|
||||
return code
|
||||
|
||||
@staticmethod
|
||||
async def exchange_authorization_code(
|
||||
code: str,
|
||||
client_id: str,
|
||||
client_secret: str,
|
||||
redirect_uri: str
|
||||
) -> Optional[Token]:
|
||||
"""Exchange authorization code for tokens"""
|
||||
db = get_database()
|
||||
|
||||
# Find and validate code
|
||||
code_doc = await db.authorization_codes.find_one({
|
||||
"code": code,
|
||||
"client_id": client_id,
|
||||
"redirect_uri": redirect_uri,
|
||||
"used": False
|
||||
})
|
||||
|
||||
if not code_doc:
|
||||
return None
|
||||
|
||||
# Check if code is expired
|
||||
if code_doc["expires_at"] < datetime.utcnow():
|
||||
return None
|
||||
|
||||
# Validate client secret
|
||||
app = await db.applications.find_one({
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret
|
||||
})
|
||||
|
||||
if not app:
|
||||
return None
|
||||
|
||||
# Mark code as used
|
||||
await db.authorization_codes.update_one(
|
||||
{"_id": code_doc["_id"]},
|
||||
{"$set": {"used": True}}
|
||||
)
|
||||
|
||||
# Get user
|
||||
user = await db.users.find_one({"_id": ObjectId(code_doc["user_id"])})
|
||||
if not user:
|
||||
return None
|
||||
|
||||
# Create tokens
|
||||
return await TokenService.create_tokens(
|
||||
str(user["_id"]),
|
||||
{
|
||||
"username": user["username"],
|
||||
"role": user["role"],
|
||||
"email": user["email"]
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user