From d332283e867b0ef737ca4cd5135cb5d0796f54fb Mon Sep 17 00:00:00 2001 From: htlee Date: Sat, 14 Feb 2026 13:00:24 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20Spring=20Boot=203.5=20+=20JDK=2017=20?= =?UTF-8?q?=EC=B4=88=EA=B8=B0=20=ED=94=84=EB=A1=9C=EC=A0=9D=ED=8A=B8=20?= =?UTF-8?q?=EA=B5=AC=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Spring Boot 3.5.2 + Spring Security + JPA + PostgreSQL - Google OAuth2 ID Token 검증 (google-api-client) - JWT 인증 (jjwt 0.12.6) - H2 인메모리 DB (로컬) / PostgreSQL (운영) 프로필 분리 - Nexus 프록시 경유 Maven 빌드 설정 - 팀 워크플로우 템플릿 (common + java-maven) 적용 --- .claude/rules/code-style.md | 59 ++++ .claude/rules/git-workflow.md | 84 +++++ .claude/rules/naming.md | 60 ++++ .claude/rules/team-policy.md | 34 ++ .claude/rules/testing.md | 62 ++++ .claude/settings.json | 47 +++ .claude/skills/create-mr/SKILL.md | 65 ++++ .claude/skills/fix-issue/SKILL.md | 49 +++ .claude/skills/init-project/SKILL.md | 90 ++++++ .claude/skills/sync-team-workflow/SKILL.md | 73 +++++ .claude/workflow-version.json | 43 +++ .editorconfig | 33 ++ .gitattributes | 2 + .githooks/commit-msg | 60 ++++ .githooks/post-checkout | 25 ++ .gitignore | 38 +++ .mvn/settings.xml | 60 ++++ .mvn/wrapper/maven-wrapper.properties | 3 + .sdkmanrc | 1 + CLAUDE.md | 56 ++++ mvnw | 295 ++++++++++++++++++ mvnw.cmd | 189 +++++++++++ pom.xml | 138 ++++++++ .../com/gcsc/guide/GcGuideApiApplication.java | 13 + .../com/gcsc/guide/config/SecurityConfig.java | 28 ++ .../guide/controller/HealthController.java | 18 ++ src/main/resources/application-local.yml | 21 ++ src/main/resources/application-prod.yml | 15 + src/main/resources/application.yml | 35 +++ .../guide/GcGuideApiApplicationTests.java | 13 + 30 files changed, 1709 insertions(+) create mode 100644 .claude/rules/code-style.md create mode 100644 .claude/rules/git-workflow.md create mode 100644 .claude/rules/naming.md create mode 100644 .claude/rules/team-policy.md create mode 100644 .claude/rules/testing.md create mode 100644 .claude/settings.json create mode 100644 .claude/skills/create-mr/SKILL.md create mode 100644 .claude/skills/fix-issue/SKILL.md create mode 100644 .claude/skills/init-project/SKILL.md create mode 100644 .claude/skills/sync-team-workflow/SKILL.md create mode 100644 .claude/workflow-version.json create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100755 .githooks/commit-msg create mode 100755 .githooks/post-checkout create mode 100644 .gitignore create mode 100644 .mvn/settings.xml create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 .sdkmanrc create mode 100644 CLAUDE.md create mode 100755 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/com/gcsc/guide/GcGuideApiApplication.java create mode 100644 src/main/java/com/gcsc/guide/config/SecurityConfig.java create mode 100644 src/main/java/com/gcsc/guide/controller/HealthController.java create mode 100644 src/main/resources/application-local.yml create mode 100644 src/main/resources/application-prod.yml create mode 100644 src/main/resources/application.yml create mode 100644 src/test/java/com/gcsc/guide/GcGuideApiApplicationTests.java 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/settings.json b/.claude/settings.json new file mode 100644 index 0000000..b3ec3a1 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,47 @@ +{ + "$schema": "https://json.schemastore.org/claude-code-settings.json", + "permissions": { + "allow": [ + "Bash(./mvnw *)", + "Bash(mvn *)", + "Bash(java -version)", + "Bash(java -jar *)", + "Bash(git status)", + "Bash(git diff *)", + "Bash(git log *)", + "Bash(git branch *)", + "Bash(git checkout *)", + "Bash(git add *)", + "Bash(git commit *)", + "Bash(git pull *)", + "Bash(git fetch *)", + "Bash(git merge *)", + "Bash(git stash *)", + "Bash(git remote *)", + "Bash(git config *)", + "Bash(git rev-parse *)", + "Bash(git show *)", + "Bash(git tag *)", + "Bash(curl -s *)", + "Bash(sdk *)" + ], + "deny": [ + "Bash(git push --force*)", + "Bash(git push -f *)", + "Bash(git push origin --force*)", + "Bash(git reset --hard*)", + "Bash(git clean -fd*)", + "Bash(git checkout -- .)", + "Bash(git restore .)", + "Bash(rm -rf /)", + "Bash(rm -rf ~)", + "Bash(rm -rf .git*)", + "Bash(rm -rf /*)", + "Read(./**/.env)", + "Read(./**/.env.*)", + "Read(./**/secrets/**)", + "Read(./**/application-local.yml)", + "Read(./**/application-local.properties)" + ] + } +} diff --git a/.claude/skills/create-mr/SKILL.md b/.claude/skills/create-mr/SKILL.md new file mode 100644 index 0000000..741fbc2 --- /dev/null +++ b/.claude/skills/create-mr/SKILL.md @@ -0,0 +1,65 @@ +--- +name: create-mr +description: 현재 브랜치에서 Gitea MR(Merge Request)을 생성합니다 +allowed-tools: "Bash, Read, Grep" +argument-hint: "[target-branch: develop|main] (기본: develop)" +--- + +현재 브랜치의 변경 사항을 기반으로 Gitea에 MR을 생성합니다. +타겟 브랜치: $ARGUMENTS (기본: develop) + +## 수행 단계 + +### 1. 사전 검증 +- 현재 브랜치가 main/develop이 아닌지 확인 +- 커밋되지 않은 변경 사항 확인 (있으면 경고) +- 리모트에 현재 브랜치가 push되어 있는지 확인 (안 되어 있으면 push) + +### 2. 변경 내역 분석 +```bash +git log develop..HEAD --oneline +git diff develop..HEAD --stat +``` +- 커밋 목록과 변경된 파일 목록 수집 +- 주요 변경 사항 요약 작성 + +### 3. MR 정보 구성 +- **제목**: 브랜치의 첫 커밋 메시지 또는 브랜치명에서 추출 + - `feature/ISSUE-42-user-login` → `feat: ISSUE-42 user-login` +- **본문**: + ```markdown + ## 변경 사항 + - (커밋 기반 자동 생성) + + ## 관련 이슈 + - closes #이슈번호 (브랜치명에서 추출) + + ## 테스트 + - [ ] 빌드 성공 확인 + - [ ] 기존 테스트 통과 + ``` + +### 4. Gitea API로 MR 생성 +```bash +# Gitea remote URL에서 owner/repo 추출 +REMOTE_URL=$(git remote get-url origin) + +# Gitea API 호출 +curl -X POST "GITEA_URL/api/v1/repos/{owner}/{repo}/pulls" \ + -H "Authorization: token ${GITEA_TOKEN}" \ + -H "Content-Type: application/json" \ + -d '{ + "title": "MR 제목", + "body": "MR 본문", + "head": "현재브랜치", + "base": "타겟브랜치" + }' +``` + +### 5. 결과 출력 +- MR URL 출력 +- 리뷰어 지정 안내 +- 다음 단계: 리뷰 대기 → 승인 → 머지 + +## 필요 환경변수 +- `GITEA_TOKEN`: Gitea API 접근 토큰 (없으면 안내) diff --git a/.claude/skills/fix-issue/SKILL.md b/.claude/skills/fix-issue/SKILL.md new file mode 100644 index 0000000..70452ea --- /dev/null +++ b/.claude/skills/fix-issue/SKILL.md @@ -0,0 +1,49 @@ +--- +name: fix-issue +description: Gitea 이슈를 분석하고 수정 브랜치를 생성합니다 +allowed-tools: "Bash, Read, Write, Edit, Glob, Grep" +argument-hint: "" +--- + +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..f0d4c30 --- /dev/null +++ b/.claude/skills/init-project/SKILL.md @@ -0,0 +1,90 @@ +--- +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/` 디렉토리 존재 여부 확인 + +### 2. CLAUDE.md 생성 +프로젝트 루트에 CLAUDE.md를 생성하고 다음 내용 포함: +- 프로젝트 개요 (이름, 타입, 주요 기술 스택) +- 빌드/실행 명령어 (감지된 빌드 도구 기반) +- 테스트 실행 명령어 +- 프로젝트 디렉토리 구조 요약 +- 팀 컨벤션 참조 (`.claude/rules/` 안내) + +### 3. .claude/ 디렉토리 구성 +이미 팀 표준 파일이 존재하면 건너뜀. 없는 경우: +- `.claude/settings.json` — 프로젝트 타입별 표준 권한 설정 +- `.claude/rules/` — 팀 규칙 파일 (team-policy, git-workflow, code-style, naming, testing) +- `.claude/skills/` — 팀 스킬 (create-mr, fix-issue, sync-team-workflow) + +### 4. Git Hooks 설정 +```bash +git config core.hooksPath .githooks +``` +`.githooks/` 디렉토리에 실행 권한 부여: +```bash +chmod +x .githooks/* +``` + +### 5. 프로젝트 타입별 추가 설정 + +#### java-maven +- `.sdkmanrc` 생성 (java=17.0.18-amzn 또는 프로젝트에 맞는 버전) +- `.mvn/settings.xml` Nexus 미러 설정 확인 +- `mvn compile` 빌드 성공 확인 + +#### java-gradle +- `.sdkmanrc` 생성 +- `gradle.properties.example` Nexus 설정 확인 +- `./gradlew compileJava` 빌드 성공 확인 + +#### react-ts +- `.node-version` 생성 (프로젝트에 맞는 Node 버전) +- `.npmrc` Nexus 레지스트리 설정 확인 +- `npm install && npm run build` 성공 확인 + +### 6. .gitignore 확인 +다음 항목이 .gitignore에 포함되어 있는지 확인하고, 없으면 추가: +``` +.claude/settings.local.json +.claude/CLAUDE.local.md +.env +.env.* +*.local +``` + +### 7. workflow-version.json 생성 +`.claude/workflow-version.json` 파일을 생성하여 현재 글로벌 워크플로우 버전 기록: +```json +{ + "applied_global_version": "1.0.0", + "applied_date": "현재날짜", + "project_type": "감지된타입" +} +``` + +### 8. 검증 및 요약 +- 생성/수정된 파일 목록 출력 +- `git config core.hooksPath` 확인 +- 빌드 명령 실행 가능 확인 +- 다음 단계 안내 (개발 시작, 첫 커밋 방법 등) diff --git a/.claude/skills/sync-team-workflow/SKILL.md b/.claude/skills/sync-team-workflow/SKILL.md new file mode 100644 index 0000000..43dd367 --- /dev/null +++ b/.claude/skills/sync-team-workflow/SKILL.md @@ -0,0 +1,73 @@ +--- +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}/api/v1/repos/gc/template-common/raw/workflow-version.json" +``` + +### 2. 버전 비교 +로컬 `.claude/workflow-version.json`과 비교: +- 버전 일치 → "최신 버전입니다" 안내 후 종료 +- 버전 불일치 → 미적용 변경 항목 추출하여 표시 + +### 3. 프로젝트 타입 감지 +자동 감지 순서: +1. `.claude/workflow-version.json`의 `project_type` 필드 확인 +2. 없으면: `pom.xml` → java-maven, `build.gradle` → java-gradle, `package.json` → react-ts + +### 4. 파일 다운로드 및 적용 +Gitea API로 해당 타입 + 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`: 글로벌 최신으로 교체 + +#### 4-3. 스킬 파일 (덮어쓰기) +``` +.claude/skills/create-mr/SKILL.md +.claude/skills/fix-issue/SKILL.md +.claude/skills/sync-team-workflow/SKILL.md +``` + +#### 4-4. Git Hooks (덮어쓰기 + 실행 권한) +```bash +chmod +x .githooks/* +``` + +### 5. 로컬 버전 업데이트 +`.claude/workflow-version.json` 갱신: +```json +{ + "applied_global_version": "새버전", + "applied_date": "오늘날짜", + "project_type": "감지된타입" +} +``` + +### 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..7e4fa16 --- /dev/null +++ b/.claude/workflow-version.json @@ -0,0 +1,43 @@ +{ + "version": "1.1.0", + "updated": "2026-02-14", + "gitea_url": "https://gitea.gc-si.dev", + "nexus_url": "https://nexus.gc-si.dev", + "changes": [ + { + "version": "1.1.0", + "date": "2026-02-14", + "description": "HTTPS 도메인 마이그레이션 + 개발자 가이드 사이트 추가", + "items": [ + "모든 서비스 URL을 IP:포트 → HTTPS 도메인으로 변경", + "Nexus 레지스트리 URL을 HTTPS 도메인으로 변경 (.npmrc, settings.xml, gradle.properties)", + "sync-team-workflow 스킬 기본 URL 업데이트", + "개발자 가이드 사이트 (guide.gc-si.dev) 추가" + ], + "affected_files": [ + "workflow-version.json", + ".npmrc", + ".mvn/settings.xml", + "gradle.properties.example" + ] + }, + { + "version": "1.0.0", + "date": "2026-02-14", + "description": "팀 워크플로우 초기 구성", + "items": [ + "3계층 정책 강제 (프로젝트 deny + 서버 hooks + Branch Protection)", + "Java Maven/Gradle + React TS 템플릿", + "Nexus 자체 레포지토리 연동", + "Conventional Commits (한/영 혼용)", + "Git hooks: pre-commit(빌드검증), commit-msg(형식검증), post-checkout(hooksPath 자동설정)" + ], + "affected_files": [ + ".claude/settings.json", + ".claude/rules/*", + ".claude/skills/*", + ".githooks/*" + ] + } + ] +} 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/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..93bb350 --- /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 ! echo "$FIRST_LINE" | grep -qE "$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..c518e35 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,56 @@ +# gc-guide-api — 가이드 사이트 백엔드 API + +## 프로젝트 개요 +gc-guide 프론트엔드의 백엔드 API. Google OAuth2 인증, 사용자 관리, 이슈 트래커 제공. + +## 기술 스택 +- Spring Boot 3.5 + JDK 17 +- Spring Security (JWT 기반 인증) +- Spring Data JPA + PostgreSQL (운영) / H2 (로컬) +- Google API Client (ID Token 검증) +- Lombok + +## 빌드 & 실행 + +```bash +./mvnw -s .mvn/settings.xml clean compile # 컴파일 +./mvnw -s .mvn/settings.xml spring-boot:run # 로컬 실행 (H2) +./mvnw -s .mvn/settings.xml package -DskipTests # JAR 패키징 +``` + +## 프로필 +- `local` (기본): H2 인메모리 DB, 디버그 로깅 +- `prod`: PostgreSQL (gc_guide DB), validate 모드 + +## API 엔드포인트 + +### 인증 +- `POST /api/auth/google` — Google ID Token 검증 → JWT 발급 +- `GET /api/auth/me` — 현재 사용자 정보 +- `POST /api/auth/logout` — 세션 무효화 + +### 활동 기록 +- `GET /api/activity/login-history` — 로그인 이력 +- `POST /api/activity/track` — 페이지 조회 기록 + +### 이슈 관리 +- `GET/POST /api/issues` — 이슈 목록/생성 +- `GET/PUT /api/issues/:id` — 이슈 상세/수정 +- `POST /api/issues/:id/comments` — 코멘트 추가 + +### 관리자 +- `GET /api/admin/users` — 사용자 목록 +- `GET /api/admin/stats` — 통계 + +## DB (운영) +- Host: 211.208.115.83:5432 +- Database: gc_guide +- Username: gcguide + +## 배포 +- Docker (eclipse-temurin:17-jre) +- guide.gc-si.dev/api/* → Nginx 프록시 + +## 관련 프로젝트 +- gc-guide: 프론트엔드 (React + TypeScript) +- Gitea: https://gitea.gc-si.dev/gc/gc-guide-api 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/config/SecurityConfig.java b/src/main/java/com/gcsc/guide/config/SecurityConfig.java new file mode 100644 index 0000000..6fb7b2a --- /dev/null +++ b/src/main/java/com/gcsc/guide/config/SecurityConfig.java @@ -0,0 +1,28 @@ +package com.gcsc.guide.config; + +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; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .csrf(csrf -> csrf.disable()) + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/api/auth/**", "/actuator/health", "/h2-console/**").permitAll() + .anyRequest().authenticated() + ) + .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())); + + return http.build(); + } +} 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/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..bdaa7a8 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,35 @@ +spring: + application: + name: gc-guide-api + + # 프로필별 DB 설정 + profiles: + active: ${SPRING_PROFILES_ACTIVE:local} + + jpa: + open-in-view: false + properties: + hibernate: + format_sql: true + +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 + +# Actuator +management: + endpoints: + web: + exposure: + include: health,info + endpoint: + health: + show-details: when-authorized 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() { + } + +}