Some checks failed
SonarQube Analysis / SonarQube Scan (push) Has been cancelled
- 시스템 관리자/관리자 권한별 대시보드 기능 추가 - 사용자 관리 페이지: 계정 생성, 역할 변경, 사용자 삭제 - 시스템 로그 페이지: 로그인 로그, 시스템 오류 로그 조회 - 로그 모니터링 대시보드: 실시간 통계, 최근 활동, 오류 모니터링 - 프론트엔드 ErrorBoundary 및 오류 로깅 시스템 통합 - 계정 설정 페이지: 프로필 업데이트, 비밀번호 변경 - 3단계 권한 시스템 (system/admin/user) 완전 구현 - 시스템 관리자 계정 생성 기능 (hyungi/000000) - 로그인 페이지 테스트 계정 안내 제거 - API 오류 수정: CORS, 이메일 검증, User 모델 import 등
199 lines
5.9 KiB
Python
199 lines
5.9 KiB
Python
"""
|
|
초기 시스템 설정 컨트롤러
|
|
배포 후 첫 실행 시 시스템 관리자 계정 생성
|
|
"""
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
from pydantic import BaseModel, EmailStr
|
|
from typing import Optional
|
|
|
|
from ..database import get_db
|
|
from .models import User, UserRepository
|
|
from ..utils.logger import get_logger
|
|
|
|
logger = get_logger(__name__)
|
|
router = APIRouter()
|
|
|
|
|
|
class SystemSetupRequest(BaseModel):
|
|
username: str
|
|
password: str
|
|
name: str
|
|
email: Optional[EmailStr] = None
|
|
department: Optional[str] = None
|
|
position: Optional[str] = None
|
|
|
|
|
|
class SystemSetupResponse(BaseModel):
|
|
success: bool
|
|
message: str
|
|
user_id: Optional[int] = None
|
|
setup_completed: bool
|
|
|
|
|
|
@router.get("/setup/status")
|
|
async def get_setup_status(db: Session = Depends(get_db)):
|
|
"""
|
|
시스템 초기 설정 상태 확인
|
|
|
|
Returns:
|
|
Dict: 설정 완료 여부
|
|
"""
|
|
try:
|
|
user_repo = UserRepository(db)
|
|
|
|
# 시스템 관리자가 존재하는지 확인
|
|
system_admin = db.query(User).filter(User.role == 'system').first()
|
|
|
|
return {
|
|
'success': True,
|
|
'setup_completed': system_admin is not None,
|
|
'has_system_admin': system_admin is not None,
|
|
'total_users': db.query(User).count()
|
|
}
|
|
|
|
except Exception as e:
|
|
logger.error(f"Setup status check error: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="설정 상태 확인 중 오류가 발생했습니다"
|
|
)
|
|
|
|
|
|
@router.post("/setup/initialize", response_model=SystemSetupResponse)
|
|
async def initialize_system(
|
|
setup_data: SystemSetupRequest,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
시스템 초기화 및 첫 번째 시스템 관리자 생성
|
|
|
|
Args:
|
|
setup_data: 시스템 관리자 계정 정보
|
|
db: 데이터베이스 세션
|
|
|
|
Returns:
|
|
SystemSetupResponse: 설정 결과
|
|
"""
|
|
try:
|
|
user_repo = UserRepository(db)
|
|
|
|
# 이미 시스템 관리자가 존재하는지 확인
|
|
existing_admin = db.query(User).filter(User.role == 'system').first()
|
|
if existing_admin:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="시스템이 이미 초기화되었습니다"
|
|
)
|
|
|
|
# 사용자명 중복 확인
|
|
existing_user = user_repo.find_by_username(setup_data.username)
|
|
if existing_user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="이미 존재하는 사용자명입니다"
|
|
)
|
|
|
|
# 이메일 중복 확인 (이메일이 제공된 경우)
|
|
if setup_data.email:
|
|
existing_email = user_repo.find_by_email(setup_data.email)
|
|
if existing_email:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="이미 존재하는 이메일입니다"
|
|
)
|
|
|
|
# 시스템 관리자 계정 생성
|
|
user = User(
|
|
username=setup_data.username,
|
|
name=setup_data.name,
|
|
email=setup_data.email,
|
|
role='system',
|
|
access_level='system',
|
|
department=setup_data.department,
|
|
position=setup_data.position,
|
|
is_active=True
|
|
)
|
|
|
|
# 비밀번호 설정
|
|
user.set_password(setup_data.password)
|
|
|
|
# 데이터베이스에 저장
|
|
db.add(user)
|
|
db.commit()
|
|
db.refresh(user)
|
|
|
|
logger.info(f"System initialized with admin user: {user.username}")
|
|
|
|
return SystemSetupResponse(
|
|
success=True,
|
|
message="시스템이 성공적으로 초기화되었습니다",
|
|
user_id=user.user_id,
|
|
setup_completed=True
|
|
)
|
|
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
db.rollback()
|
|
logger.error(f"System initialization error: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="시스템 초기화 중 오류가 발생했습니다"
|
|
)
|
|
|
|
|
|
@router.post("/setup/reset")
|
|
async def reset_system_setup(
|
|
confirm_reset: bool = False,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
시스템 설정 리셋 (개발/테스트 용도)
|
|
|
|
Args:
|
|
confirm_reset: 리셋 확인
|
|
db: 데이터베이스 세션
|
|
|
|
Returns:
|
|
Dict: 리셋 결과
|
|
"""
|
|
try:
|
|
if not confirm_reset:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="리셋을 확인해주세요 (confirm_reset=true)"
|
|
)
|
|
|
|
# 개발 환경에서만 허용
|
|
from ..config import get_settings
|
|
settings = get_settings()
|
|
|
|
if settings.environment != 'development':
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="개발 환경에서만 시스템 리셋이 가능합니다"
|
|
)
|
|
|
|
# 모든 사용자 삭제
|
|
db.query(User).delete()
|
|
db.commit()
|
|
|
|
logger.warning("System setup has been reset (development only)")
|
|
|
|
return {
|
|
'success': True,
|
|
'message': '시스템 설정이 리셋되었습니다',
|
|
'setup_completed': False
|
|
}
|
|
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
db.rollback()
|
|
logger.error(f"System reset error: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="시스템 리셋 중 오류가 발생했습니다"
|
|
)
|