diff --git a/.claude/rules/code-style.md b/.claude/rules/code-style.md new file mode 100644 index 0000000..0cb1563 --- /dev/null +++ b/.claude/rules/code-style.md @@ -0,0 +1,59 @@ +# Java 코드 스타일 규칙 + +## 일반 +- Java 17+ 문법 사용 (record, sealed class, pattern matching, text block 활용) +- 들여쓰기: 4 spaces (탭 사용 금지) +- 줄 길이: 120자 이하 +- 파일 끝에 빈 줄 추가 + +## 클래스 구조 +클래스 내 멤버 순서: +1. static 상수 (public → private) +2. 인스턴스 필드 (public → private) +3. 생성자 +4. public 메서드 +5. protected/package-private 메서드 +6. private 메서드 +7. inner class/enum + +## Spring Boot 규칙 + +### 계층 구조 +- Controller → Service → Repository 단방향 의존 +- Controller에 비즈니스 로직 금지 (요청/응답 변환만) +- Service 계층 간 순환 참조 금지 +- Repository에 비즈니스 로직 금지 + +### DTO와 Entity 분리 +- API 요청/응답에 Entity 직접 사용 금지 +- DTO는 record 또는 불변 클래스로 작성 +- DTO ↔ Entity 변환은 매퍼 클래스 또는 팩토리 메서드 사용 + +### 의존성 주입 +- 생성자 주입 사용 (필드 주입 `@Autowired` 사용 금지) +- 단일 생성자는 `@Autowired` 어노테이션 생략 +- Lombok `@RequiredArgsConstructor` 사용 가능 + +### 트랜잭션 +- `@Transactional` 범위 최소화 +- 읽기 전용: `@Transactional(readOnly = true)` +- Service 메서드 레벨에 적용 (클래스 레벨 지양) + +## Lombok 규칙 +- `@Getter`, `@Setter` 허용 (Entity에서 Setter는 지양) +- `@Builder` 허용 +- `@Data` 사용 금지 (명시적으로 필요한 어노테이션만) +- `@AllArgsConstructor` 단독 사용 금지 (`@Builder`와 함께 사용) +- `@Slf4j` 로거 사용 + +## 예외 처리 +- 비즈니스 예외는 커스텀 Exception 클래스 정의 +- `@ControllerAdvice`로 전역 예외 처리 +- 예외 메시지에 컨텍스트 정보 포함 +- catch 블록에서 예외 무시 금지 (`// ignore` 금지) + +## 기타 +- `Optional`은 반환 타입으로만 사용 (필드, 파라미터에 사용 금지) +- `null` 반환보다 빈 컬렉션 또는 `Optional` 반환 +- Stream API 활용 (단, 3단계 이상 체이닝은 메서드 추출) +- 하드코딩된 문자열/숫자 금지 → 상수 또는 설정값으로 추출 diff --git a/.claude/rules/git-workflow.md b/.claude/rules/git-workflow.md new file mode 100644 index 0000000..4fee618 --- /dev/null +++ b/.claude/rules/git-workflow.md @@ -0,0 +1,84 @@ +# Git 워크플로우 규칙 + +## 브랜치 전략 + +### 브랜치 구조 +``` +main ← 배포 가능한 안정 브랜치 (보호됨) + └── develop ← 개발 통합 브랜치 + ├── feature/ISSUE-123-기능설명 + ├── bugfix/ISSUE-456-버그설명 + └── hotfix/ISSUE-789-긴급수정 +``` + +### 브랜치 네이밍 +- feature 브랜치: `feature/ISSUE-번호-간단설명` (예: `feature/ISSUE-42-user-login`) +- bugfix 브랜치: `bugfix/ISSUE-번호-간단설명` +- hotfix 브랜치: `hotfix/ISSUE-번호-간단설명` +- 이슈 번호가 없는 경우: `feature/간단설명` (예: `feature/add-swagger-docs`) + +### 브랜치 규칙 +- main, develop 브랜치에 직접 커밋/푸시 금지 +- feature 브랜치는 develop에서 분기 +- hotfix 브랜치는 main에서 분기 +- 머지는 반드시 MR(Merge Request)을 통해 수행 + +## 커밋 메시지 규칙 + +### Conventional Commits 형식 +``` +type(scope): subject + +body (선택) + +footer (선택) +``` + +### type (필수) +| type | 설명 | +|------|------| +| feat | 새로운 기능 추가 | +| fix | 버그 수정 | +| docs | 문서 변경 | +| style | 코드 포맷팅 (기능 변경 없음) | +| refactor | 리팩토링 (기능 변경 없음) | +| test | 테스트 추가/수정 | +| chore | 빌드, 설정 변경 | +| ci | CI/CD 설정 변경 | +| perf | 성능 개선 | + +### scope (선택) +- 변경 범위를 나타내는 짧은 단어 +- 한국어, 영어 모두 허용 (예: `feat(인증): 로그인 기능`, `fix(auth): token refresh`) + +### subject (필수) +- 변경 내용을 간결하게 설명 +- 한국어, 영어 모두 허용 +- 72자 이내 +- 마침표(.) 없이 끝냄 + +### 예시 +``` +feat(auth): JWT 기반 로그인 구현 +fix(배치): 야간 배치 타임아웃 수정 +docs: README에 빌드 방법 추가 +refactor(user-service): 중복 로직 추출 +test(결제): 환불 로직 단위 테스트 추가 +chore: Gradle 의존성 버전 업데이트 +``` + +## MR(Merge Request) 규칙 + +### MR 생성 +- 제목: 커밋 메시지와 동일한 Conventional Commits 형식 +- 본문: 변경 내용 요약, 테스트 방법, 관련 이슈 번호 +- 라벨: 적절한 라벨 부착 (feature, bugfix, hotfix 등) + +### MR 리뷰 +- 최소 1명의 리뷰어 승인 필수 +- CI 검증 통과 필수 (설정된 경우) +- 리뷰 코멘트 모두 해결 후 머지 + +### MR 머지 +- Squash Merge 권장 (깔끔한 히스토리) +- 머지 후 소스 브랜치 삭제 diff --git a/.claude/rules/naming.md b/.claude/rules/naming.md new file mode 100644 index 0000000..c1b6949 --- /dev/null +++ b/.claude/rules/naming.md @@ -0,0 +1,60 @@ +# Java 네이밍 규칙 + +## 패키지 +- 모두 소문자, 단수형 +- 도메인 역순: `com.gcsc.프로젝트명.모듈` +- 예: `com.gcsc.batch.scheduler`, `com.gcsc.api.auth` + +## 클래스 +- PascalCase +- 명사 또는 명사구 +- 접미사로 역할 표시: + +| 계층 | 접미사 | 예시 | +|------|--------|------| +| Controller | `Controller` | `UserController` | +| Service | `Service` | `UserService` | +| Service 구현 | `ServiceImpl` | `UserServiceImpl` (인터페이스 있을 때만) | +| Repository | `Repository` | `UserRepository` | +| Entity | (없음) | `User`, `ShipRoute` | +| DTO 요청 | `Request` | `CreateUserRequest` | +| DTO 응답 | `Response` | `UserResponse` | +| 설정 | `Config` | `SecurityConfig` | +| 예외 | `Exception` | `UserNotFoundException` | +| Enum | (없음) | `UserStatus`, `ShipType` | +| Mapper | `Mapper` | `UserMapper` | + +## 메서드 +- camelCase +- 동사로 시작 +- CRUD 패턴: + +| 작업 | Controller | Service | Repository | +|------|-----------|---------|------------| +| 조회(단건) | `getUser()` | `getUser()` | `findById()` | +| 조회(목록) | `getUsers()` | `getUsers()` | `findAll()` | +| 생성 | `createUser()` | `createUser()` | `save()` | +| 수정 | `updateUser()` | `updateUser()` | `save()` | +| 삭제 | `deleteUser()` | `deleteUser()` | `deleteById()` | +| 존재확인 | - | `existsUser()` | `existsById()` | + +## 변수 +- camelCase +- 의미 있는 이름 (단일 문자 변수 금지, 루프 인덱스 `i, j, k` 예외) +- boolean: `is`, `has`, `can`, `should` 접두사 + - 예: `isActive`, `hasPermission`, `canDelete` + +## 상수 +- UPPER_SNAKE_CASE +- 예: `MAX_RETRY_COUNT`, `DEFAULT_PAGE_SIZE` + +## 테스트 +- 클래스: `{대상클래스}Test` (예: `UserServiceTest`) +- 메서드: `{메서드명}_{시나리오}_{기대결과}` 또는 한국어 `@DisplayName` + - 예: `createUser_withDuplicateEmail_throwsException()` + - 예: `@DisplayName("중복 이메일로 생성 시 예외 발생")` + +## 파일/디렉토리 +- Java 파일: PascalCase (클래스명과 동일) +- 리소스 파일: kebab-case (예: `application-local.yml`) +- SQL 파일: `V{번호}__{설명}.sql` (Flyway) 또는 kebab-case diff --git a/.claude/rules/team-policy.md b/.claude/rules/team-policy.md new file mode 100644 index 0000000..16d7553 --- /dev/null +++ b/.claude/rules/team-policy.md @@ -0,0 +1,34 @@ +# 팀 정책 (Team Policy) + +이 규칙은 조직 전체에 적용되는 필수 정책입니다. +프로젝트별 `.claude/rules/`에 추가 규칙을 정의할 수 있으나, 이 정책을 위반할 수 없습니다. + +## 보안 정책 + +### 금지 행위 +- `.env`, `.env.*`, `secrets/` 파일 읽기 및 내용 출력 금지 +- 비밀번호, API 키, 토큰 등 민감 정보를 코드에 하드코딩 금지 +- `git push --force`, `git reset --hard`, `git clean -fd` 실행 금지 +- `rm -rf /`, `rm -rf ~`, `rm -rf .git` 등 파괴적 명령 실행 금지 +- main/develop 브랜치에 직접 push 금지 (MR을 통해서만 머지) + +### 인증 정보 관리 +- 환경변수 또는 외부 설정 파일(`.env`, `application-local.yml`)로 관리 +- 설정 파일은 `.gitignore`에 반드시 포함 +- 예시 파일(`.env.example`, `application.yml.example`)만 커밋 + +## 코드 품질 정책 + +### 필수 검증 +- 커밋 전 빌드(컴파일) 성공 확인 +- 린트 경고 0개 유지 (CI에서도 검증) +- 테스트 코드가 있는 프로젝트는 테스트 통과 필수 + +### 코드 리뷰 +- main 브랜치 머지 시 최소 1명 리뷰 필수 +- 리뷰어 승인 없이 머지 불가 + +## 문서화 정책 +- 공개 API(controller endpoint)에는 반드시 설명 주석 작성 +- 복잡한 비즈니스 로직에는 의도를 설명하는 주석 작성 +- README.md에 프로젝트 빌드/실행 방법 유지 diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md new file mode 100644 index 0000000..b18d0c9 --- /dev/null +++ b/.claude/rules/testing.md @@ -0,0 +1,62 @@ +# Java 테스트 규칙 + +## 테스트 프레임워크 +- JUnit 5 + AssertJ 조합 +- Mockito로 의존성 모킹 +- Spring Boot Test (`@SpringBootTest`) 는 통합 테스트에만 사용 + +## 테스트 구조 + +### 단위 테스트 (Unit Test) +- Service, Util, Domain 로직 테스트 +- Spring 컨텍스트 로딩 없이 (`@ExtendWith(MockitoExtension.class)`) +- 외부 의존성은 Mockito로 모킹 + +```java +@ExtendWith(MockitoExtension.class) +class UserServiceTest { + @InjectMocks + private UserService userService; + + @Mock + private UserRepository userRepository; + + @Test + @DisplayName("사용자 생성 시 정상 저장") + void createUser_withValidInput_savesUser() { + // given + // when + // then + } +} +``` + +### 통합 테스트 (Integration Test) +- Controller 테스트: `@WebMvcTest` + `MockMvc` +- Repository 테스트: `@DataJpaTest` +- 전체 플로우: `@SpringBootTest` (최소화) + +### 테스트 패턴 +- **Given-When-Then** 구조 사용 +- 각 섹션을 주석으로 구분 +- 하나의 테스트에 하나의 검증 원칙 (가능한 범위에서) + +## 테스트 네이밍 +- 메서드명: `{메서드}_{시나리오}_{기대결과}` 패턴 +- `@DisplayName`: 한국어로 테스트 의도 설명 + +## 테스트 커버리지 +- 새로 작성하는 Service 클래스: 핵심 비즈니스 로직 테스트 필수 +- 기존 코드 수정 시: 수정된 로직에 대한 테스트 추가 권장 +- Controller: 주요 API endpoint 통합 테스트 권장 + +## 테스트 데이터 +- 테스트 데이터는 테스트 메서드 내부 또는 `@BeforeEach`에서 생성 +- 공통 테스트 데이터는 TestFixture 클래스로 분리 +- 실제 DB 연결 필요 시 H2 인메모리 또는 Testcontainers 사용 + +## 금지 사항 +- `@SpringBootTest`를 단위 테스트에 사용 금지 +- 테스트 간 상태 공유 금지 +- `Thread.sleep()` 사용 금지 → `Awaitility` 사용 +- 실제 외부 API 호출 금지 → WireMock 또는 Mockito 사용 diff --git a/.claude/scripts/on-commit.sh b/.claude/scripts/on-commit.sh new file mode 100755 index 0000000..f473403 --- /dev/null +++ b/.claude/scripts/on-commit.sh @@ -0,0 +1,14 @@ +#!/bin/bash +INPUT=$(cat) +COMMAND=$(echo "$INPUT" | python3 -c "import sys,json;print(json.load(sys.stdin).get('tool_input',{}).get('command',''))" 2>/dev/null || echo "") +if echo "$COMMAND" | grep -qE 'git commit'; then + cat </dev/null || echo "") +if [ -z "$CWD" ]; then + CWD=$(pwd) +fi +PROJECT_HASH=$(echo "$CWD" | sed 's|/|-|g') +MEMORY_DIR="$HOME/.claude/projects/$PROJECT_HASH/memory" +CONTEXT="" +if [ -f "$MEMORY_DIR/MEMORY.md" ]; then + SUMMARY=$(head -100 "$MEMORY_DIR/MEMORY.md" | python3 -c "import sys;print(sys.stdin.read().replace('\\\\','\\\\\\\\').replace('\"','\\\\\"').replace('\n','\\\\n'))" 2>/dev/null) + CONTEXT="컨텍스트가 압축되었습니다.\\n\\n[세션 요약]\\n${SUMMARY}" +fi +if [ -f "$MEMORY_DIR/project-snapshot.md" ]; then + SNAP=$(head -50 "$MEMORY_DIR/project-snapshot.md" | python3 -c "import sys;print(sys.stdin.read().replace('\\\\','\\\\\\\\').replace('\"','\\\\\"').replace('\n','\\\\n'))" 2>/dev/null) + CONTEXT="${CONTEXT}\\n\\n[프로젝트 최신 상태]\\n${SNAP}" +fi +if [ -n "$CONTEXT" ]; then + CONTEXT="${CONTEXT}\\n\\n위 내용을 참고하여 작업을 이어가세요. 상세 내용은 memory/ 디렉토리의 각 파일을 참조하세요." + echo "{\"hookSpecificOutput\":{\"additionalContext\":\"${CONTEXT}\"}}" +else + echo "{\"hookSpecificOutput\":{\"additionalContext\":\"컨텍스트가 압축되었습니다. memory 파일이 없으므로 사용자에게 이전 작업 내용을 확인하세요.\"}}" +fi diff --git a/.claude/scripts/on-pre-compact.sh b/.claude/scripts/on-pre-compact.sh new file mode 100755 index 0000000..3f52f09 --- /dev/null +++ b/.claude/scripts/on-pre-compact.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# PreCompact hook: systemMessage만 지원 (hookSpecificOutput 사용 불가) +INPUT=$(cat) +cat <" +--- + +Gitea 이슈 #$ARGUMENTS 를 분석하고 수정 작업을 시작합니다. + +## 수행 단계 + +### 1. 이슈 조회 +```bash +curl -s "GITEA_URL/api/v1/repos/{owner}/{repo}/issues/$ARGUMENTS" \ + -H "Authorization: token ${GITEA_TOKEN}" +``` +- 이슈 제목, 본문, 라벨, 담당자 정보 확인 +- 이슈 내용을 사용자에게 요약하여 보여줌 + +### 2. 브랜치 생성 +이슈 라벨에 따라 브랜치 타입 결정: +- `bug` 라벨 → `bugfix/ISSUE-번호-설명` +- 그 외 → `feature/ISSUE-번호-설명` +- 긴급 → `hotfix/ISSUE-번호-설명` + +```bash +git checkout develop +git pull origin develop +git checkout -b {type}/ISSUE-{number}-{slug} +``` + +### 3. 이슈 분석 +이슈 내용을 바탕으로: +- 관련 파일 탐색 (Grep, Glob 활용) +- 영향 범위 파악 +- 수정 방향 제안 + +### 4. 수정 계획 제시 +사용자에게 수정 계획을 보여주고 승인을 받은 후 작업 진행: +- 수정할 파일 목록 +- 변경 내용 요약 +- 예상 영향 + +### 5. 작업 완료 후 +- 변경 사항 요약 +- `/create-mr` 실행 안내 + +## 필요 환경변수 +- `GITEA_TOKEN`: Gitea API 접근 토큰 diff --git a/.claude/skills/init-project/SKILL.md b/.claude/skills/init-project/SKILL.md new file mode 100644 index 0000000..3f5d388 --- /dev/null +++ b/.claude/skills/init-project/SKILL.md @@ -0,0 +1,246 @@ +--- +name: init-project +description: 팀 표준 워크플로우로 프로젝트를 초기화합니다 +allowed-tools: "Bash, Read, Write, Edit, Glob, Grep" +argument-hint: "[project-type: java-maven|java-gradle|react-ts|auto]" +--- + +팀 표준 워크플로우에 따라 프로젝트를 초기화합니다. +프로젝트 타입: $ARGUMENTS (기본: auto — 자동 감지) + +## 프로젝트 타입 자동 감지 + +$ARGUMENTS가 "auto"이거나 비어있으면 다음 순서로 감지: +1. `pom.xml` 존재 → **java-maven** +2. `build.gradle` 또는 `build.gradle.kts` 존재 → **java-gradle** +3. `package.json` + `tsconfig.json` 존재 → **react-ts** +4. 감지 실패 → 사용자에게 타입 선택 요청 + +## 수행 단계 + +### 1. 프로젝트 분석 +- 빌드 파일, 설정 파일, 디렉토리 구조 파악 +- 사용 중인 프레임워크, 라이브러리 감지 +- 기존 `.claude/` 디렉토리 존재 여부 확인 +- eslint, prettier, checkstyle, spotless 등 lint 도구 설치 여부 확인 + +### 2. CLAUDE.md 생성 +프로젝트 루트에 CLAUDE.md를 생성하고 다음 내용 포함: +- 프로젝트 개요 (이름, 타입, 주요 기술 스택) +- 빌드/실행 명령어 (감지된 빌드 도구 기반) +- 테스트 실행 명령어 +- lint 실행 명령어 (감지된 도구 기반) +- 프로젝트 디렉토리 구조 요약 +- 팀 컨벤션 참조 (`.claude/rules/` 안내) + +### Gitea 파일 다운로드 URL 패턴 +⚠️ Gitea raw 파일은 반드시 **web raw URL**을 사용해야 합니다 (`/api/v1/` 경로 사용 불가): +```bash +GITEA_URL="${GITEA_URL:-https://gitea.gc-si.dev}" +# common 파일: ${GITEA_URL}/gc/template-common/raw/branch/develop/<파일경로> +# 타입별 파일: ${GITEA_URL}/gc/template-<타입>/raw/branch/develop/<파일경로> +# 예시: +curl -sf "${GITEA_URL}/gc/template-common/raw/branch/develop/.claude/rules/team-policy.md" +curl -sf "${GITEA_URL}/gc/template-react-ts/raw/branch/develop/.editorconfig" +``` + +### 3. .claude/ 디렉토리 구성 +이미 팀 표준 파일이 존재하면 건너뜀. 없는 경우 위의 URL 패턴으로 Gitea에서 다운로드: +- `.claude/settings.json` — 프로젝트 타입별 표준 권한 설정 + hooks 섹션 (4단계 참조) +- `.claude/rules/` — 팀 규칙 파일 (team-policy, git-workflow, code-style, naming, testing) +- `.claude/skills/` — 팀 스킬 (create-mr, fix-issue, sync-team-workflow, init-project) + +### 4. Hook 스크립트 생성 +`.claude/scripts/` 디렉토리를 생성하고 다음 스크립트 파일 생성 (chmod +x): + +- `.claude/scripts/on-pre-compact.sh`: + +```bash +#!/bin/bash +# PreCompact hook: systemMessage만 지원 (hookSpecificOutput 사용 불가) +INPUT=$(cat) +cat </dev/null || echo "") +if [ -z "$CWD" ]; then + CWD=$(pwd) +fi +PROJECT_HASH=$(echo "$CWD" | sed 's|/|-|g') +MEMORY_DIR="$HOME/.claude/projects/$PROJECT_HASH/memory" +CONTEXT="" +if [ -f "$MEMORY_DIR/MEMORY.md" ]; then + SUMMARY=$(head -100 "$MEMORY_DIR/MEMORY.md" | python3 -c "import sys;print(sys.stdin.read().replace('\\\\','\\\\\\\\').replace('\"','\\\\\"').replace('\n','\\\\n'))" 2>/dev/null) + CONTEXT="컨텍스트가 압축되었습니다.\\n\\n[세션 요약]\\n${SUMMARY}" +fi +if [ -f "$MEMORY_DIR/project-snapshot.md" ]; then + SNAP=$(head -50 "$MEMORY_DIR/project-snapshot.md" | python3 -c "import sys;print(sys.stdin.read().replace('\\\\','\\\\\\\\').replace('\"','\\\\\"').replace('\n','\\\\n'))" 2>/dev/null) + CONTEXT="${CONTEXT}\\n\\n[프로젝트 최신 상태]\\n${SNAP}" +fi +if [ -n "$CONTEXT" ]; then + CONTEXT="${CONTEXT}\\n\\n위 내용을 참고하여 작업을 이어가세요. 상세 내용은 memory/ 디렉토리의 각 파일을 참조하세요." + echo "{\"hookSpecificOutput\":{\"additionalContext\":\"${CONTEXT}\"}}" +else + echo "{\"hookSpecificOutput\":{\"additionalContext\":\"컨텍스트가 압축되었습니다. memory 파일이 없으므로 사용자에게 이전 작업 내용을 확인하세요.\"}}" +fi +``` + +- `.claude/scripts/on-commit.sh`: + +```bash +#!/bin/bash +INPUT=$(cat) +COMMAND=$(echo "$INPUT" | python3 -c "import sys,json;print(json.load(sys.stdin).get('tool_input',{}).get('command',''))" 2>/dev/null || echo "") +if echo "$COMMAND" | grep -qE 'git commit'; then + cat </memory/`) 다음 파일들을 생성: + +- `memory/MEMORY.md` — 프로젝트 분석 결과 기반 핵심 요약 (200줄 이내) + - 현재 상태, 프로젝트 개요, 기술 스택, 주요 패키지 구조, 상세 참조 링크 +- `memory/project-snapshot.md` — 디렉토리 구조, 패키지 구성, 주요 의존성, API 엔드포인트 +- `memory/project-history.md` — "초기 팀 워크플로우 구성" 항목으로 시작 +- `memory/api-types.md` — 주요 인터페이스/DTO/Entity 타입 요약 +- `memory/decisions.md` — 빈 템플릿 (# 의사결정 기록) +- `memory/debugging.md` — 빈 템플릿 (# 디버깅 경험 & 패턴) + +### 10. Lint 도구 확인 +- TypeScript: eslint, prettier 설치 여부 확인. 미설치 시 사용자에게 설치 제안 +- Java: checkstyle, spotless 등 설정 확인 +- CLAUDE.md에 lint 실행 명령어가 이미 기록되었는지 확인 + +### 11. workflow-version.json 생성 +Gitea API로 최신 팀 워크플로우 버전을 조회: +```bash +curl -sf --max-time 5 "https://gitea.gc-si.dev/gc/template-common/raw/branch/develop/workflow-version.json" +``` +조회 성공 시 해당 `version` 값 사용, 실패 시 "1.0.0" 기본값 사용. + +`.claude/workflow-version.json` 파일 생성: +```json +{ + "applied_global_version": "<조회된 버전>", + "applied_date": "<현재날짜>", + "project_type": "<감지된타입>", + "gitea_url": "https://gitea.gc-si.dev" +} +``` + +### 12. 검증 및 요약 +- 생성/수정된 파일 목록 출력 +- `git config core.hooksPath` 확인 +- 빌드 명령 실행 가능 확인 +- Hook 스크립트 실행 권한 확인 +- 다음 단계 안내: + - 개발 시작, 첫 커밋 방법 + - 범용 스킬: `/api-registry`, `/changelog`, `/swagger-spec` diff --git a/.claude/skills/sync-team-workflow/SKILL.md b/.claude/skills/sync-team-workflow/SKILL.md new file mode 100644 index 0000000..930d04d --- /dev/null +++ b/.claude/skills/sync-team-workflow/SKILL.md @@ -0,0 +1,98 @@ +--- +name: sync-team-workflow +description: 팀 글로벌 워크플로우를 현재 프로젝트에 동기화합니다 +allowed-tools: "Bash, Read, Write, Edit, Glob, Grep" +--- + +팀 글로벌 워크플로우의 최신 버전을 현재 프로젝트에 적용합니다. + +## 수행 절차 + +### 1. 글로벌 버전 조회 +Gitea API로 template-common 리포의 workflow-version.json 조회: +```bash +GITEA_URL=$(python3 -c "import json; print(json.load(open('.claude/workflow-version.json')).get('gitea_url', 'https://gitea.gc-si.dev'))" 2>/dev/null || echo "https://gitea.gc-si.dev") + +curl -sf "${GITEA_URL}/gc/template-common/raw/branch/develop/workflow-version.json" +``` + +### 2. 버전 비교 +로컬 `.claude/workflow-version.json`의 `applied_global_version` 필드와 비교: +- 버전 일치 → "최신 버전입니다" 안내 후 종료 +- 버전 불일치 → 미적용 변경 항목 추출하여 표시 + +### 3. 프로젝트 타입 감지 +자동 감지 순서: +1. `.claude/workflow-version.json`의 `project_type` 필드 확인 +2. 없으면: `pom.xml` → java-maven, `build.gradle` → java-gradle, `package.json` → react-ts + +### Gitea 파일 다운로드 URL 패턴 +⚠️ Gitea raw 파일은 반드시 **web raw URL**을 사용해야 합니다 (`/api/v1/` 경로 사용 불가): +```bash +GITEA_URL="${GITEA_URL:-https://gitea.gc-si.dev}" +# common 파일: ${GITEA_URL}/gc/template-common/raw/branch/develop/<파일경로> +# 타입별 파일: ${GITEA_URL}/gc/template-<타입>/raw/branch/develop/<파일경로> +# 예시: +curl -sf "${GITEA_URL}/gc/template-common/raw/branch/develop/.claude/rules/team-policy.md" +curl -sf "${GITEA_URL}/gc/template-react-ts/raw/branch/develop/.editorconfig" +``` + +### 4. 파일 다운로드 및 적용 +위의 URL 패턴으로 해당 타입 + common 템플릿 파일 다운로드: + +#### 4-1. 규칙 파일 (덮어쓰기) +팀 규칙은 로컬 수정 불가 — 항상 글로벌 최신으로 교체: +``` +.claude/rules/team-policy.md +.claude/rules/git-workflow.md +.claude/rules/code-style.md (타입별) +.claude/rules/naming.md (타입별) +.claude/rules/testing.md (타입별) +``` + +#### 4-2. settings.json (부분 갱신) +- `deny` 목록: 글로벌 최신으로 교체 +- `allow` 목록: 기존 사용자 커스텀 유지 + 글로벌 기본값 병합 +- `hooks`: init-project SKILL.md의 hooks JSON 블록을 참조하여 교체 (없으면 추가) + - SessionStart(compact) → on-post-compact.sh + - PreCompact → on-pre-compact.sh + - PostToolUse(Bash) → on-commit.sh + +#### 4-3. 스킬 파일 (덮어쓰기) +``` +.claude/skills/create-mr/SKILL.md +.claude/skills/fix-issue/SKILL.md +.claude/skills/sync-team-workflow/SKILL.md +.claude/skills/init-project/SKILL.md +``` + +#### 4-4. Git Hooks (덮어쓰기 + 실행 권한) +```bash +chmod +x .githooks/* +``` + +#### 4-5. Hook 스크립트 갱신 +init-project SKILL.md의 코드 블록에서 최신 스크립트를 추출하여 덮어쓰기: +``` +.claude/scripts/on-pre-compact.sh +.claude/scripts/on-post-compact.sh +.claude/scripts/on-commit.sh +``` +실행 권한 부여: `chmod +x .claude/scripts/*.sh` + +### 5. 로컬 버전 업데이트 +`.claude/workflow-version.json` 갱신: +```json +{ + "applied_global_version": "새버전", + "applied_date": "오늘날짜", + "project_type": "감지된타입", + "gitea_url": "https://gitea.gc-si.dev" +} +``` + +### 6. 변경 보고 +- `git diff`로 변경 내역 확인 +- 업데이트된 파일 목록 출력 +- 변경 로그(글로벌 workflow-version.json의 changes) 표시 +- 필요한 추가 조치 안내 (빌드 확인, 의존성 업데이트 등) diff --git a/.claude/workflow-version.json b/.claude/workflow-version.json new file mode 100644 index 0000000..1e2b661 --- /dev/null +++ b/.claude/workflow-version.json @@ -0,0 +1,6 @@ +{ + "applied_global_version": "1.2.0", + "applied_date": "2026-02-14", + "project_type": "java-maven", + "gitea_url": "https://gitea.gc-si.dev" +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..6f831b5 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,33 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{java,kt}] +indent_style = space +indent_size = 4 + +[*.{js,jsx,ts,tsx,json,yml,yaml,css,scss,html}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[*.{sh,bash}] +indent_style = space +indent_size = 4 + +[Makefile] +indent_style = tab + +[*.{gradle,groovy}] +indent_style = space +indent_size = 4 + +[*.xml] +indent_style = space +indent_size = 4 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..f0f0fe4 --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,46 @@ +name: Build and Deploy API + +on: + push: + branches: + - main + +jobs: + build-and-deploy: + runs-on: ubuntu-latest + container: + image: maven:3.9-eclipse-temurin-17 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Configure Maven settings + run: | + mkdir -p ~/.m2 + cat > ~/.m2/settings.xml << 'SETTINGS' + + + + nexus + * + https://nexus.gc-si.dev/repository/maven-public/ + + + + + nexus + ${{ secrets.NEXUS_USERNAME }} + ${{ secrets.NEXUS_PASSWORD }} + + + + SETTINGS + + - name: Build + run: mvn clean package -DskipTests -B + + - name: Deploy to server + run: | + cp target/gc-guide-api-*.jar /deploy/api/app.jar + echo "Deployed at $(date '+%Y-%m-%d %H:%M:%S')" + ls -la /deploy/api/ diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..20260d9 --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,60 @@ +#!/bin/bash +#============================================================================== +# commit-msg hook +# Conventional Commits 형식 검증 (한/영 혼용 지원) +#============================================================================== + +COMMIT_MSG_FILE="$1" +COMMIT_MSG=$(cat "$COMMIT_MSG_FILE") + +# Merge 커밋은 검증 건너뜀 +if echo "$COMMIT_MSG" | head -1 | grep -qE "^Merge "; then + exit 0 +fi + +# Revert 커밋은 검증 건너뜀 +if echo "$COMMIT_MSG" | head -1 | grep -qE "^Revert "; then + exit 0 +fi + +# Conventional Commits 정규식 +# type(scope): subject +# - type: feat|fix|docs|style|refactor|test|chore|ci|perf (필수) +# - scope: 영문, 숫자, 한글, 점, 밑줄, 하이픈 허용 (선택) +# - subject: 1~72자, 한/영 혼용 허용 (필수) +PATTERN='^(feat|fix|docs|style|refactor|test|chore|ci|perf)(\([a-zA-Z0-9가-힣._-]+\))?: .{1,72}$' + +FIRST_LINE=$(head -1 "$COMMIT_MSG_FILE") + +if ! [[ "$FIRST_LINE" =~ $PATTERN ]]; then + echo "" + echo "╔══════════════════════════════════════════════════════════════╗" + echo "║ 커밋 메시지가 Conventional Commits 형식에 맞지 않습니다 ║" + echo "╚══════════════════════════════════════════════════════════════╝" + echo "" + echo " 올바른 형식: type(scope): subject" + echo "" + echo " type (필수):" + echo " feat — 새로운 기능" + echo " fix — 버그 수정" + echo " docs — 문서 변경" + echo " style — 코드 포맷팅" + echo " refactor — 리팩토링" + echo " test — 테스트" + echo " chore — 빌드/설정 변경" + echo " ci — CI/CD 변경" + echo " perf — 성능 개선" + echo "" + echo " scope (선택): 한/영 모두 가능" + echo " subject (필수): 1~72자, 한/영 모두 가능" + echo "" + echo " 예시:" + echo " feat(auth): JWT 기반 로그인 구현" + echo " fix(배치): 야간 배치 타임아웃 수정" + echo " docs: README 업데이트" + echo " chore: Gradle 의존성 업데이트" + echo "" + echo " 현재 메시지: $FIRST_LINE" + echo "" + exit 1 +fi diff --git a/.githooks/post-checkout b/.githooks/post-checkout new file mode 100755 index 0000000..bae360f --- /dev/null +++ b/.githooks/post-checkout @@ -0,0 +1,25 @@ +#!/bin/bash +#============================================================================== +# post-checkout hook +# 브랜치 체크아웃 시 core.hooksPath 자동 설정 +# clone/checkout 후 .githooks 디렉토리가 있으면 자동으로 hooksPath 설정 +#============================================================================== + +# post-checkout 파라미터: prev_HEAD, new_HEAD, branch_flag +# branch_flag=1: 브랜치 체크아웃, 0: 파일 체크아웃 +BRANCH_FLAG="$3" + +# 파일 체크아웃은 건너뜀 +if [ "$BRANCH_FLAG" = "0" ]; then + exit 0 +fi + +# .githooks 디렉토리 존재 확인 +REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) +if [ -d "${REPO_ROOT}/.githooks" ]; then + CURRENT_HOOKS_PATH=$(git config core.hooksPath 2>/dev/null || echo "") + if [ "$CURRENT_HOOKS_PATH" != ".githooks" ]; then + git config core.hooksPath .githooks + chmod +x "${REPO_ROOT}/.githooks/"* 2>/dev/null + fi +fi diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..258f955 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +# Claude Code 워크플로우 (글로벌 제외 해제) +!.claude/ +.claude/settings.local.json +.claude/CLAUDE.local.md + +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/settings.xml b/.mvn/settings.xml new file mode 100644 index 0000000..ba8b42b --- /dev/null +++ b/.mvn/settings.xml @@ -0,0 +1,60 @@ + + + + + + + nexus + admin + Gcsc!8932 + + + + + + nexus + GCSC Nexus Repository + https://nexus.gc-si.dev/repository/maven-public/ + * + + + + + + nexus + + + central + http://central + true + true + + + + + central + http://central + true + true + + + + + + + nexus + + + diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..8dea6c2 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip diff --git a/.sdkmanrc b/.sdkmanrc new file mode 100644 index 0000000..a4417cd --- /dev/null +++ b/.sdkmanrc @@ -0,0 +1 @@ +java=17.0.18-amzn diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..f9f2187 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,308 @@ +# gc-guide-api — 가이드 사이트 백엔드 API + +## 프로젝트 개요 +gc-guide 프론트엔드의 백엔드 API. Google OAuth2 인증, 사용자 관리(RBAC), 활동 기록, 이슈 트래커 제공. + +## 기술 스택 +- Spring Boot 3.5.2 + JDK 17 +- Spring Security (JWT 기반 Stateless 인증) +- Spring Data JPA + PostgreSQL (운영) / H2 (로컬) +- Google API Client 2.7.2 (ID Token 검증) +- JJWT 0.12.6 (JWT 생성/검증) +- Lombok + +## 빌드 & 실행 + +```bash +source ~/.sdkman/bin/sdkman-init.sh && sdk use java 17.0.18-amzn # JDK 전환 +./mvnw -s .mvn/settings.xml clean compile # 컴파일 +./mvnw -s .mvn/settings.xml spring-boot:run # 로컬 실행 (H2, port 8080) +./mvnw -s .mvn/settings.xml package -DskipTests # JAR 패키징 +``` + +## 프로필 +- `local` (기본): H2 인메모리 DB (`create-drop`), 디버그 로깅, H2 콘솔 `/h2-console` +- `prod`: PostgreSQL (gc_guide DB), `validate` 모드 + +## 배포 +- Docker (eclipse-temurin:17-jre + JAR) +- guide.gc-si.dev/api/* → Nginx 프록시 → 컨테이너 +- CI/CD: Gitea Actions (main 머지 시 자동 빌드/배포) +- Gitea: https://gitea.gc-si.dev/gc/gc-guide-api + +## 의존성 레포지토리 +- Maven: Nexus 프록시 `.mvn/settings.xml` (admin/Gcsc!8932 인증 포함) + +## 관련 프로젝트 +- gc-guide: 프론트엔드 (React + TypeScript + Vite) + +--- + +## 현재 구현 상태 + +### 완료 (scaffold) +- Spring Boot 프로젝트 초기화 (pom.xml + Maven Wrapper) +- application.yml + local/prod 프로필 분리 +- SecurityConfig.java — CSRF 비활성화, Stateless 세션, 공개 엔드포인트 설정 +- HealthController.java — `GET /api/health` → `{status: "UP"}` +- Nexus 프록시 인증 설정 (.mvn/settings.xml) +- 빌드 검증: `mvn clean compile` 성공 + +### 미구현 (별도 세션에서 작업) +아래 순서대로 구현 필요: + +#### 1단계: DB 엔티티 + JPA +패키지: `com.gcsc.guide.entity` + +```java +@Entity User — id, email, name, avatarUrl, status(PENDING/ACTIVE/REJECTED/DISABLED), isAdmin, createdAt, updatedAt, lastLoginAt +@Entity Role — id, name, description, createdAt +@Entity UserRole — userId, roleId (다대다, @IdClass 또는 @JoinTable) +@Entity RoleUrlPattern — id, roleId, urlPattern, createdAt +@Entity LoginHistory — id, userId, loginAt, ipAddress, userAgent +@Entity PageView — id, userId, pagePath, viewedAt +@Entity Issue — id, title, body, status, priority, authorId, assigneeId, createdAt, updatedAt +@Entity IssueComment — id, issueId, authorId, body, createdAt +``` + +패키지: `com.gcsc.guide.repository` — 각 엔티티별 JpaRepository + +#### 2단계: 인증 API +패키지: `com.gcsc.guide.auth` + +- `JwtTokenProvider.java` — JWT 생성/검증 (JJWT 0.12.6) + - secret: `app.jwt.secret` (256bit 이상) + - expiration: `app.jwt.expiration-ms` (기본 24시간) +- `JwtAuthenticationFilter.java` — OncePerRequestFilter, Authorization Bearer 토큰 파싱 +- `GoogleTokenVerifier.java` — Google API Client로 ID Token 검증 + - Client ID: `app.google.client-id` + - 이메일 도메인 검증: `app.allowed-email-domain` (gcsc.co.kr) +- `AuthController.java`: + - `POST /api/auth/google` — { idToken } → GoogleTokenVerifier → User 조회/생성 → JWT 발급 + - 신규 사용자: status=PENDING, DB 저장 + - htlee@gcsc.co.kr: 자동 ACTIVE + isAdmin=true + - 응답: { token, user } + - `GET /api/auth/me` — JWT에서 userId 추출 → User + roles 반환 + - `POST /api/auth/logout` — (Stateless이므로 프론트에서 토큰 삭제, 서버는 204) + +SecurityConfig 수정: +- JwtAuthenticationFilter를 UsernamePasswordAuthenticationFilter 앞에 추가 +- 공개 엔드포인트: `/api/auth/**`, `/api/health`, `/actuator/health`, `/h2-console/**` + +#### 3단계: 관리자 API +패키지: `com.gcsc.guide.controller` + +- `AdminUserController.java`: + - `GET /api/admin/users` — 전체 목록 (status 필터 쿼리파라미터) + - `PUT /api/admin/users/{id}/approve` — PENDING→ACTIVE + - `PUT /api/admin/users/{id}/reject` — PENDING→REJECTED + - `PUT /api/admin/users/{id}/disable` — ACTIVE→DISABLED + - `PUT /api/admin/users/{id}/roles` — { roleIds: [1,2] } → user_roles 업데이트 + - `POST /api/admin/users/{id}/admin` — isAdmin=true + - `DELETE /api/admin/users/{id}/admin` — isAdmin=false + +- `AdminRoleController.java`: + - `GET /api/admin/roles` — 전체 롤 목록 + - `POST /api/admin/roles` — { name, description } → Role 생성 + - `PUT /api/admin/roles/{id}` — 수정 + - `DELETE /api/admin/roles/{id}` — 삭제 + - `GET /api/admin/roles/{id}/permissions` — URL 패턴 목록 + - `POST /api/admin/roles/{id}/permissions` — { urlPattern } 추가 + - `DELETE /api/admin/permissions/{id}` — 삭제 + +- `AdminStatsController.java`: + - `GET /api/admin/stats` — { totalUsers, activeUsers, pendingUsers, todayLogins, ... } + +관리자 권한 체크: `@PreAuthorize("@authChecker.isAdmin()")` 또는 SecurityConfig에서 `/api/admin/**` 패턴에 커스텀 필터 적용 + +#### 4단계: 활동 기록 API +- `ActivityController.java`: + - `POST /api/activity/track` — { pagePath } → PageView 저장 + - `GET /api/activity/login-history` — 현재 사용자의 로그인 이력 + +#### 5단계: 이슈 관리 API +- `IssueController.java`: + - `GET /api/issues` — 이슈 목록 (status 필터, 페이징) + - `POST /api/issues` — { title, body, priority } → Issue 생성 + - `GET /api/issues/{id}` — 이슈 상세 (코멘트 포함) + - `PUT /api/issues/{id}` — 수정 + - `POST /api/issues/{id}/comments` — { body } → 코멘트 추가 + +#### 6단계: 롤 기반 URL 접근 제어 (선택) +- `DynamicAuthorizationManager.java` — 커스텀 AuthorizationManager + - 매 요청마다 DB에서 사용자 롤 → role_url_patterns 조회 → ant-style 매칭 + - SecurityConfig에서 `.anyRequest().access(dynamicAuthorizationManager)` 적용 + - 캐싱: 사용자별 URL 패턴을 JWT 클레임에 포함하거나 Redis/로컬캐시 활용 + +#### 7단계: 초기 데이터 시딩 +`data.sql` 또는 ApplicationRunner로: + +```sql +INSERT INTO roles (name, description) VALUES + ('ADMIN', '전체 접근 권한 (관리자 페이지 포함)'), + ('DEVELOPER', '전체 개발 가이드 접근'), + ('FRONT_DEV', '프론트엔드 개발 가이드만'); + +INSERT INTO role_url_patterns (role_id, url_pattern) VALUES + (1, '/**'), + (2, '/dev/**'), + (3, '/dev/front/**'); +``` + +--- + +## DB 스키마 + +### 로컬 (H2, create-drop) +JPA가 엔티티 기반으로 자동 생성. `data.sql`로 초기 시드. + +### 운영 (PostgreSQL) +| 항목 | 값 | +|------|-----| +| Host | 211.208.115.83 (Docker: 172.17.0.1) | +| Port | 5432 | +| Database | gc_guide | +| Username | gcguide | +| Password | GcGuide!2026 | + +**DB/사용자 아직 미생성** — 서버에서 아래 SQL 실행 필요: + +```sql +CREATE USER gcguide WITH PASSWORD 'GcGuide!2026'; +CREATE DATABASE gc_guide OWNER gcguide ENCODING 'UTF8'; +GRANT ALL PRIVILEGES ON DATABASE gc_guide TO gcguide; +``` + +스키마 DDL (JPA가 로컬에서 자동 생성하되, 운영은 validate 모드이므로 수동 생성 필요): + +```sql +CREATE TABLE users ( + id BIGSERIAL PRIMARY KEY, + email VARCHAR(255) NOT NULL UNIQUE, + name VARCHAR(100) NOT NULL, + avatar_url VARCHAR(500), + status VARCHAR(20) DEFAULT 'PENDING', + is_admin BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT NOW(), + updated_at TIMESTAMP DEFAULT NOW(), + last_login_at TIMESTAMP +); + +CREATE TABLE roles ( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(50) NOT NULL UNIQUE, + description VARCHAR(255), + created_at TIMESTAMP DEFAULT NOW() +); + +CREATE TABLE user_roles ( + user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + role_id BIGINT REFERENCES roles(id) ON DELETE CASCADE, + PRIMARY KEY (user_id, role_id) +); + +CREATE TABLE role_url_patterns ( + id BIGSERIAL PRIMARY KEY, + role_id BIGINT REFERENCES roles(id) ON DELETE CASCADE, + url_pattern VARCHAR(255) NOT NULL, + created_at TIMESTAMP DEFAULT NOW() +); + +CREATE TABLE login_history ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT REFERENCES users(id), + login_at TIMESTAMP DEFAULT NOW(), + ip_address VARCHAR(45), + user_agent VARCHAR(500) +); + +CREATE TABLE page_views ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT REFERENCES users(id), + page_path VARCHAR(255) NOT NULL, + viewed_at TIMESTAMP DEFAULT NOW() +); + +CREATE TABLE issues ( + id BIGSERIAL PRIMARY KEY, + title VARCHAR(255) NOT NULL, + body TEXT, + status VARCHAR(20) DEFAULT 'OPEN', + priority VARCHAR(20) DEFAULT 'NORMAL', + author_id BIGINT REFERENCES users(id), + assignee_id BIGINT REFERENCES users(id), + created_at TIMESTAMP DEFAULT NOW(), + updated_at TIMESTAMP DEFAULT NOW() +); + +CREATE TABLE issue_comments ( + id BIGSERIAL PRIMARY KEY, + issue_id BIGINT REFERENCES issues(id) ON DELETE CASCADE, + author_id BIGINT REFERENCES users(id), + body TEXT NOT NULL, + created_at TIMESTAMP DEFAULT NOW() +); + +CREATE INDEX idx_login_history_user ON login_history(user_id); +CREATE INDEX idx_page_views_user ON page_views(user_id); +CREATE INDEX idx_issues_status ON issues(status); +CREATE INDEX idx_issue_comments_issue ON issue_comments(issue_id); +``` + +--- + +## 패키지 구조 (목표) + +``` +com.gcsc.guide/ +├── GcGuideApiApplication.java ✅ +├── config/ +│ └── SecurityConfig.java ✅ (JWT 필터 추가 필요) +├── auth/ +│ ├── JwtTokenProvider.java ⬜ +│ ├── JwtAuthenticationFilter.java ⬜ +│ ├── GoogleTokenVerifier.java ⬜ +│ └── AuthController.java ⬜ +├── entity/ +│ ├── User.java ⬜ +│ ├── Role.java ⬜ +│ ├── RoleUrlPattern.java ⬜ +│ ├── LoginHistory.java ⬜ +│ ├── PageView.java ⬜ +│ ├── Issue.java ⬜ +│ └── IssueComment.java ⬜ +├── repository/ ⬜ (각 엔티티별 JpaRepository) +├── service/ +│ ├── UserService.java ⬜ +│ ├── RoleService.java ⬜ +│ ├── ActivityService.java ⬜ +│ └── IssueService.java ⬜ +├── controller/ +│ ├── HealthController.java ✅ +│ ├── AdminUserController.java ⬜ +│ ├── AdminRoleController.java ⬜ +│ ├── AdminStatsController.java ⬜ +│ ├── ActivityController.java ⬜ +│ └── IssueController.java ⬜ +├── dto/ ⬜ (요청/응답 DTO) +└── exception/ ⬜ (GlobalExceptionHandler) +``` + +## application.yml 설정 참조 + +```yaml +app: + jwt: + secret: ${JWT_SECRET:gc-guide-dev-jwt-secret-key-must-be-at-least-256-bits-long} + expiration-ms: ${JWT_EXPIRATION:86400000} + google: + client-id: ${GOOGLE_CLIENT_ID:295080817934-1uqaqrkup9jnslajkl1ngpee7gm249fv.apps.googleusercontent.com} + allowed-email-domain: gcsc.co.kr +``` + +## 구현 시 주의사항 +- DTO와 Entity 분리 필수 (API 응답에 Entity 직접 노출 금지) +- 비즈니스 로직은 Service 계층에 집중 +- @Transactional 범위 최소화 +- H2 로컬 모드에서 전체 기능 테스트 가능하도록 프로필 분리 유지 +- Google OAuth2 Client ID는 gc-guide (프론트엔드)와 동일한 것 사용 diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3051501 --- /dev/null +++ b/pom.xml @@ -0,0 +1,138 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.2 + + + com.gcsc.guide + gc-guide-api + 0.0.1-SNAPSHOT + gc-guide-api + GC SI Developer Guide API + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + + org.postgresql + postgresql + runtime + + + org.projectlombok + lombok + true + + + + com.google.api-client + google-api-client + 2.7.2 + + + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + runtime + + + + + com.h2database + h2 + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/main/java/com/gcsc/guide/GcGuideApiApplication.java b/src/main/java/com/gcsc/guide/GcGuideApiApplication.java new file mode 100644 index 0000000..694ed28 --- /dev/null +++ b/src/main/java/com/gcsc/guide/GcGuideApiApplication.java @@ -0,0 +1,13 @@ +package com.gcsc.guide; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class GcGuideApiApplication { + + public static void main(String[] args) { + SpringApplication.run(GcGuideApiApplication.class, args); + } + +} diff --git a/src/main/java/com/gcsc/guide/auth/AuthController.java b/src/main/java/com/gcsc/guide/auth/AuthController.java new file mode 100644 index 0000000..174467d --- /dev/null +++ b/src/main/java/com/gcsc/guide/auth/AuthController.java @@ -0,0 +1,96 @@ +package com.gcsc.guide.auth; + +import com.gcsc.guide.dto.AuthResponse; +import com.gcsc.guide.dto.GoogleLoginRequest; +import com.gcsc.guide.dto.UserResponse; +import com.gcsc.guide.entity.User; +import com.gcsc.guide.repository.UserRepository; +import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.server.ResponseStatusException; + +@Slf4j +@RestController +@RequestMapping("/api/auth") +@RequiredArgsConstructor +public class AuthController { + + private static final String AUTO_ADMIN_EMAIL = "htlee@gcsc.co.kr"; + + private final GoogleTokenVerifier googleTokenVerifier; + private final JwtTokenProvider jwtTokenProvider; + private final UserRepository userRepository; + + /** + * Google ID Token으로 로그인/회원가입 처리 후 JWT 발급 + */ + @PostMapping("/google") + public ResponseEntity googleLogin(@Valid @RequestBody GoogleLoginRequest request) { + GoogleIdToken.Payload payload = googleTokenVerifier.verify(request.idToken()); + if (payload == null) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "유효하지 않은 Google 토큰입니다"); + } + + String email = payload.getEmail(); + String name = (String) payload.get("name"); + String avatarUrl = (String) payload.get("picture"); + + userRepository.findByEmail(email) + .ifPresentOrElse( + existingUser -> { + existingUser.updateProfile(name, avatarUrl); + existingUser.updateLastLogin(); + userRepository.save(existingUser); + }, + () -> createNewUser(email, name, avatarUrl) + ); + + User userWithRoles = userRepository.findByEmailWithRoles(email) + .orElseThrow(); + + String token = jwtTokenProvider.generateToken( + userWithRoles.getId(), userWithRoles.getEmail(), userWithRoles.isAdmin()); + + return ResponseEntity.ok(new AuthResponse(token, UserResponse.from(userWithRoles))); + } + + /** + * 현재 인증된 사용자 정보 조회 + */ + @GetMapping("/me") + public ResponseEntity getCurrentUser(Authentication authentication) { + Long userId = (Long) authentication.getPrincipal(); + + User user = userRepository.findByIdWithRoles(userId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "사용자를 찾을 수 없습니다")); + + return ResponseEntity.ok(UserResponse.from(user)); + } + + /** + * 로그아웃 (Stateless JWT이므로 서버 측 처리 없음, 프론트에서 토큰 삭제) + */ + @PostMapping("/logout") + public ResponseEntity logout() { + return ResponseEntity.noContent().build(); + } + + private User createNewUser(String email, String name, String avatarUrl) { + User newUser = new User(email, name, avatarUrl); + + if (AUTO_ADMIN_EMAIL.equals(email)) { + newUser.activate(); + newUser.grantAdmin(); + log.info("관리자 자동 승인: {}", email); + } + + newUser.updateLastLogin(); + return userRepository.save(newUser); + } +} diff --git a/src/main/java/com/gcsc/guide/auth/GoogleTokenVerifier.java b/src/main/java/com/gcsc/guide/auth/GoogleTokenVerifier.java new file mode 100644 index 0000000..60dbd44 --- /dev/null +++ b/src/main/java/com/gcsc/guide/auth/GoogleTokenVerifier.java @@ -0,0 +1,57 @@ +package com.gcsc.guide.auth; + +import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; +import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.Collections; + +@Slf4j +@Component +public class GoogleTokenVerifier { + + private final GoogleIdTokenVerifier verifier; + private final String allowedEmailDomain; + + public GoogleTokenVerifier( + @Value("${app.google.client-id}") String clientId, + @Value("${app.allowed-email-domain}") String allowedEmailDomain + ) { + this.verifier = new GoogleIdTokenVerifier.Builder( + new NetHttpTransport(), GsonFactory.getDefaultInstance()) + .setAudience(Collections.singletonList(clientId)) + .build(); + this.allowedEmailDomain = allowedEmailDomain; + } + + /** + * Google ID Token을 검증하고 페이로드를 반환한다. + * 검증 실패 또는 허용되지 않은 이메일 도메인이면 null을 반환한다. + */ + public GoogleIdToken.Payload verify(String idTokenString) { + try { + GoogleIdToken idToken = verifier.verify(idTokenString); + if (idToken == null) { + log.warn("Google ID Token 검증 실패: 유효하지 않은 토큰"); + return null; + } + + GoogleIdToken.Payload payload = idToken.getPayload(); + String email = payload.getEmail(); + + if (email == null || !email.endsWith("@" + allowedEmailDomain)) { + log.warn("허용되지 않은 이메일 도메인: {}", email); + return null; + } + + return payload; + } catch (Exception e) { + log.error("Google ID Token 검증 중 오류: {}", e.getMessage()); + return null; + } + } +} diff --git a/src/main/java/com/gcsc/guide/auth/JwtAuthenticationFilter.java b/src/main/java/com/gcsc/guide/auth/JwtAuthenticationFilter.java new file mode 100644 index 0000000..b3898fb --- /dev/null +++ b/src/main/java/com/gcsc/guide/auth/JwtAuthenticationFilter.java @@ -0,0 +1,57 @@ +package com.gcsc.guide.auth; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.List; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private static final String AUTHORIZATION_HEADER = "Authorization"; + private static final String BEARER_PREFIX = "Bearer "; + + private final JwtTokenProvider jwtTokenProvider; + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + + String token = extractToken(request); + + if (token != null && jwtTokenProvider.validateToken(token)) { + Long userId = jwtTokenProvider.getUserIdFromToken(token); + + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(userId, token, List.of(new SimpleGrantedAuthority("ROLE_USER"))); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + filterChain.doFilter(request, response); + } + + private String extractToken(HttpServletRequest request) { + String bearerToken = request.getHeader(AUTHORIZATION_HEADER); + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER_PREFIX)) { + return bearerToken.substring(BEARER_PREFIX.length()); + } + return null; + } +} diff --git a/src/main/java/com/gcsc/guide/auth/JwtTokenProvider.java b/src/main/java/com/gcsc/guide/auth/JwtTokenProvider.java new file mode 100644 index 0000000..58a0127 --- /dev/null +++ b/src/main/java/com/gcsc/guide/auth/JwtTokenProvider.java @@ -0,0 +1,66 @@ +package com.gcsc.guide.auth; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.util.Date; + +@Slf4j +@Component +public class JwtTokenProvider { + + private final SecretKey secretKey; + private final long expirationMs; + + public JwtTokenProvider( + @Value("${app.jwt.secret}") String secret, + @Value("${app.jwt.expiration-ms}") long expirationMs + ) { + this.secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); + this.expirationMs = expirationMs; + } + + public String generateToken(Long userId, String email, boolean isAdmin) { + Date now = new Date(); + Date expiry = new Date(now.getTime() + expirationMs); + + return Jwts.builder() + .subject(userId.toString()) + .claim("email", email) + .claim("isAdmin", isAdmin) + .issuedAt(now) + .expiration(expiry) + .signWith(secretKey) + .compact(); + } + + public Long getUserIdFromToken(String token) { + Claims claims = parseToken(token); + return Long.parseLong(claims.getSubject()); + } + + public boolean validateToken(String token) { + try { + parseToken(token); + return true; + } catch (JwtException | IllegalArgumentException e) { + log.debug("JWT 토큰 검증 실패: {}", e.getMessage()); + return false; + } + } + + private Claims parseToken(String token) { + return Jwts.parser() + .verifyWith(secretKey) + .build() + .parseSignedClaims(token) + .getPayload(); + } +} diff --git a/src/main/java/com/gcsc/guide/config/SecurityConfig.java b/src/main/java/com/gcsc/guide/config/SecurityConfig.java new file mode 100644 index 0000000..b1386a6 --- /dev/null +++ b/src/main/java/com/gcsc/guide/config/SecurityConfig.java @@ -0,0 +1,65 @@ +package com.gcsc.guide.config; + +import com.gcsc.guide.auth.JwtAuthenticationFilter; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.List; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + + private final JwtAuthenticationFilter jwtAuthenticationFilter; + + @Value("${app.cors.allowed-origins:http://localhost:5173,https://guide.gc-si.dev}") + private List allowedOrigins; + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .csrf(csrf -> csrf.disable()) + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .requestMatchers( + "/api/auth/**", + "/api/health", + "/actuator/health", + "/h2-console/**" + ).permitAll() + .requestMatchers("/api/admin/**").authenticated() + .anyRequest().authenticated() + ) + .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration config = new CorsConfiguration(); + config.setAllowedOrigins(allowedOrigins); + config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); + config.setAllowedHeaders(List.of("*")); + config.setAllowCredentials(true); + config.setMaxAge(3600L); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/api/**", config); + return source; + } +} diff --git a/src/main/java/com/gcsc/guide/controller/HealthController.java b/src/main/java/com/gcsc/guide/controller/HealthController.java new file mode 100644 index 0000000..13443ca --- /dev/null +++ b/src/main/java/com/gcsc/guide/controller/HealthController.java @@ -0,0 +1,18 @@ +package com.gcsc.guide.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +@RestController +public class HealthController { + + @GetMapping("/api/health") + public Map health() { + return Map.of( + "status", "UP", + "service", "gc-guide-api" + ); + } +} diff --git a/src/main/java/com/gcsc/guide/dto/AuthResponse.java b/src/main/java/com/gcsc/guide/dto/AuthResponse.java new file mode 100644 index 0000000..ecde172 --- /dev/null +++ b/src/main/java/com/gcsc/guide/dto/AuthResponse.java @@ -0,0 +1,7 @@ +package com.gcsc.guide.dto; + +public record AuthResponse( + String token, + UserResponse user +) { +} diff --git a/src/main/java/com/gcsc/guide/dto/GoogleLoginRequest.java b/src/main/java/com/gcsc/guide/dto/GoogleLoginRequest.java new file mode 100644 index 0000000..af0a48e --- /dev/null +++ b/src/main/java/com/gcsc/guide/dto/GoogleLoginRequest.java @@ -0,0 +1,8 @@ +package com.gcsc.guide.dto; + +import jakarta.validation.constraints.NotBlank; + +public record GoogleLoginRequest( + @NotBlank String idToken +) { +} diff --git a/src/main/java/com/gcsc/guide/dto/RoleResponse.java b/src/main/java/com/gcsc/guide/dto/RoleResponse.java new file mode 100644 index 0000000..ef8ede5 --- /dev/null +++ b/src/main/java/com/gcsc/guide/dto/RoleResponse.java @@ -0,0 +1,27 @@ +package com.gcsc.guide.dto; + +import com.gcsc.guide.entity.Role; +import com.gcsc.guide.entity.RoleUrlPattern; + +import java.util.List; + +public record RoleResponse( + Long id, + String name, + String description, + List urlPatterns +) { + + public static RoleResponse from(Role role) { + List patterns = role.getUrlPatterns().stream() + .map(RoleUrlPattern::getUrlPattern) + .toList(); + + return new RoleResponse( + role.getId(), + role.getName(), + role.getDescription(), + patterns + ); + } +} diff --git a/src/main/java/com/gcsc/guide/dto/UserResponse.java b/src/main/java/com/gcsc/guide/dto/UserResponse.java new file mode 100644 index 0000000..ec386f2 --- /dev/null +++ b/src/main/java/com/gcsc/guide/dto/UserResponse.java @@ -0,0 +1,37 @@ +package com.gcsc.guide.dto; + +import com.gcsc.guide.entity.User; + +import java.time.LocalDateTime; +import java.util.List; + +public record UserResponse( + Long id, + String email, + String name, + String avatarUrl, + String status, + boolean isAdmin, + List roles, + LocalDateTime createdAt, + LocalDateTime lastLoginAt +) { + + public static UserResponse from(User user) { + List roles = user.getRoles().stream() + .map(RoleResponse::from) + .toList(); + + return new UserResponse( + user.getId(), + user.getEmail(), + user.getName(), + user.getAvatarUrl(), + user.getStatus().name(), + user.isAdmin(), + roles, + user.getCreatedAt(), + user.getLastLoginAt() + ); + } +} diff --git a/src/main/java/com/gcsc/guide/entity/Role.java b/src/main/java/com/gcsc/guide/entity/Role.java new file mode 100644 index 0000000..37f92d9 --- /dev/null +++ b/src/main/java/com/gcsc/guide/entity/Role.java @@ -0,0 +1,47 @@ +package com.gcsc.guide.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "roles") +@Getter +@NoArgsConstructor +public class Role { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, unique = true, length = 50) + private String name; + + @Column(length = 255) + private String description; + + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + @OneToMany(mappedBy = "role", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) + private List urlPatterns = new ArrayList<>(); + + public Role(String name, String description) { + this.name = name; + this.description = description; + } + + public void update(String name, String description) { + this.name = name; + this.description = description; + } + + @PrePersist + protected void onCreate() { + this.createdAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/gcsc/guide/entity/RoleUrlPattern.java b/src/main/java/com/gcsc/guide/entity/RoleUrlPattern.java new file mode 100644 index 0000000..2d02d80 --- /dev/null +++ b/src/main/java/com/gcsc/guide/entity/RoleUrlPattern.java @@ -0,0 +1,38 @@ +package com.gcsc.guide.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Entity +@Table(name = "role_url_patterns") +@Getter +@NoArgsConstructor +public class RoleUrlPattern { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "role_id", nullable = false) + private Role role; + + @Column(name = "url_pattern", nullable = false, length = 255) + private String urlPattern; + + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + public RoleUrlPattern(Role role, String urlPattern) { + this.role = role; + this.urlPattern = urlPattern; + } + + @PrePersist + protected void onCreate() { + this.createdAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/gcsc/guide/entity/User.java b/src/main/java/com/gcsc/guide/entity/User.java new file mode 100644 index 0000000..57ff158 --- /dev/null +++ b/src/main/java/com/gcsc/guide/entity/User.java @@ -0,0 +1,103 @@ +package com.gcsc.guide.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table(name = "users") +@Getter +@NoArgsConstructor +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, unique = true) + private String email; + + @Column(nullable = false, length = 100) + private String name; + + @Column(name = "avatar_url", length = 500) + private String avatarUrl; + + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 20) + private UserStatus status = UserStatus.PENDING; + + @Column(name = "is_admin", nullable = false) + private boolean isAdmin = false; + + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; + + @Column(name = "last_login_at") + private LocalDateTime lastLoginAt; + + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable( + name = "user_roles", + joinColumns = @JoinColumn(name = "user_id"), + inverseJoinColumns = @JoinColumn(name = "role_id") + ) + private Set roles = new HashSet<>(); + + public User(String email, String name, String avatarUrl) { + this.email = email; + this.name = name; + this.avatarUrl = avatarUrl; + } + + public void activate() { + this.status = UserStatus.ACTIVE; + } + + public void reject() { + this.status = UserStatus.REJECTED; + } + + public void disable() { + this.status = UserStatus.DISABLED; + } + + public void grantAdmin() { + this.isAdmin = true; + } + + public void revokeAdmin() { + this.isAdmin = false; + } + + public void updateLastLogin() { + this.lastLoginAt = LocalDateTime.now(); + } + + public void updateProfile(String name, String avatarUrl) { + this.name = name; + this.avatarUrl = avatarUrl; + } + + public void updateRoles(Set roles) { + this.roles = roles; + } + + @PrePersist + protected void onCreate() { + this.createdAt = LocalDateTime.now(); + this.updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + this.updatedAt = LocalDateTime.now(); + } +} diff --git a/src/main/java/com/gcsc/guide/entity/UserStatus.java b/src/main/java/com/gcsc/guide/entity/UserStatus.java new file mode 100644 index 0000000..f2f1946 --- /dev/null +++ b/src/main/java/com/gcsc/guide/entity/UserStatus.java @@ -0,0 +1,8 @@ +package com.gcsc.guide.entity; + +public enum UserStatus { + PENDING, + ACTIVE, + REJECTED, + DISABLED +} diff --git a/src/main/java/com/gcsc/guide/repository/RoleRepository.java b/src/main/java/com/gcsc/guide/repository/RoleRepository.java new file mode 100644 index 0000000..c8e5409 --- /dev/null +++ b/src/main/java/com/gcsc/guide/repository/RoleRepository.java @@ -0,0 +1,19 @@ +package com.gcsc.guide.repository; + +import com.gcsc.guide.entity.Role; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; +import java.util.Optional; + +public interface RoleRepository extends JpaRepository { + + Optional findByName(String name); + + @Query("SELECT DISTINCT r FROM Role r LEFT JOIN FETCH r.urlPatterns") + List findAllWithUrlPatterns(); + + @Query("SELECT r FROM Role r LEFT JOIN FETCH r.urlPatterns WHERE r.id = :id") + Optional findByIdWithUrlPatterns(Long id); +} diff --git a/src/main/java/com/gcsc/guide/repository/UserRepository.java b/src/main/java/com/gcsc/guide/repository/UserRepository.java new file mode 100644 index 0000000..7f2dfbe --- /dev/null +++ b/src/main/java/com/gcsc/guide/repository/UserRepository.java @@ -0,0 +1,24 @@ +package com.gcsc.guide.repository; + +import com.gcsc.guide.entity.User; +import com.gcsc.guide.entity.UserStatus; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + + Optional findByEmail(String email); + + @Query("SELECT u FROM User u LEFT JOIN FETCH u.roles r LEFT JOIN FETCH r.urlPatterns WHERE u.id = :id") + Optional findByIdWithRoles(Long id); + + @Query("SELECT u FROM User u LEFT JOIN FETCH u.roles r LEFT JOIN FETCH r.urlPatterns WHERE u.email = :email") + Optional findByEmailWithRoles(String email); + + List findByStatus(UserStatus status); + + long countByStatus(UserStatus status); +} diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml new file mode 100644 index 0000000..ae3cdb2 --- /dev/null +++ b/src/main/resources/application-local.yml @@ -0,0 +1,21 @@ +spring: + datasource: + url: jdbc:h2:mem:gcguide + driver-class-name: org.h2.Driver + username: sa + password: + h2: + console: + enabled: true + path: /h2-console + jpa: + hibernate: + ddl-auto: create-drop + database-platform: org.hibernate.dialect.H2Dialect + show-sql: true + +# 로컬에서는 Security 비활성화 (개발 편의) +logging: + level: + com.gcsc.guide: DEBUG + org.springframework.security: DEBUG diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000..5df3084 --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,15 @@ +spring: + datasource: + url: jdbc:postgresql://${DB_HOST:172.17.0.1}:${DB_PORT:5432}/${DB_NAME:gc_guide} + username: ${DB_USER:gcguide} + password: ${DB_PASS:GcGuide!2026} + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: validate + database-platform: org.hibernate.dialect.PostgreSQLDialect + show-sql: false + +logging: + level: + com.gcsc.guide: INFO diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..b625f85 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,42 @@ +spring: + application: + name: gc-guide-api + + # 프로필별 DB 설정 + profiles: + active: ${SPRING_PROFILES_ACTIVE:local} + + jpa: + open-in-view: false + defer-datasource-initialization: true + properties: + hibernate: + format_sql: true + + jackson: + serialization: + write-dates-as-timestamps: false + +server: + port: ${SERVER_PORT:8080} + +# 앱 설정 +app: + jwt: + secret: ${JWT_SECRET:gc-guide-dev-jwt-secret-key-must-be-at-least-256-bits-long} + expiration-ms: ${JWT_EXPIRATION:86400000} # 24시간 + google: + client-id: ${GOOGLE_CLIENT_ID:} + allowed-email-domain: gcsc.co.kr + cors: + allowed-origins: ${CORS_ORIGINS:http://localhost:5173,https://guide.gc-si.dev} + +# Actuator +management: + endpoints: + web: + exposure: + include: health,info + endpoint: + health: + show-details: when-authorized diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql new file mode 100644 index 0000000..475970f --- /dev/null +++ b/src/main/resources/data.sql @@ -0,0 +1,11 @@ +-- 초기 롤 시드 데이터 +INSERT INTO roles (name, description, created_at) VALUES + ('ADMIN', '전체 접근 권한 (관리자 페이지 포함)', NOW()), + ('DEVELOPER', '전체 개발 가이드 접근', NOW()), + ('FRONT_DEV', '프론트엔드 개발 가이드만', NOW()); + +-- 롤별 URL 패턴 +INSERT INTO role_url_patterns (role_id, url_pattern, created_at) VALUES + ((SELECT id FROM roles WHERE name = 'ADMIN'), '/**', NOW()), + ((SELECT id FROM roles WHERE name = 'DEVELOPER'), '/dev/**', NOW()), + ((SELECT id FROM roles WHERE name = 'FRONT_DEV'), '/dev/front/**', NOW()); diff --git a/src/test/java/com/gcsc/guide/GcGuideApiApplicationTests.java b/src/test/java/com/gcsc/guide/GcGuideApiApplicationTests.java new file mode 100644 index 0000000..a793ebb --- /dev/null +++ b/src/test/java/com/gcsc/guide/GcGuideApiApplicationTests.java @@ -0,0 +1,13 @@ +package com.gcsc.guide; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class GcGuideApiApplicationTests { + + @Test + void contextLoads() { + } + +}