Compare commits
47 Commits
072f782652
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b27f92bbf | ||
|
|
3bd836e5d8 | ||
|
|
630fa76786 | ||
| 1f0874cbc3 | |||
|
|
62daf51e57 | ||
| f5cd4aa873 | |||
|
|
6f707dcacd | ||
|
|
6d903dea2c | ||
|
|
be3ff66110 | ||
| 6ac9689693 | |||
| a1e3d41dcd | |||
| 6183ae350e | |||
| 0b996c5941 | |||
| 979547d2ce | |||
|
|
5c3b867888 | ||
| fc4770679c | |||
| 235ee5e29b | |||
| 4248a9a0a3 | |||
| 31d3402db8 | |||
| 3ddc8bc76e | |||
| 6dfc8279a8 | |||
| f6f6be31ea | |||
| 1b150af17d | |||
|
|
64d355507e | ||
|
|
50e0a007a3 | ||
| 29f8596f2b | |||
|
|
e62d7a3f1c | ||
|
|
4be71e53ec | ||
| 2b01629d12 | |||
| c640bef2b9 | |||
|
|
8687f009df | ||
|
|
fe0db8e701 | ||
| 4aa3375f57 | |||
| cd689211ec | |||
| f489fa3e51 | |||
| 26350425f5 | |||
| 0e6eb8a64d | |||
| 230ef022c5 | |||
| 4fac74b6a5 | |||
| 51fe350c6d | |||
| 470a5c8add | |||
| 3972a77c85 | |||
|
|
e2025621d6 | ||
| 24934e4a54 | |||
| 35cf8203ba | |||
| e1283792c3 | |||
| ff7d69f0b6 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -39,6 +39,7 @@ jacoco.exec
|
||||
.classpath
|
||||
.settings/
|
||||
bin/
|
||||
.metadata/
|
||||
|
||||
# Temporary files created by the OS
|
||||
.DS_Store
|
||||
|
||||
19
Dockerfile
Normal file
19
Dockerfile
Normal file
@@ -0,0 +1,19 @@
|
||||
# --- build stage ---
|
||||
FROM gradle:8.10.2-jdk17-alpine AS build
|
||||
WORKDIR /workspace
|
||||
COPY . .
|
||||
# 테스트는 생략(필요시 제거)
|
||||
RUN ./gradlew --no-daemon clean bootJar -x test
|
||||
|
||||
# --- run stage ---
|
||||
FROM eclipse-temurin:17-jre-alpine
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache tzdata && cp /usr/share/zoneinfo/Asia/Seoul /etc/localtime
|
||||
# 로그 디렉터리 생성 및 권한 설정
|
||||
RUN mkdir -p /app/logs && chown -R 1000:1000 /app
|
||||
RUN addgroup -S app && adduser -S app -G app -u 1000
|
||||
USER app
|
||||
COPY --from=build /workspace/build/libs/*.jar /app/app.jar
|
||||
EXPOSE 8080
|
||||
ENV JAVA_OPTS="-Xms256m -Xmx512m"
|
||||
ENTRYPOINT ["sh","-c","java $JAVA_OPTS -jar /app/app.jar"]
|
||||
78
README.md
78
README.md
@@ -10,6 +10,28 @@
|
||||
- **Container**: Docker + Kubernetes
|
||||
- **API Documentation**: Swagger (SpringDoc OpenAPI)
|
||||
|
||||
## 개발 환경 설정
|
||||
|
||||
### Eclipse/STS 사용 시 필수 설정
|
||||
|
||||
**Annotation Processing 설정이 필요합니다.**
|
||||
|
||||
STS에서 프로젝트를 열었을 때 컴파일 오류가 발생하는 경우, 다음 설정을 확인하세요:
|
||||
|
||||
1. **프로젝트 우클릭** → **Properties** 선택
|
||||
2. **Java Compiler** → **Annotation Processing** 선택
|
||||
3. 다음 설정을 확인/적용:
|
||||
- **Enable project specific settings** 체크
|
||||
- **Enable annotation processing** 체크
|
||||
- **Enable processing in editor** 체크 해제 (선택사항)
|
||||
- **Generated source directory**: `build/generated/sources/annotationProcessor/java/main`
|
||||
- **Generated test source directory**: `build/generated/sources/annotationProcessor/java/test`
|
||||
|
||||
**설정 이유:**
|
||||
- MapStruct 매퍼 인터페이스의 구현체가 자동 생성됩니다
|
||||
- QueryDSL Q클래스들이 자동 생성됩니다
|
||||
- 이 설정이 없으면 컴파일 오류가 발생할 수 있습니다
|
||||
|
||||
## 개발 가이드
|
||||
|
||||
### 1. 프로젝트 구조
|
||||
@@ -66,7 +88,7 @@ public class ApiResponseDto<T> {
|
||||
"success": true,
|
||||
"code": 201,
|
||||
"message": "COMMON_SUCCESS_CREATED",
|
||||
"description": "Created successfully",
|
||||
"description": "성공적으로 생성되었습니다",
|
||||
"data": {
|
||||
"seq": 1,
|
||||
"userId": "user123",
|
||||
@@ -82,7 +104,7 @@ public class ApiResponseDto<T> {
|
||||
"success": false,
|
||||
"code": 409,
|
||||
"message": "USER_ID_DUPLICATE",
|
||||
"description": "User ID already exists"
|
||||
"description": "이미 존재하는 사용자 ID입니다"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -142,8 +164,8 @@ public enum ApiResponseCode {
|
||||
|
||||
#### 토큰 구성
|
||||
|
||||
- **Access Token**: 15분 (900,000ms) - API 요청 시 사용
|
||||
- **Refresh Token**: 7일 (604,800,000ms) - 쿠키에 저장, 자동 갱신
|
||||
- **Access Token** - 쿠키에 저장, 자동 갱신
|
||||
- **Refresh Token** - 쿠키에 저장, 자동 갱신
|
||||
|
||||
#### 자동 토큰 갱신
|
||||
|
||||
@@ -189,10 +211,8 @@ public enum ApiResponseCode {
|
||||
@Operation(summary = "회원 가입", description = "새로운 회원을 등록합니다.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "201", description = "회원 가입 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터",
|
||||
content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "409", description = "중복된 사용자 정보",
|
||||
content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||
@ApiResponse(responseCode = "409", description = "중복된 사용자 정보", content = @Content)
|
||||
})
|
||||
```
|
||||
|
||||
@@ -353,16 +373,48 @@ public class Member extends BaseEntity {
|
||||
}
|
||||
```
|
||||
|
||||
### 11. 데이터베이스 스키마
|
||||
### 11. DTO 네이밍 규칙
|
||||
|
||||
**데이터베이스 테이블 구조는 `ddl/schema.sql`에 정의되어 있습니다.**
|
||||
#### 기본 원칙
|
||||
|
||||
- **API 계층**: `Dto` 접미사 유지
|
||||
- **Service 계층**: 역할에 따라 `Dto` 접미사 결정
|
||||
|
||||
#### 사용 예시
|
||||
|
||||
```java
|
||||
// API 계층 (Dto 유지)
|
||||
CreateMemberRequestDto, GetMemberResponseDto
|
||||
|
||||
// Service 계층 - 비즈니스 핵심 (Dto 유지)
|
||||
MemberDto
|
||||
|
||||
// Service 계층 - 내부 전달 (Dto 제거)
|
||||
MemberSearchCondition
|
||||
```
|
||||
|
||||
#### 핵심 규칙
|
||||
|
||||
- **API 노출**: `Dto` 유지
|
||||
- **비즈니스 핵심**: `Dto` 유지
|
||||
- **내부 전달**: `Dto` 제거
|
||||
|
||||
### 12. 데이터베이스 스키마
|
||||
|
||||
**데이터베이스 테이블 구조는 `ddl/schema_entity.sql`에 정의되어 있습니다.**
|
||||
|
||||
#### 스키마 파일
|
||||
|
||||
- **위치**: `ddl/schema.sql`
|
||||
- **내용**: 모든 테이블의 CREATE TABLE DDL 스크립트
|
||||
- **위치**: `ddl/schema_entity.sql`
|
||||
- **내용**: 모든 엔티티 테이블의 CREATE TABLE DDL 스크립트
|
||||
|
||||
#### 초기화 스크립트
|
||||
|
||||
- **위치**: `src/main/resources/schema_initial.sql`
|
||||
- **내용**: 서버 부팅 시 자동 실행되는 초기화 스크립트 (예: shedlock 테이블 등)
|
||||
|
||||
#### 사용 방법
|
||||
|
||||
- **자동 생성**: 애플리케이션 시작 시 `schema.sql`로 테이블 자동 생성
|
||||
- **자동 생성**: 애플리케이션 시작 시 `schema_entity.sql`로 엔티티 테이블 자동 생성
|
||||
- **초기화**: 서버 부팅 시 `schema_initial.sql`로 시스템 테이블 자동 생성
|
||||
- **설정**: `spring.jpa.hibernate.ddl-auto=none`으로 Hibernate 자동 스키마 생성 비활성화
|
||||
|
||||
19
build.gradle
19
build.gradle
@@ -62,30 +62,37 @@ dependencies {
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
|
||||
// querydsl
|
||||
// QueryDSL
|
||||
implementation 'io.github.openfeign.querydsl:querydsl-jpa:6.11'
|
||||
annotationProcessor 'io.github.openfeign.querydsl:querydsl-apt:6.11:jpa'
|
||||
annotationProcessor 'jakarta.annotation:jakarta.annotation-api'
|
||||
annotationProcessor 'jakarta.persistence:jakarta.persistence-api'
|
||||
|
||||
// p6spy
|
||||
implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.9.0'
|
||||
implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.12.0'
|
||||
|
||||
// SpringDoc OpenAPI (Swagger)
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.9'
|
||||
|
||||
// ShedLock for distributed scheduling
|
||||
implementation 'net.javacrumbs.shedlock:shedlock-spring:5.10.2'
|
||||
implementation 'net.javacrumbs.shedlock:shedlock-provider-jdbc-template:5.10.2'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
// querydsl
|
||||
def generatedSrcDir = 'build/generated/sources/annotation-processor'
|
||||
// annotationProcessor(QueryDSL, MapStruct)
|
||||
// * Annotation Processing 설정이 필요한경우 "build/generated/sources/annotationProcessor/java/main" 경로 등록
|
||||
def generatedSrcDir = layout.buildDirectory.dir("generated/sources/annotationProcessor/java/main").get().asFile
|
||||
|
||||
clean {
|
||||
delete file(generatedSrcDir)
|
||||
}
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.generatedSourceOutputDirectory = file(generatedSrcDir)
|
||||
options.annotationProcessorGeneratedSourcesDirectory = file(generatedSrcDir)
|
||||
options.encoding = 'UTF-8'
|
||||
}
|
||||
|
||||
jib {
|
||||
@@ -94,7 +101,7 @@ jib {
|
||||
// (선택) 인증서 추가/회사 CA 필요 시 extraDirectories 사용
|
||||
}
|
||||
to {
|
||||
image = 'demo.stam.kr/leejisun9/bio-backend'; tags = ['1.0.0'] // 기본 대상 레지스트리
|
||||
image = 'demo.stam.kr/leejisun9/bio-backend'; //tags = ['1.0.0'] // 기본 대상 레지스트리
|
||||
// tags는 skaffold가 자동 주입. 로컬 단독 빌드시 -Djib.to.tags=로 지정 가능
|
||||
}
|
||||
container {
|
||||
|
||||
@@ -1,291 +1,491 @@
|
||||
|
||||
create table st_common_code (
|
||||
sort_order integer not null,
|
||||
use_flag boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
code varchar(50) not null unique,
|
||||
group_code varchar(50) not null,
|
||||
parent_code varchar(50),
|
||||
character_ref1 varchar(100),
|
||||
character_ref2 varchar(100),
|
||||
character_ref3 varchar(100),
|
||||
character_ref4 varchar(100),
|
||||
character_ref5 varchar(100),
|
||||
name varchar(100) not null,
|
||||
description varchar(500),
|
||||
created_id varchar(255),
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_common_code.sort_order is
|
||||
'정렬 순번';
|
||||
|
||||
comment on column st_common_code.use_flag is
|
||||
'사용 여부';
|
||||
|
||||
comment on column st_common_code.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_common_code.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_common_code.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_common_code.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_common_code.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_common_code.code is
|
||||
'코드';
|
||||
|
||||
comment on column st_common_code.group_code is
|
||||
'그룹 코드';
|
||||
|
||||
comment on column st_common_code.parent_code is
|
||||
'부모 코드';
|
||||
|
||||
comment on column st_common_code.character_ref1 is
|
||||
'문자 참조1';
|
||||
|
||||
comment on column st_common_code.character_ref2 is
|
||||
'문자 참조2';
|
||||
|
||||
comment on column st_common_code.character_ref3 is
|
||||
'문자 참조3';
|
||||
|
||||
comment on column st_common_code.character_ref4 is
|
||||
'문자 참조4';
|
||||
|
||||
comment on column st_common_code.character_ref5 is
|
||||
'문자 참조5';
|
||||
|
||||
comment on column st_common_code.name is
|
||||
'코드명';
|
||||
|
||||
comment on column st_common_code.description is
|
||||
'설명';
|
||||
|
||||
comment on column st_common_code.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_common_code.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_common_group_code (
|
||||
sort_order integer not null,
|
||||
use_flag boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
code varchar(50) not null unique,
|
||||
character_ref1_title varchar(100),
|
||||
character_ref2_title varchar(100),
|
||||
character_ref3_title varchar(100),
|
||||
character_ref4_title varchar(100),
|
||||
character_ref5_title varchar(100),
|
||||
name varchar(100) not null,
|
||||
created_id varchar(255),
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_common_group_code.sort_order is
|
||||
'정렬 순번';
|
||||
|
||||
comment on column st_common_group_code.use_flag is
|
||||
'사용 여부';
|
||||
|
||||
comment on column st_common_group_code.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_common_group_code.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_common_group_code.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_common_group_code.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_common_group_code.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_common_group_code.code is
|
||||
'코드';
|
||||
|
||||
comment on column st_common_group_code.character_ref1_title is
|
||||
'문자 참조 타이틀1';
|
||||
|
||||
comment on column st_common_group_code.character_ref2_title is
|
||||
'문자 참조 타이틀2';
|
||||
|
||||
comment on column st_common_group_code.character_ref3_title is
|
||||
'문자 참조 타이틀3';
|
||||
|
||||
comment on column st_common_group_code.character_ref4_title is
|
||||
'문자 참조 타이틀4';
|
||||
|
||||
comment on column st_common_group_code.character_ref5_title is
|
||||
'문자 참조 타이틀5';
|
||||
|
||||
comment on column st_common_group_code.name is
|
||||
'코드명';
|
||||
|
||||
comment on column st_common_group_code.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_common_group_code.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_file (
|
||||
use_flag boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
file_size bigint not null,
|
||||
group_oid bigint,
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
content_type varchar(255) not null,
|
||||
created_id varchar(255),
|
||||
description varchar(255),
|
||||
file_path varchar(255) not null,
|
||||
original_file_name varchar(255) not null,
|
||||
stored_file_name varchar(255) not null,
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_file.use_flag is
|
||||
'사용 여부';
|
||||
|
||||
comment on column st_file.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_file.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_file.file_size is
|
||||
'파일 크기';
|
||||
|
||||
comment on column st_file.group_oid is
|
||||
'그룹 OID';
|
||||
|
||||
comment on column st_file.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_file.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_file.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_file.content_type is
|
||||
'콘텐츠 타입';
|
||||
|
||||
comment on column st_file.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_file.description is
|
||||
'설명';
|
||||
|
||||
comment on column st_file.file_path is
|
||||
'파일 경로';
|
||||
|
||||
comment on column st_file.original_file_name is
|
||||
'원본 파일명';
|
||||
|
||||
comment on column st_file.stored_file_name is
|
||||
'저장 파일명';
|
||||
|
||||
comment on column st_file.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_member (
|
||||
use_flag boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
last_login_at timestamp(6),
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
login_ip varchar(45),
|
||||
name varchar(100) not null,
|
||||
password varchar(100) not null,
|
||||
user_id varchar(100) not null,
|
||||
refresh_token varchar(1024),
|
||||
created_id varchar(255),
|
||||
email varchar(255) not null,
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_member.use_flag is
|
||||
'사용 여부';
|
||||
|
||||
comment on column st_member.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_member.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_member.last_login_at is
|
||||
'마지막 로그인 일시';
|
||||
|
||||
comment on column st_member.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_member.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_member.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_member.login_ip is
|
||||
'로그인 IP';
|
||||
|
||||
comment on column st_member.name is
|
||||
'이름';
|
||||
|
||||
comment on column st_member.password is
|
||||
'비밀번호';
|
||||
|
||||
comment on column st_member.user_id is
|
||||
'사용자 ID';
|
||||
|
||||
comment on column st_member.refresh_token is
|
||||
'리프레시 토큰';
|
||||
|
||||
comment on column st_member.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_member.email is
|
||||
'이메일';
|
||||
|
||||
comment on column st_member.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create index idx_common_code_code
|
||||
on st_common_code (code);
|
||||
|
||||
create index idx_common_code_group_code
|
||||
on st_common_code (group_code);
|
||||
|
||||
create index idx_common_code_parent_code
|
||||
on st_common_code (parent_code);
|
||||
|
||||
create index idx_common_group_code_code
|
||||
on st_common_group_code (code);
|
||||
|
||||
create index idx_member_user_id
|
||||
on st_member (user_id);
|
||||
|
||||
create table st_auth_group (
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
name varchar(100),
|
||||
created_id varchar(255),
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_auth_group.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_auth_group.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_auth_group.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_auth_group.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_auth_group.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_auth_group.name is
|
||||
'권한 그룹명';
|
||||
|
||||
comment on column st_auth_group.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_auth_group.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_auth_group_resource (
|
||||
auth_group_oid bigint,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
oid bigint not null,
|
||||
resource_oid bigint,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
created_id varchar(255),
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_auth_group_resource.auth_group_oid is
|
||||
'권한 그룹 OID';
|
||||
|
||||
comment on column st_auth_group_resource.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_auth_group_resource.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_auth_group_resource.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_auth_group_resource.resource_oid is
|
||||
'리소스 OID';
|
||||
|
||||
comment on column st_auth_group_resource.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_auth_group_resource.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_auth_group_resource.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_auth_group_resource.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_common_code (
|
||||
sort_order integer not null,
|
||||
use_flag boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
code varchar(50) not null unique,
|
||||
group_code varchar(50) not null,
|
||||
parent_code varchar(50),
|
||||
character_ref1 varchar(100),
|
||||
character_ref2 varchar(100),
|
||||
character_ref3 varchar(100),
|
||||
character_ref4 varchar(100),
|
||||
character_ref5 varchar(100),
|
||||
name varchar(100) not null,
|
||||
description varchar(500),
|
||||
created_id varchar(255),
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_common_code.sort_order is
|
||||
'정렬 순번';
|
||||
|
||||
comment on column st_common_code.use_flag is
|
||||
'사용 여부';
|
||||
|
||||
comment on column st_common_code.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_common_code.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_common_code.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_common_code.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_common_code.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_common_code.code is
|
||||
'코드';
|
||||
|
||||
comment on column st_common_code.group_code is
|
||||
'그룹 코드';
|
||||
|
||||
comment on column st_common_code.parent_code is
|
||||
'부모 코드';
|
||||
|
||||
comment on column st_common_code.character_ref1 is
|
||||
'문자 참조1';
|
||||
|
||||
comment on column st_common_code.character_ref2 is
|
||||
'문자 참조2';
|
||||
|
||||
comment on column st_common_code.character_ref3 is
|
||||
'문자 참조3';
|
||||
|
||||
comment on column st_common_code.character_ref4 is
|
||||
'문자 참조4';
|
||||
|
||||
comment on column st_common_code.character_ref5 is
|
||||
'문자 참조5';
|
||||
|
||||
comment on column st_common_code.name is
|
||||
'코드명';
|
||||
|
||||
comment on column st_common_code.description is
|
||||
'설명';
|
||||
|
||||
comment on column st_common_code.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_common_code.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_common_group_code (
|
||||
sort_order integer not null,
|
||||
use_flag boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
code varchar(50) not null unique,
|
||||
character_ref1_title varchar(100),
|
||||
character_ref2_title varchar(100),
|
||||
character_ref3_title varchar(100),
|
||||
character_ref4_title varchar(100),
|
||||
character_ref5_title varchar(100),
|
||||
name varchar(100) not null,
|
||||
created_id varchar(255),
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_common_group_code.sort_order is
|
||||
'정렬 순번';
|
||||
|
||||
comment on column st_common_group_code.use_flag is
|
||||
'사용 여부';
|
||||
|
||||
comment on column st_common_group_code.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_common_group_code.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_common_group_code.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_common_group_code.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_common_group_code.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_common_group_code.code is
|
||||
'코드';
|
||||
|
||||
comment on column st_common_group_code.character_ref1_title is
|
||||
'문자 참조 타이틀1';
|
||||
|
||||
comment on column st_common_group_code.character_ref2_title is
|
||||
'문자 참조 타이틀2';
|
||||
|
||||
comment on column st_common_group_code.character_ref3_title is
|
||||
'문자 참조 타이틀3';
|
||||
|
||||
comment on column st_common_group_code.character_ref4_title is
|
||||
'문자 참조 타이틀4';
|
||||
|
||||
comment on column st_common_group_code.character_ref5_title is
|
||||
'문자 참조 타이틀5';
|
||||
|
||||
comment on column st_common_group_code.name is
|
||||
'코드명';
|
||||
|
||||
comment on column st_common_group_code.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_common_group_code.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_file (
|
||||
use_flag boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
file_size bigint not null,
|
||||
group_oid bigint,
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
content_type varchar(255) not null,
|
||||
created_id varchar(255),
|
||||
description varchar(255),
|
||||
file_path varchar(255) not null,
|
||||
original_file_name varchar(255) not null,
|
||||
stored_file_name varchar(255) not null,
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_file.use_flag is
|
||||
'사용 여부';
|
||||
|
||||
comment on column st_file.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_file.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_file.file_size is
|
||||
'파일 크기';
|
||||
|
||||
comment on column st_file.group_oid is
|
||||
'그룹 OID';
|
||||
|
||||
comment on column st_file.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_file.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_file.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_file.content_type is
|
||||
'콘텐츠 타입';
|
||||
|
||||
comment on column st_file.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_file.description is
|
||||
'설명';
|
||||
|
||||
comment on column st_file.file_path is
|
||||
'파일 경로';
|
||||
|
||||
comment on column st_file.original_file_name is
|
||||
'원본 파일명';
|
||||
|
||||
comment on column st_file.stored_file_name is
|
||||
'저장 파일명';
|
||||
|
||||
comment on column st_file.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_member (
|
||||
use_flag boolean not null,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
last_login_at timestamp(6),
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
login_ip varchar(45),
|
||||
name varchar(100) not null,
|
||||
password varchar(100) not null,
|
||||
user_id varchar(100) not null,
|
||||
refresh_token varchar(1024),
|
||||
created_id varchar(255),
|
||||
email varchar(255) not null,
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_member.use_flag is
|
||||
'사용 여부';
|
||||
|
||||
comment on column st_member.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_member.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_member.last_login_at is
|
||||
'마지막 로그인 일시';
|
||||
|
||||
comment on column st_member.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_member.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_member.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_member.login_ip is
|
||||
'로그인 IP';
|
||||
|
||||
comment on column st_member.name is
|
||||
'이름';
|
||||
|
||||
comment on column st_member.password is
|
||||
'비밀번호';
|
||||
|
||||
comment on column st_member.user_id is
|
||||
'사용자 ID';
|
||||
|
||||
comment on column st_member.refresh_token is
|
||||
'리프레시 토큰';
|
||||
|
||||
comment on column st_member.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_member.email is
|
||||
'이메일';
|
||||
|
||||
comment on column st_member.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_member_auth_group (
|
||||
auth_group_oid bigint,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
member_oid bigint,
|
||||
oid bigint not null,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
created_id varchar(255),
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_member_auth_group.auth_group_oid is
|
||||
'권한 그룹 OID';
|
||||
|
||||
comment on column st_member_auth_group.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_member_auth_group.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_member_auth_group.member_oid is
|
||||
'사용자 OID';
|
||||
|
||||
comment on column st_member_auth_group.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_member_auth_group.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_member_auth_group.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_member_auth_group.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_member_auth_group.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create table st_resource (
|
||||
menu_yn boolean,
|
||||
sort_order integer,
|
||||
created_at timestamp(6) not null,
|
||||
created_oid bigint,
|
||||
oid bigint not null,
|
||||
parent_code bigint,
|
||||
updated_at timestamp(6) not null,
|
||||
updated_oid bigint,
|
||||
type varchar(50),
|
||||
code varchar(100),
|
||||
name varchar(100),
|
||||
path varchar(100),
|
||||
created_id varchar(255),
|
||||
description varchar(255),
|
||||
updated_id varchar(255),
|
||||
primary key (oid)
|
||||
);
|
||||
|
||||
comment on column st_resource.menu_yn is
|
||||
'메뉴여부';
|
||||
|
||||
comment on column st_resource.sort_order is
|
||||
'정렬 순서';
|
||||
|
||||
comment on column st_resource.created_at is
|
||||
'생성일시';
|
||||
|
||||
comment on column st_resource.created_oid is
|
||||
'생성자 OID';
|
||||
|
||||
comment on column st_resource.oid is
|
||||
'OID';
|
||||
|
||||
comment on column st_resource.parent_code is
|
||||
'부모 코드';
|
||||
|
||||
comment on column st_resource.updated_at is
|
||||
'수정일시';
|
||||
|
||||
comment on column st_resource.updated_oid is
|
||||
'수정자 OID';
|
||||
|
||||
comment on column st_resource.type is
|
||||
'리소스 유형(메뉴, 페이지, 컴포넌트)';
|
||||
|
||||
comment on column st_resource.code is
|
||||
'코드';
|
||||
|
||||
comment on column st_resource.name is
|
||||
'리소스명';
|
||||
|
||||
comment on column st_resource.path is
|
||||
'주소';
|
||||
|
||||
comment on column st_resource.created_id is
|
||||
'생성자 ID';
|
||||
|
||||
comment on column st_resource.description is
|
||||
'설명';
|
||||
|
||||
comment on column st_resource.updated_id is
|
||||
'수정자 ID';
|
||||
|
||||
create index idx_common_code_code
|
||||
on st_common_code (code);
|
||||
|
||||
create index idx_common_code_group_code
|
||||
on st_common_code (group_code);
|
||||
|
||||
create index idx_common_code_parent_code
|
||||
on st_common_code (parent_code);
|
||||
|
||||
create index idx_common_group_code_code
|
||||
on st_common_group_code (code);
|
||||
|
||||
create index idx_member_user_id
|
||||
on st_member (user_id);
|
||||
|
||||
alter table if exists st_auth_group_resource
|
||||
add constraint FKqw6aih072qipjh1r88f0dbfd6
|
||||
foreign key (auth_group_oid)
|
||||
references st_auth_group;
|
||||
|
||||
alter table if exists st_auth_group_resource
|
||||
add constraint FKrvq0ta0bwef2kt6ahklo7f3k4
|
||||
foreign key (resource_oid)
|
||||
references st_resource;
|
||||
|
||||
alter table if exists st_member_auth_group
|
||||
add constraint FKob027cxsjfyvewjb8xp6hjkbm
|
||||
foreign key (auth_group_oid)
|
||||
references st_auth_group;
|
||||
|
||||
alter table if exists st_member_auth_group
|
||||
add constraint FKqew1t81hap15dmn78p8xhunhj
|
||||
foreign key (member_oid)
|
||||
references st_member;
|
||||
2
gradle/wrapper/gradle-wrapper.properties
vendored
2
gradle/wrapper/gradle-wrapper.properties
vendored
@@ -1,6 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
distributionUrl=http\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
Binary file not shown.
BIN
jpa-curd.zip
Normal file
BIN
jpa-curd.zip
Normal file
Binary file not shown.
@@ -31,6 +31,7 @@ http {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
@@ -41,6 +42,7 @@ http {
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# (선택) 업로드 크게 받을 때
|
||||
|
||||
51
nginx-1.28.0/conf/nginx_docker_bak.conf
Normal file
51
nginx-1.28.0/conf/nginx_docker_bak.conf
Normal file
@@ -0,0 +1,51 @@
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
sendfile on;
|
||||
keepalive_timeout 65;
|
||||
|
||||
# (선택) 로그 위치
|
||||
access_log /var/log/nginx/access.log;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
|
||||
# 웹소켓용
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
# Nuxt(개발서버 3000)
|
||||
location / {
|
||||
proxy_pass http://frontend:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
|
||||
# Spring Boot(8080)
|
||||
location /service/ {
|
||||
proxy_pass http://backend:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# (선택) 업로드 크게 받을 때
|
||||
# client_max_body_size 50m;
|
||||
}
|
||||
}
|
||||
@@ -38,8 +38,8 @@ public class CommonCodeController {
|
||||
@Operation(summary = "그룹 코드 생성", description = "새로운 그룹 코드를 생성합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "201", description = "그룹 코드 생성 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "409", description = "중복된 그룹 코드", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||
@ApiResponse(responseCode = "409", description = "중복된 그룹 코드", content = @Content)
|
||||
})
|
||||
@PostMapping("/group")
|
||||
public ResponseEntity<ApiResponseDto<CreateCommonGroupCodeResponseDto>> createGroupCode(@RequestBody @Valid CreateCommonGroupCodeRequestDto requestDto) {
|
||||
@@ -55,8 +55,8 @@ public class CommonCodeController {
|
||||
@Operation(summary = "그룹 코드 수정", description = "기존 그룹 코드를 수정합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "그룹 코드 수정 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "404", description = "그룹 코드를 찾을 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||
@ApiResponse(responseCode = "404", description = "그룹 코드를 찾을 수 없음", content = @Content)
|
||||
})
|
||||
@PutMapping("/group/{code}")
|
||||
public ResponseEntity<ApiResponseDto<String>> updateGroupCode(
|
||||
@@ -71,8 +71,8 @@ public class CommonCodeController {
|
||||
@Operation(summary = "그룹 코드 삭제", description = "그룹 코드를 삭제합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "그룹 코드 삭제 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "하위 공통 코드가 존재하여 삭제할 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "404", description = "그룹 코드를 찾을 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "하위 공통 코드가 존재하여 삭제할 수 없음", content = @Content),
|
||||
@ApiResponse(responseCode = "404", description = "그룹 코드를 찾을 수 없음", content = @Content)
|
||||
})
|
||||
@DeleteMapping("/group/{code}")
|
||||
public ResponseEntity<ApiResponseDto<Void>> deleteGroupCode(@PathVariable String code) {
|
||||
@@ -84,7 +84,7 @@ public class CommonCodeController {
|
||||
@Operation(summary = "그룹 코드 조회", description = "특정 그룹 코드를 조회합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "그룹 코드 조회 성공"),
|
||||
@ApiResponse(responseCode = "404", description = "그룹 코드를 찾을 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "404", description = "그룹 코드를 찾을 수 없음", content = @Content)
|
||||
})
|
||||
@GetMapping("/group/{code}")
|
||||
public ResponseEntity<ApiResponseDto<CommonGroupCodeDto>> getGroupCode(@PathVariable String code) {
|
||||
@@ -119,8 +119,8 @@ public class CommonCodeController {
|
||||
@Operation(summary = "공통 코드 생성", description = "새로운 공통 코드를 생성합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "201", description = "공통 코드 생성 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "409", description = "중복된 공통 코드", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||
@ApiResponse(responseCode = "409", description = "중복된 공통 코드", content = @Content)
|
||||
})
|
||||
@PostMapping
|
||||
public ResponseEntity<ApiResponseDto<CreateCommonCodeResponseDto>> createCode(@RequestBody @Valid CreateCommonCodeRequestDto requestDto) {
|
||||
@@ -136,8 +136,8 @@ public class CommonCodeController {
|
||||
@Operation(summary = "공통 코드 수정", description = "기존 공통 코드를 수정합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "공통 코드 수정 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "404", description = "공통 코드를 찾을 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||
@ApiResponse(responseCode = "404", description = "공통 코드를 찾을 수 없음", content = @Content)
|
||||
})
|
||||
@PutMapping("/{code}")
|
||||
public ResponseEntity<ApiResponseDto<String>> updateCode(
|
||||
@@ -152,8 +152,8 @@ public class CommonCodeController {
|
||||
@Operation(summary = "공통 코드 삭제", description = "공통 코드를 삭제합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "공통 코드 삭제 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "하위 공통 코드가 존재하여 삭제할 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "404", description = "공통 코드를 찾을 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "하위 공통 코드가 존재하여 삭제할 수 없음", content = @Content),
|
||||
@ApiResponse(responseCode = "404", description = "공통 코드를 찾을 수 없음", content = @Content)
|
||||
})
|
||||
@DeleteMapping("/{code}")
|
||||
public ResponseEntity<ApiResponseDto<Void>> deleteCode(@PathVariable String code) {
|
||||
@@ -165,11 +165,11 @@ public class CommonCodeController {
|
||||
@Operation(summary = "공통 코드 조회", description = "특정 공통 코드를 조회합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "공통 코드 조회 성공"),
|
||||
@ApiResponse(responseCode = "404", description = "공통 코드를 찾을 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "404", description = "공통 코드를 찾을 수 없음", content = @Content)
|
||||
})
|
||||
@GetMapping("/{code}")
|
||||
public ResponseEntity<ApiResponseDto<CommonCodeDto>> getCode(@PathVariable String code) {
|
||||
CommonCodeDto commonCode = commonCodeService.getCode(code);
|
||||
public ResponseEntity<ApiResponseDto<GetCommonCodeResponseDto>> getCode(@PathVariable String code) {
|
||||
GetCommonCodeResponseDto commonCode = commonCodeService.getCodeWithJoinInfo(code);
|
||||
return ResponseEntity.ok(ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS_RETRIEVED, commonCode));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.bio.bio_backend.domain.admin.common_code.dto;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 공통 코드 조회용 Response DTO
|
||||
* CommonGroupCode의 name과 Member의 name을 join을 통해 함께 조회
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@SqlResultSetMapping(
|
||||
name = "GetCommonCodeResponseDtoMapping",
|
||||
classes = @ConstructorResult(
|
||||
targetClass = GetCommonCodeResponseDto.class,
|
||||
columns = {
|
||||
@ColumnResult(name = "code", type = String.class),
|
||||
@ColumnResult(name = "name", type = String.class),
|
||||
@ColumnResult(name = "description", type = String.class),
|
||||
@ColumnResult(name = "group_code", type = String.class),
|
||||
@ColumnResult(name = "parent_code", type = String.class),
|
||||
@ColumnResult(name = "character_ref1", type = String.class),
|
||||
@ColumnResult(name = "character_ref2", type = String.class),
|
||||
@ColumnResult(name = "character_ref3", type = String.class),
|
||||
@ColumnResult(name = "character_ref4", type = String.class),
|
||||
@ColumnResult(name = "character_ref5", type = String.class),
|
||||
@ColumnResult(name = "sort_order", type = Integer.class),
|
||||
@ColumnResult(name = "use_flag", type = Boolean.class),
|
||||
@ColumnResult(name = "created_at", type = LocalDateTime.class),
|
||||
@ColumnResult(name = "updated_at", type = LocalDateTime.class),
|
||||
@ColumnResult(name = "group_code_name", type = String.class),
|
||||
@ColumnResult(name = "created_by_name", type = String.class),
|
||||
@ColumnResult(name = "updated_by_name", type = String.class)
|
||||
}
|
||||
)
|
||||
)
|
||||
public class GetCommonCodeResponseDto {
|
||||
|
||||
// CommonCode 기본 정보
|
||||
private String code;
|
||||
private String name;
|
||||
private String description;
|
||||
private String groupCode;
|
||||
private String parentCode;
|
||||
private String characterRef1;
|
||||
private String characterRef2;
|
||||
private String characterRef3;
|
||||
private String characterRef4;
|
||||
private String characterRef5;
|
||||
private Integer sortOrder;
|
||||
private Boolean useFlag;
|
||||
|
||||
// BaseEntity 정보
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
// Join을 통해 가져올 정보
|
||||
private String groupCodeName; // CommonGroupCode의 name
|
||||
private String createdByName; // 생성자 Member의 name
|
||||
private String updatedByName; // 수정자 Member의 name
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.bio.bio_backend.domain.admin.common_code.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.admin.common_code.dto.GetCommonCodeResponseDto;
|
||||
import com.bio.bio_backend.domain.admin.common_code.entity.CommonCode;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용한 커스텀 쿼리 메서드들을 정의하는 인터페이스
|
||||
@@ -24,4 +26,22 @@ public interface CommonCodeRepositoryCustom {
|
||||
* @return List<CommonCode> 활성화된 공통 코드 목록
|
||||
*/
|
||||
List<CommonCode> findByParentCode(String parentCode);
|
||||
|
||||
/**
|
||||
* 특정 공통 코드를 조회하며 CommonGroupCode와 Member 정보를 join하여 함께 조회합니다.
|
||||
* QueryDSL을 사용하여 성능 최적화된 쿼리를 실행합니다.
|
||||
*
|
||||
* @param code 조회할 공통 코드
|
||||
* @return Optional<GetCommonCodeResponseDto> 조회된 공통 코드 정보 (없으면 empty)
|
||||
*/
|
||||
Optional<GetCommonCodeResponseDto> findCodeWithJoinInfo(String code);
|
||||
|
||||
/**
|
||||
* 특정 공통 코드를 조회하며 CommonGroupCode와 Member 정보를 join하여 함께 조회합니다.
|
||||
* Native Query를 사용한 버전 (사용하지 않음, 참고용)
|
||||
*
|
||||
* @param code 조회할 공통 코드
|
||||
* @return Optional<GetCommonCodeResponseDto> 조회된 공통 코드 정보 (없으면 empty)
|
||||
*/
|
||||
Optional<GetCommonCodeResponseDto> findCodeWithJoinInfoNative(String code);
|
||||
}
|
||||
@@ -1,28 +1,29 @@
|
||||
package com.bio.bio_backend.domain.admin.common_code.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.admin.common_code.dto.GetCommonCodeResponseDto;
|
||||
import com.bio.bio_backend.domain.admin.common_code.entity.CommonCode;
|
||||
import com.bio.bio_backend.domain.admin.common_code.entity.QCommonCode;
|
||||
import com.bio.bio_backend.domain.admin.common_code.entity.QCommonGroupCode;
|
||||
import com.bio.bio_backend.domain.base.member.entity.QMember;
|
||||
import com.querydsl.core.types.Projections;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용하여 CommonCodeRepositoryCustom 인터페이스를 구현하는 클래스
|
||||
* 복잡한 쿼리나 동적 쿼리를 QueryDSL로 작성하여 성능과 가독성을 향상시킵니다.
|
||||
*/
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class CommonCodeRepositoryImpl implements CommonCodeRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
private final EntityManager entityManager;
|
||||
|
||||
/**
|
||||
* QCommonCode 인스턴스를 생성하여 쿼리에서 사용합니다.
|
||||
* QueryDSL의 Q클래스를 통해 타입 안전한 쿼리 작성이 가능합니다.
|
||||
*/
|
||||
private final QCommonCode commonCode = QCommonCode.commonCode;
|
||||
private final QCommonGroupCode commonGroupCode = QCommonGroupCode.commonGroupCode;
|
||||
private final QMember member = QMember.member;
|
||||
|
||||
@Override
|
||||
public List<CommonCode> findByGroupCode(String groupCode) {
|
||||
@@ -43,4 +44,53 @@ public class CommonCodeRepositoryImpl implements CommonCodeRepositoryCustom {
|
||||
.orderBy(commonCode.sortOrder.asc())
|
||||
.fetch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<GetCommonCodeResponseDto> findCodeWithJoinInfo(String code) {
|
||||
return Optional.ofNullable(
|
||||
queryFactory
|
||||
.select(Projections.constructor(GetCommonCodeResponseDto.class,
|
||||
commonCode.code, commonCode.name, commonCode.description,
|
||||
commonCode.groupCode, commonCode.parentCode,
|
||||
commonCode.characterRef1, commonCode.characterRef2, commonCode.characterRef3,
|
||||
commonCode.characterRef4, commonCode.characterRef5,
|
||||
commonCode.sortOrder, commonCode.useFlag,
|
||||
commonCode.createdAt, commonCode.updatedAt,
|
||||
commonGroupCode.name, member.name, member.name
|
||||
))
|
||||
.from(commonCode)
|
||||
.leftJoin(commonGroupCode).on(commonCode.groupCode.eq(commonGroupCode.code))
|
||||
.leftJoin(member).on(commonCode.createdOid.eq(member.oid))
|
||||
.leftJoin(member).on(commonCode.updatedOid.eq(member.oid))
|
||||
.where(commonCode.code.eq(code))
|
||||
.fetchOne()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<GetCommonCodeResponseDto> findCodeWithJoinInfoNative(String code) {
|
||||
String nativeQuery = """
|
||||
SELECT cc.code, cc.name, cc.description, cc.group_code, cc.parent_code,
|
||||
cc.character_ref1, cc.character_ref2, cc.character_ref3, cc.character_ref4, cc.character_ref5,
|
||||
cc.sort_order, cc.use_flag, cc.created_at, cc.updated_at,
|
||||
cgc.name as group_code_name, cm1.name as created_by_name, cm2.name as updated_by_name
|
||||
FROM st_common_code cc
|
||||
LEFT JOIN st_common_group_code cgc ON cc.group_code = cgc.code
|
||||
LEFT JOIN st_member cm1 ON cc.created_oid = cm1.oid
|
||||
LEFT JOIN st_member cm2 ON cc.updated_oid = cm2.oid
|
||||
WHERE cc.code = :code
|
||||
""";
|
||||
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<GetCommonCodeResponseDto> results = entityManager
|
||||
.createNativeQuery(nativeQuery, "GetCommonCodeResponseDtoMapping")
|
||||
.setParameter("code", code)
|
||||
.getResultList();
|
||||
|
||||
return results.isEmpty() ? Optional.empty() : Optional.of(results.get(0));
|
||||
} catch (Exception e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ package com.bio.bio_backend.domain.admin.common_code.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.admin.common_code.entity.CommonGroupCode;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.bio.bio_backend.domain.admin.common_code.service;
|
||||
|
||||
import com.bio.bio_backend.domain.admin.common_code.dto.CommonCodeDto;
|
||||
import com.bio.bio_backend.domain.admin.common_code.dto.CommonGroupCodeDto;
|
||||
import com.bio.bio_backend.domain.admin.common_code.dto.GetCommonCodeResponseDto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -20,6 +21,7 @@ public interface CommonCodeService {
|
||||
void updateCode(String code, CommonCodeDto codeDto);
|
||||
void deleteCode(String code);
|
||||
CommonCodeDto getCode(String code);
|
||||
GetCommonCodeResponseDto getCodeWithJoinInfo(String code);
|
||||
List<CommonCodeDto> getActiveCodesByGroupCode(String groupCode);
|
||||
List<CommonCodeDto> getActiveCodesByParentCode(String parentCode);
|
||||
List<CommonCodeDto> getAllCodes();
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.bio.bio_backend.domain.admin.common_code.service;
|
||||
|
||||
import com.bio.bio_backend.domain.admin.common_code.dto.CommonCodeDto;
|
||||
import com.bio.bio_backend.domain.admin.common_code.dto.CommonGroupCodeDto;
|
||||
import com.bio.bio_backend.domain.admin.common_code.dto.GetCommonCodeResponseDto;
|
||||
import com.bio.bio_backend.domain.admin.common_code.entity.CommonCode;
|
||||
import com.bio.bio_backend.domain.admin.common_code.entity.CommonGroupCode;
|
||||
import com.bio.bio_backend.domain.admin.common_code.mapper.CommonCodeMapper;
|
||||
@@ -133,6 +134,12 @@ public class CommonCodeServiceImpl implements CommonCodeService {
|
||||
return commonCodeMapper.toCommonCodeDto(commonCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetCommonCodeResponseDto getCodeWithJoinInfo(String code) {
|
||||
return commonCodeRepository.findCodeWithJoinInfo(code)
|
||||
.orElseThrow(() -> new ApiException(ApiResponseCode.COMMON_CODE_ERROR_003));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CommonCodeDto> getActiveCodesByGroupCode(String groupCode) {
|
||||
List<CommonCode> commonCodes = commonCodeRepository.findByGroupCode(groupCode);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.controller;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.dto.AuthGroupDto;
|
||||
import com.bio.bio_backend.domain.base.authgroup.service.AuthGroupService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth_group")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "AuthGroup", description = "")
|
||||
@Slf4j
|
||||
public class AuthGroupController {
|
||||
|
||||
private final AuthGroupService authGroupService;
|
||||
|
||||
@PostMapping("/create")
|
||||
public AuthGroupDto create(@RequestBody AuthGroupDto authGroupDto) {
|
||||
return authGroupService.create(authGroupDto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public AuthGroupDto getById(@PathVariable Long id) {
|
||||
return authGroupService.getById(id);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<AuthGroupDto> getAll() {
|
||||
return authGroupService.getAll();
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public AuthGroupDto update(@PathVariable Long id, @RequestBody AuthGroupDto dto) {
|
||||
return authGroupService.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void delete(@PathVariable Long id) {
|
||||
authGroupService.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AuthGroupDto {
|
||||
private String name;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.entity;
|
||||
|
||||
import com.bio.bio_backend.global.constants.AppConstants;
|
||||
import com.bio.bio_backend.global.entity.BaseEntity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import org.hibernate.annotations.Comment;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@Table(name = AppConstants.TABLE_PREFIX + "auth_group")
|
||||
public class AuthGroup extends BaseEntity {
|
||||
|
||||
@Column(name = "name", length = 100)
|
||||
@Comment("권한 그룹명")
|
||||
private String name;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.mapper;
|
||||
|
||||
import com.bio.bio_backend.global.config.GlobalMapperConfig;
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.authgroup.dto.AuthGroupDto;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(config = GlobalMapperConfig.class)
|
||||
public interface AuthGroupMapper {
|
||||
AuthGroup toEntity(AuthGroupDto dto);
|
||||
|
||||
AuthGroupDto toDto(AuthGroup entity);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface AuthGroupRepository extends JpaRepository<AuthGroup, Long>, AuthGroupRepositoryCustom {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용한 커스텀 쿼리 메서드들을 정의하는 인터페이스
|
||||
* 복잡한 쿼리나 동적 쿼리가 필요한 경우 이 인터페이스를 구현하여 사용합니다.
|
||||
*/
|
||||
public interface AuthGroupRepositoryCustom {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.QAuthGroup;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용하여 AuthGroupRepositoryCustom 인터페이스를 구현하는 클래스
|
||||
* 복잡한 쿼리나 동적 쿼리를 QueryDSL로 작성하여 성능과 가독성을 향상시킵니다.
|
||||
*/
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class AuthGroupRepositoryImpl implements AuthGroupRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
|
||||
/**
|
||||
* QAuthGroup 인스턴스를 생성하여 쿼리에서 사용합니다.
|
||||
* QueryDSL의 Q클래스를 통해 타입 안전한 쿼리 작성이 가능합니다.
|
||||
*/
|
||||
private final QAuthGroup authGroup = QAuthGroup.authGroup;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.dto.AuthGroupDto;
|
||||
import java.util.List;
|
||||
|
||||
public interface AuthGroupService {
|
||||
AuthGroupDto create(AuthGroupDto dto);
|
||||
|
||||
AuthGroupDto getById(Long id);
|
||||
|
||||
List<AuthGroupDto> getAll();
|
||||
|
||||
AuthGroupDto update(Long id, AuthGroupDto dto);
|
||||
|
||||
void delete(Long id);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.bio.bio_backend.domain.base.authgroup.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.dto.AuthGroupDto;
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.authgroup.repository.AuthGroupRepository;
|
||||
import com.bio.bio_backend.domain.base.authgroup.mapper.AuthGroupMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@Transactional(readOnly = true)
|
||||
public class AuthGroupServiceImpl implements AuthGroupService {
|
||||
|
||||
private final AuthGroupRepository repository;
|
||||
private final AuthGroupMapper mapper;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public AuthGroupDto create(AuthGroupDto dto) {
|
||||
AuthGroup entity = mapper.toEntity(dto);
|
||||
return mapper.toDto(repository.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthGroupDto getById(Long id) {
|
||||
return repository.findById(id).map(mapper::toDto).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AuthGroupDto> getAll() {
|
||||
return repository.findAll().stream().map(mapper::toDto).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public AuthGroupDto update(Long id, AuthGroupDto dto) {
|
||||
AuthGroup entity = repository.findById(id).orElseThrow();
|
||||
// TODO: update fields
|
||||
return mapper.toDto(repository.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void delete(Long id) {
|
||||
repository.deleteById(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.controller;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.dto.AuthGroupResourceDto;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.dto.ReplaceAuthGroupResourcesRequest;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.service.AuthGroupResourceService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth_group_resource")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "AuthGroupResource", description = "")
|
||||
@Slf4j
|
||||
public class AuthGroupResourceController {
|
||||
|
||||
private final AuthGroupResourceService service;
|
||||
|
||||
@PostMapping("/create")
|
||||
public AuthGroupResourceDto create(@RequestBody AuthGroupResourceDto dto) {
|
||||
return service.create(dto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public AuthGroupResourceDto getById(@PathVariable Long id) {
|
||||
return service.getById(id);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<AuthGroupResourceDto> getAll() {
|
||||
return service.getAll();
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public AuthGroupResourceDto update(@PathVariable Long id, @RequestBody AuthGroupResourceDto dto) {
|
||||
return service.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void delete(@PathVariable Long id) {
|
||||
service.delete(id);
|
||||
}
|
||||
|
||||
@PostMapping("/replace")
|
||||
public void replaceAuthGroupResources(@RequestBody ReplaceAuthGroupResourcesRequest request) {
|
||||
service.replaceAuthGroupResources(request.getAuthGroupOid(), request.getResourceOids());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.dto;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.resource.entity.Resource;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AuthGroupResourceDto {
|
||||
private AuthGroup authGroupOid;
|
||||
private Resource resourceOid;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ReplaceAuthGroupResourcesRequest {
|
||||
private Long authGroupOid;
|
||||
private List<Long> resourceOids;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.entity;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.resource.entity.Resource;
|
||||
import com.bio.bio_backend.global.constants.AppConstants;
|
||||
import com.bio.bio_backend.global.entity.BaseEntity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import org.hibernate.annotations.Comment;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@Table(name = AppConstants.TABLE_PREFIX + "auth_group_resource")
|
||||
|
||||
public class AuthGroupResource extends BaseEntity {
|
||||
|
||||
@JoinColumn(name = "auth_group_oid")
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@Comment("권한 그룹 OID")
|
||||
private AuthGroup authGroupOid;
|
||||
|
||||
@JoinColumn(name = "resource_oid")
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@Comment("리소스 OID")
|
||||
private Resource resourceOid;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.mapper;
|
||||
|
||||
import com.bio.bio_backend.global.config.GlobalMapperConfig;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.entity.AuthGroupResource;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.dto.AuthGroupResourceDto;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(config = GlobalMapperConfig.class)
|
||||
public interface AuthGroupResourceMapper {
|
||||
AuthGroupResource toEntity(AuthGroupResourceDto dto);
|
||||
|
||||
AuthGroupResourceDto toDto(AuthGroupResource entity);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.entity.AuthGroupResource;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface AuthGroupResourceRepository
|
||||
extends JpaRepository<AuthGroupResource, Long>, AuthGroupResourceRepositoryCustom {
|
||||
|
||||
@Modifying
|
||||
@Query("delete from AuthGroupResource agr where agr.authGroupOid.oid = :authGroupOid")
|
||||
void deleteByAuthGroupOid(@Param("authGroupOid") Long authGroupOid);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.entity.AuthGroupResource;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용한 커스텀 쿼리 메서드들을 정의하는 인터페이스
|
||||
* 복잡한 쿼리나 동적 쿼리가 필요한 경우 이 인터페이스를 구현하여 사용합니다.
|
||||
*/
|
||||
public interface AuthGroupResourceRepositoryCustom {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.entity.AuthGroupResource;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.entity.QAuthGroupResource;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용하여 AuthGroupResourceRepositoryCustom 인터페이스를 구현하는 클래스
|
||||
* 복잡한 쿼리나 동적 쿼리를 QueryDSL로 작성하여 성능과 가독성을 향상시킵니다.
|
||||
*/
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class AuthGroupResourceRepositoryImpl implements AuthGroupResourceRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
|
||||
/**
|
||||
* QAuthGroupResource 인스턴스를 생성하여 쿼리에서 사용합니다.
|
||||
* QueryDSL의 Q클래스를 통해 타입 안전한 쿼리 작성이 가능합니다.
|
||||
*/
|
||||
private final QAuthGroupResource authGroupResource = QAuthGroupResource.authGroupResource;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.dto.AuthGroupResourceDto;
|
||||
import java.util.List;
|
||||
|
||||
public interface AuthGroupResourceService {
|
||||
AuthGroupResourceDto create(AuthGroupResourceDto dto);
|
||||
|
||||
AuthGroupResourceDto getById(Long id);
|
||||
|
||||
List<AuthGroupResourceDto> getAll();
|
||||
|
||||
AuthGroupResourceDto update(Long id, AuthGroupResourceDto dto);
|
||||
|
||||
void delete(Long id);
|
||||
|
||||
/**
|
||||
* 특정 authGroupOid의 기존 매핑을 모두 삭제하고, 전달된 resourceOid 목록으로 재등록
|
||||
*/
|
||||
void replaceAuthGroupResources(Long authGroupOid, List<Long> resourceOids);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.bio.bio_backend.domain.base.authgroupresource.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.dto.AuthGroupResourceDto;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.entity.AuthGroupResource;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.repository.AuthGroupResourceRepository;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.mapper.AuthGroupResourceMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.resource.entity.Resource;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@Transactional(readOnly = true)
|
||||
public class AuthGroupResourceServiceImpl implements AuthGroupResourceService {
|
||||
|
||||
private final AuthGroupResourceRepository repository;
|
||||
private final AuthGroupResourceMapper mapper;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public AuthGroupResourceDto create(AuthGroupResourceDto dto) {
|
||||
AuthGroupResource entity = mapper.toEntity(dto);
|
||||
return mapper.toDto(repository.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthGroupResourceDto getById(Long id) {
|
||||
return repository.findById(id).map(mapper::toDto).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AuthGroupResourceDto> getAll() {
|
||||
return repository.findAll().stream().map(mapper::toDto).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public AuthGroupResourceDto update(Long id, AuthGroupResourceDto dto) {
|
||||
AuthGroupResource entity = repository.findById(id).orElseThrow();
|
||||
// TODO: update fields
|
||||
return mapper.toDto(repository.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void delete(Long id) {
|
||||
repository.deleteById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void replaceAuthGroupResources(Long authGroupOid, List<Long> resourceOids) {
|
||||
repository.deleteByAuthGroupOid(authGroupOid);
|
||||
|
||||
if (resourceOids == null || resourceOids.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
AuthGroup groupRef = new AuthGroup();
|
||||
groupRef.setOid(authGroupOid);
|
||||
|
||||
for (Long resourceOid : resourceOids) {
|
||||
Resource resourceRef = new Resource();
|
||||
resourceRef.setOid(resourceOid);
|
||||
|
||||
AuthGroupResource entity = AuthGroupResource.builder()
|
||||
.authGroupOid(groupRef)
|
||||
.resourceOid(resourceRef)
|
||||
.build();
|
||||
repository.save(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,8 +37,8 @@ public class FileController {
|
||||
@Operation(summary = "파일 업로드", description = "단일 파일을 업로드합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "파일 업로드 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "500", description = "파일 업로드 실패", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "파일 업로드 실패", content = @Content)
|
||||
})
|
||||
@PostMapping("/upload")
|
||||
public ResponseEntity<ApiResponseDto<FileUploadResponseDto>> uploadFile(
|
||||
@@ -53,8 +53,8 @@ public class FileController {
|
||||
@Operation(summary = "다중 파일 업로드", description = "여러 파일을 동시에 업로드합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "다중 파일 업로드 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "500", description = "다중 파일 업로드 실패", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "다중 파일 업로드 실패", content = @Content)
|
||||
})
|
||||
@PostMapping("/upload-multiple")
|
||||
public ResponseEntity<ApiResponseDto<MultipleFileUploadResponseDto>> uploadMultipleFiles(
|
||||
@@ -69,8 +69,8 @@ public class FileController {
|
||||
@Operation(summary = "파일 다운로드", description = "파일 ID로 파일을 다운로드합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "파일 다운로드 성공"),
|
||||
@ApiResponse(responseCode = "404", description = "파일을 찾을 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "500", description = "파일 다운로드 실패", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "404", description = "파일을 찾을 수 없음", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "파일 다운로드 실패", content = @Content)
|
||||
})
|
||||
@GetMapping("/download/{oid}")
|
||||
public ResponseEntity<ByteArrayResource> downloadFile(@PathVariable Long oid) {
|
||||
@@ -90,8 +90,8 @@ public class FileController {
|
||||
@Operation(summary = "파일 논리적 삭제", description = "파일 ID로 파일을 논리적으로 삭제합니다. (use_flag를 false로 변경)")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "파일 논리적 삭제 성공"),
|
||||
@ApiResponse(responseCode = "404", description = "파일을 찾을 수 없음", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "500", description = "파일 논리적 삭제 실패", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "404", description = "파일을 찾을 수 없음", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "파일 논리적 삭제 실패", content = @Content)
|
||||
})
|
||||
@DeleteMapping("/{oid}")
|
||||
public ResponseEntity<ApiResponseDto<Void>> deleteFile(@PathVariable Long oid) {
|
||||
|
||||
@@ -8,8 +8,14 @@ import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.GetMemberResponseDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.CreateMemberRequestDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.CreateMemberResponseDto;
|
||||
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberSearchCondition;
|
||||
import com.bio.bio_backend.domain.base.member.dto.GetMembersRequestDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.GetMembersPagedRequestDto;
|
||||
import com.bio.bio_backend.global.dto.PagedResult;
|
||||
import com.bio.bio_backend.domain.base.member.service.MemberService;
|
||||
import com.bio.bio_backend.domain.base.member.mapper.MemberMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -26,6 +32,9 @@ import com.bio.bio_backend.global.utils.JwtUtils;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Tag(name = "Member", description = "회원 관련 API")
|
||||
@RestController
|
||||
@RequestMapping("/members")
|
||||
@@ -41,8 +50,8 @@ public class MemberController {
|
||||
@Operation(summary = "회원 등록", description = "새로운 회원을 등록합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "201", description = "회원 가입 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
|
||||
@ApiResponse(responseCode = "409", description = "중복된 사용자 정보", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
|
||||
@ApiResponse(responseCode = "409", description = "중복된 사용자 정보", content = @Content)
|
||||
})
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<ApiResponseDto<CreateMemberResponseDto>> createMember(@RequestBody @Valid CreateMemberRequestDto requestDto) {
|
||||
@@ -53,28 +62,51 @@ public class MemberController {
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(apiResponse);
|
||||
}
|
||||
|
||||
@LogExecution("회원 목록 조회")
|
||||
@Operation(summary = "회원 목록 조회", description = "활성화된 모든 회원의 목록을 조회합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "회원 목록 조회 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 파라미터", content = @Content)
|
||||
})
|
||||
@GetMapping
|
||||
public ResponseEntity<ApiResponseDto<List<GetMemberResponseDto>>> getMembers(@ModelAttribute GetMembersRequestDto requestDto) {
|
||||
MemberSearchCondition condition = memberMapper.toSearchCondition(requestDto);
|
||||
List<GetMemberResponseDto> members = memberService.getMembers(condition);
|
||||
ApiResponseDto<List<GetMemberResponseDto>> apiResponse = ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS, members);
|
||||
log.info("회원 목록 조회 완료: {}명", members.size());
|
||||
|
||||
return ResponseEntity.ok(apiResponse);
|
||||
}
|
||||
|
||||
@LogExecution("회원 목록 조회 (페이지네이션)")
|
||||
@Operation(summary = "회원 목록 조회 (페이지네이션)", description = "페이지네이션을 적용한 회원 목록을 조회합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "회원 목록 조회 성공"),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 요청 파라미터", content = @Content)
|
||||
})
|
||||
@GetMapping("/paged")
|
||||
public ResponseEntity<ApiResponseDto<PagedResult<GetMemberResponseDto>>> getMembersPaged(@ModelAttribute GetMembersPagedRequestDto requestDto) {
|
||||
MemberSearchCondition condition = memberMapper.toSearchCondition(requestDto);
|
||||
PagedResult<GetMemberResponseDto> pagedMembers = memberService.getMembersPaged(condition, requestDto.getPage(), requestDto.getSize());
|
||||
ApiResponseDto<PagedResult<GetMemberResponseDto>> apiResponse = ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS, pagedMembers);
|
||||
log.info("페이지네이션된 회원 목록 조회 완료: 페이지={}, 크기={}, 전체={}명", requestDto.getPage(), requestDto.getSize(), pagedMembers.getTotalElements());
|
||||
|
||||
return ResponseEntity.ok(apiResponse);
|
||||
}
|
||||
|
||||
@LogExecution("로그아웃")
|
||||
@Operation(summary = "로그아웃", description = "사용자 로그아웃을 처리합니다.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "로그아웃 성공"),
|
||||
@ApiResponse(responseCode = "401", description = "인증 실패", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
|
||||
@ApiResponse(responseCode = "200", description = "로그아웃 성공")
|
||||
})
|
||||
@PostMapping("/logout")
|
||||
public ResponseEntity<ApiResponseDto<Void>> logout(HttpServletResponse response) {
|
||||
try {
|
||||
String userId = SecurityUtils.getCurrentUserId();
|
||||
memberService.deleteRefreshToken(userId);
|
||||
|
||||
// 모든 토큰 쿠키 삭제
|
||||
jwtUtils.deleteAllTokenCookies(response);
|
||||
|
||||
log.info("사용자 로그아웃 완료: {}", userId);
|
||||
|
||||
return ResponseEntity.ok(ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS));
|
||||
} catch (Exception e) {
|
||||
log.error("로그아웃 처리 중 오류 발생: {}", e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(ApiResponseDto.fail(ApiResponseCode.COMMON_INTERNAL_SERVER_ERROR));
|
||||
}
|
||||
String userId = SecurityUtils.getCurrentUserId();
|
||||
memberService.deleteRefreshToken(userId);
|
||||
// 모든 토큰 쿠키 삭제
|
||||
jwtUtils.deleteAllTokenCookies(response);
|
||||
log.info("사용자 로그아웃 완료: {}", userId);
|
||||
|
||||
return ResponseEntity.ok(ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.bio.bio_backend.domain.base.member.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 회원 조회용 Response DTO
|
||||
* 민감한 정보(password, refreshToken, loginIp)는 제외하고 안전한 정보만 포함
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class GetMemberResponseDto {
|
||||
|
||||
private Long oid;
|
||||
private String userId;
|
||||
private String name;
|
||||
private String email;
|
||||
private Boolean useFlag;
|
||||
private LocalDateTime lastLoginAt;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.bio.bio_backend.domain.base.member.dto;
|
||||
|
||||
import com.bio.bio_backend.global.dto.BasePagedRequestDto;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 회원 목록 조회 요청용 DTO (검색 조건 + 페이지네이션 포함)
|
||||
* GET /members/paged
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class GetMembersPagedRequestDto extends BasePagedRequestDto {
|
||||
|
||||
private String userId;
|
||||
private String name;
|
||||
private String email;
|
||||
private String searchKeyword;
|
||||
private String createdDateFrom;
|
||||
private String createdDateTo;
|
||||
private String lastLoginFrom;
|
||||
private String lastLoginTo;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.bio.bio_backend.domain.base.member.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 회원 목록 조회 요청용 DTO (검색 조건만 포함)
|
||||
* GET /members
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class GetMembersRequestDto {
|
||||
|
||||
private String userId;
|
||||
private String name;
|
||||
private String email;
|
||||
private String searchKeyword;
|
||||
private String createdDateFrom;
|
||||
private String createdDateTo;
|
||||
private String lastLoginFrom;
|
||||
private String lastLoginTo;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.bio.bio_backend.domain.base.member.dto;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 회원 검색 조건
|
||||
*/
|
||||
@Builder
|
||||
@Getter
|
||||
@Setter
|
||||
public class MemberSearchCondition {
|
||||
|
||||
private String userId;
|
||||
private String name;
|
||||
private String email;
|
||||
private String searchKeyword;
|
||||
private String createdDateFrom;
|
||||
private String createdDateTo;
|
||||
private String lastLoginFrom;
|
||||
private String lastLoginTo;
|
||||
}
|
||||
@@ -4,6 +4,10 @@ import com.bio.bio_backend.domain.base.member.dto.CreateMemberRequestDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.CreateMemberResponseDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.LoginResponseDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberSearchCondition;
|
||||
import com.bio.bio_backend.domain.base.member.dto.GetMembersRequestDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.GetMembersPagedRequestDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.GetMemberResponseDto;
|
||||
import com.bio.bio_backend.domain.base.member.entity.Member;
|
||||
import com.bio.bio_backend.global.annotation.IgnoreBaseEntityMapping;
|
||||
import com.bio.bio_backend.global.config.GlobalMapperConfig;
|
||||
@@ -57,4 +61,24 @@ public interface MemberMapper {
|
||||
* MemberDto를 LoginResponseDto로 변환
|
||||
*/
|
||||
LoginResponseDto toLoginResponseDto(MemberDto memberDto);
|
||||
|
||||
/**
|
||||
* Member 엔티티를 GetMemberResponseDto로 변환 (민감한 정보 제외)
|
||||
*/
|
||||
GetMemberResponseDto toGetMemberResponseDto(Member member);
|
||||
|
||||
/**
|
||||
* Member 엔티티 리스트를 GetMemberResponseDto 리스트로 변환 (민감한 정보 제외)
|
||||
*/
|
||||
List<GetMemberResponseDto> toGetMemberResponseDtoList(List<Member> members);
|
||||
|
||||
/**
|
||||
* GetMembersRequestDto를 MemberSearchCondition으로 변환
|
||||
*/
|
||||
MemberSearchCondition toSearchCondition(GetMembersRequestDto request);
|
||||
|
||||
/**
|
||||
* GetMembersPagedRequestDto를 MemberSearchCondition으로 변환
|
||||
*/
|
||||
MemberSearchCondition toSearchCondition(GetMembersPagedRequestDto request);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.bio.bio_backend.domain.base.member.repository;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@@ -14,4 +16,7 @@ public interface MemberRepository extends JpaRepository<Member, Long>, MemberRep
|
||||
|
||||
// 활성화된 회원 목록 조회
|
||||
List<Member> findByUseFlagTrue();
|
||||
|
||||
// 활성화된 회원 목록 조회 (페이지네이션)
|
||||
Page<Member> findByUseFlagTrue(Pageable pageable);
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
package com.bio.bio_backend.domain.base.member.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberSearchCondition;
|
||||
import com.bio.bio_backend.domain.base.member.entity.Member;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용한 커스텀 쿼리 메서드들을 정의하는 인터페이스
|
||||
* 복잡한 쿼리나 동적 쿼리가 필요한 경우 이 인터페이스를 구현하여 사용합니다.
|
||||
*/
|
||||
public interface MemberRepositoryCustom {
|
||||
|
||||
/**
|
||||
@@ -16,4 +16,21 @@ public interface MemberRepositoryCustom {
|
||||
* @return Optional<Member> 회원 정보 (없으면 empty)
|
||||
*/
|
||||
Optional<Member> findActiveMemberByUserId(String userId);
|
||||
|
||||
/**
|
||||
* QueryDSL을 사용한 회원 목록 조회 (검색 조건 + 페이징)
|
||||
*
|
||||
* @param condition 검색 조건
|
||||
* @param pageable 페이징 정보
|
||||
* @return Page<Member> 검색된 회원 목록
|
||||
*/
|
||||
Page<Member> findMembers(MemberSearchCondition condition, Pageable pageable);
|
||||
|
||||
/**
|
||||
* QueryDSL을 사용한 회원 목록 조회 (검색 조건)
|
||||
*
|
||||
* @param condition 검색 조건
|
||||
* @return List<Member> 검색된 회원 목록
|
||||
*/
|
||||
List<Member> findMembers(MemberSearchCondition condition);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
package com.bio.bio_backend.domain.base.member.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberSearchCondition;
|
||||
import com.bio.bio_backend.domain.base.member.entity.Member;
|
||||
import com.bio.bio_backend.domain.base.member.entity.QMember;
|
||||
import com.querydsl.core.BooleanBuilder;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -17,11 +26,6 @@ import java.util.Optional;
|
||||
public class MemberRepositoryImpl implements MemberRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
|
||||
/**
|
||||
* QMember 인스턴스를 생성하여 쿼리에서 사용합니다.
|
||||
* QueryDSL의 Q클래스를 통해 타입 안전한 쿼리 작성이 가능합니다.
|
||||
*/
|
||||
private final QMember member = QMember.member;
|
||||
|
||||
@Override
|
||||
@@ -35,4 +39,91 @@ public class MemberRepositoryImpl implements MemberRepositoryCustom {
|
||||
|
||||
return Optional.ofNullable(foundMember);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<Member> findMembers(MemberSearchCondition condition, Pageable pageable) {
|
||||
BooleanBuilder builder = buildSearchConditions(condition);
|
||||
|
||||
List<Member> members = queryFactory
|
||||
.selectFrom(member)
|
||||
.where(builder)
|
||||
.orderBy(member.createdAt.desc())
|
||||
.offset(pageable.getOffset())
|
||||
.limit(pageable.getPageSize())
|
||||
.fetch();
|
||||
|
||||
Long total = queryFactory
|
||||
.select(member.count())
|
||||
.from(member)
|
||||
.where(builder)
|
||||
.fetchOne();
|
||||
|
||||
return new PageImpl<>(members, pageable, total);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Member> findMembers(MemberSearchCondition condition) {
|
||||
return queryFactory
|
||||
.selectFrom(member)
|
||||
.where(buildSearchConditions(condition))
|
||||
.orderBy(member.createdAt.desc())
|
||||
.fetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* 검색 조건들을 조합하여 BooleanBuilder 생성
|
||||
*/
|
||||
private BooleanBuilder buildSearchConditions(MemberSearchCondition condition) {
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
|
||||
// 기본 조건: useFlag = true (활성화된 회원만 조회)
|
||||
builder.and(member.useFlag.eq(true));
|
||||
|
||||
// 사용자 ID (정확 일치)
|
||||
if (StringUtils.hasText(condition.getUserId())) {
|
||||
builder.and(member.userId.eq(condition.getUserId()));
|
||||
}
|
||||
|
||||
// 이름 (부분 일치)
|
||||
if (StringUtils.hasText(condition.getName())) {
|
||||
builder.and(member.name.containsIgnoreCase(condition.getName()));
|
||||
}
|
||||
|
||||
// 이메일 (부분 일치)
|
||||
if (StringUtils.hasText(condition.getEmail())) {
|
||||
builder.and(member.email.containsIgnoreCase(condition.getEmail()));
|
||||
}
|
||||
|
||||
// 통합 검색 키워드 (이름, 이메일, 사용자ID에서 검색)
|
||||
if (StringUtils.hasText(condition.getSearchKeyword())) {
|
||||
String keyword = condition.getSearchKeyword();
|
||||
builder.and(member.name.containsIgnoreCase(keyword)
|
||||
.or(member.email.containsIgnoreCase(keyword))
|
||||
.or(member.userId.containsIgnoreCase(keyword)));
|
||||
}
|
||||
|
||||
|
||||
// 생성일 범위
|
||||
if (StringUtils.hasText(condition.getCreatedDateFrom())) {
|
||||
LocalDate fromDate = LocalDate.parse(condition.getCreatedDateFrom(), DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
builder.and(member.createdAt.goe(fromDate.atStartOfDay()));
|
||||
}
|
||||
if (StringUtils.hasText(condition.getCreatedDateTo())) {
|
||||
LocalDate toDate = LocalDate.parse(condition.getCreatedDateTo(), DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
builder.and(member.createdAt.loe(toDate.atTime(23, 59, 59)));
|
||||
}
|
||||
|
||||
// 마지막 로그인 범위
|
||||
if (StringUtils.hasText(condition.getLastLoginFrom())) {
|
||||
LocalDate fromDate = LocalDate.parse(condition.getLastLoginFrom(), DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
builder.and(member.lastLoginAt.goe(fromDate.atStartOfDay()));
|
||||
}
|
||||
if (StringUtils.hasText(condition.getLastLoginTo())) {
|
||||
LocalDate toDate = LocalDate.parse(condition.getLastLoginTo(), DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
builder.and(member.lastLoginAt.loe(toDate.atTime(23, 59, 59)));
|
||||
}
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.bio.bio_backend.domain.base.member.scheduler;
|
||||
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
|
||||
import com.bio.bio_backend.domain.base.member.service.MemberService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* 멤버 동기화 스케줄러
|
||||
* ShedLock을 사용하여 분산 환경에서 중복 실행을 방지합니다.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MemberSyncScheduler {
|
||||
|
||||
private final MemberService memberService;
|
||||
|
||||
/**
|
||||
* 1시간마다 멤버 동기화를 실행합니다.
|
||||
* 현재는 더미 데이터를 생성하지만, 추후 실제 조직도 연동으로 변경 예정입니다.
|
||||
*/
|
||||
@Scheduled(cron = "0 0 * * * *") // 1시간마다
|
||||
@SchedulerLock(name = "memberSync", lockAtMostFor = "50m", lockAtLeastFor = "5m")
|
||||
public void syncMembersAtTopOfHour() {
|
||||
log.info("1시간마다 멤버 동기화 시작");
|
||||
try {
|
||||
int createdCount = createDummyMembers(5); // 1시간마다 5명씩 생성
|
||||
log.info("1시간마다 멤버 동기화 완료: {}명 생성", createdCount);
|
||||
} catch (Exception e) {
|
||||
log.error("1시간마다 멤버 동기화 실패: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 매일 새벽 2시에 대량 동기화를 실행합니다.
|
||||
*/
|
||||
@Scheduled(cron = "0 0 2 * * *") // 매일 새벽 2시
|
||||
@SchedulerLock(name = "memberBulkSync", lockAtMostFor = "30m", lockAtLeastFor = "5m")
|
||||
public void bulkSyncMembers() {
|
||||
log.info("일일 대량 멤버 동기화 시작");
|
||||
try {
|
||||
int createdCount = createDummyMembers(20); // 새벽에 20명씩 생성
|
||||
log.info("일일 대량 멤버 동기화 완료: {}명 생성", createdCount);
|
||||
} catch (Exception e) {
|
||||
log.error("일일 대량 멤버 동기화 실패: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 더미 멤버를 생성합니다.
|
||||
* 추후 실제 조직도 API 연동으로 변경될 예정입니다.
|
||||
*
|
||||
* @param count 생성할 멤버 수
|
||||
* @return 실제 생성된 멤버 수
|
||||
*/
|
||||
private int createDummyMembers(int count) {
|
||||
int createdCount = 0;
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
try {
|
||||
String randomSuffix = String.valueOf(System.currentTimeMillis() + i);
|
||||
|
||||
MemberDto memberDto = MemberDto.builder()
|
||||
.userId("user_" + randomSuffix)
|
||||
.password("password123") // 실제로는 더 복잡한 패스워드 생성
|
||||
.name(generateRandomName())
|
||||
.email("user_" + randomSuffix + "@company.com")
|
||||
.build();
|
||||
|
||||
memberService.createMember(memberDto);
|
||||
createdCount++;
|
||||
|
||||
log.debug("더미 멤버 생성 완료: {}", memberDto.getUserId());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("더미 멤버 생성 실패 ({}번째): {}", i + 1, e.getMessage());
|
||||
// 개별 멤버 생성 실패는 전체 프로세스를 중단하지 않음
|
||||
}
|
||||
}
|
||||
|
||||
return createdCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 랜덤한 이름을 생성합니다.
|
||||
* 실제 환경에서는 조직도에서 가져온 실제 이름을 사용합니다.
|
||||
*
|
||||
* @return 생성된 랜덤 이름
|
||||
*/
|
||||
private String generateRandomName() {
|
||||
String[] surnames = {"김", "이", "박", "최", "정", "강", "조", "윤", "장", "임"};
|
||||
String[] givenNames = {"민수", "지영", "현우", "수진", "태현", "은지", "동훈", "예린", "준호", "서연"};
|
||||
|
||||
String surname = surnames[ThreadLocalRandom.current().nextInt(surnames.length)];
|
||||
String givenName = givenNames[ThreadLocalRandom.current().nextInt(givenNames.length)];
|
||||
|
||||
return surname + givenName;
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.GetMemberResponseDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberSearchCondition;
|
||||
import com.bio.bio_backend.global.dto.PagedResult;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public interface MemberService extends UserDetailsService {
|
||||
|
||||
@@ -19,6 +21,20 @@ public interface MemberService extends UserDetailsService {
|
||||
void deleteRefreshToken(String id);
|
||||
|
||||
void updateMember(MemberDto member);
|
||||
|
||||
List<MemberDto> selectMemberList(Map<String, String> params);
|
||||
|
||||
/**
|
||||
* 검색 조건에 따른 회원 목록 조회
|
||||
* @param condition 검색 조건
|
||||
* @return GetMemberResponseDto 리스트
|
||||
*/
|
||||
List<GetMemberResponseDto> getMembers(MemberSearchCondition condition);
|
||||
|
||||
/**
|
||||
* 페이지네이션된 회원 목록 조회
|
||||
* @param condition 검색 조건
|
||||
* @param page 페이지 번호
|
||||
* @param size 페이지 크기
|
||||
* @return PagedResult<GetMemberResponseDto> 페이지네이션된 회원 목록
|
||||
*/
|
||||
PagedResult<GetMemberResponseDto> getMembersPaged(MemberSearchCondition condition, int page, int size);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.bio.bio_backend.domain.base.member.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.GetMemberResponseDto;
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberSearchCondition;
|
||||
import com.bio.bio_backend.global.dto.PagedResult;
|
||||
import com.bio.bio_backend.domain.base.member.entity.Member;
|
||||
import com.bio.bio_backend.domain.base.member.mapper.MemberMapper;
|
||||
import com.bio.bio_backend.domain.base.member.repository.MemberRepository;
|
||||
@@ -12,12 +15,15 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -88,11 +94,20 @@ public class MemberServiceImpl implements MemberService {
|
||||
member.setRefreshToken(null);
|
||||
memberRepository.save(member);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<MemberDto> selectMemberList(Map<String, String> params) {
|
||||
List<Member> members = memberRepository.findByUseFlagTrue();
|
||||
public List<GetMemberResponseDto> getMembers(MemberSearchCondition condition) {
|
||||
List<Member> members = memberRepository.findMembers(condition);
|
||||
|
||||
return memberMapper.toMemberDtoList(members);
|
||||
return memberMapper.toGetMemberResponseDtoList(members);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PagedResult<GetMemberResponseDto> getMembersPaged(MemberSearchCondition condition, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(page, size);
|
||||
Page<Member> memberPage = memberRepository.findMembers(condition, pageable);
|
||||
List<GetMemberResponseDto> members = memberMapper.toGetMemberResponseDtoList(memberPage.getContent());
|
||||
|
||||
return PagedResult.of(memberPage, members);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.controller;
|
||||
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.dto.MemberAuthGroupDto;
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.dto.ReplaceMemberAuthGroupsRequest;
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.service.MemberAuthGroupService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/member_auth_group")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "MemberAuthGroup", description = "")
|
||||
@Slf4j
|
||||
public class MemberAuthGroupController {
|
||||
|
||||
private final MemberAuthGroupService service;
|
||||
|
||||
@PostMapping
|
||||
public MemberAuthGroupDto create(@RequestBody MemberAuthGroupDto dto) {
|
||||
return service.create(dto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public MemberAuthGroupDto getById(@PathVariable Long id) {
|
||||
return service.getById(id);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<MemberAuthGroupDto> getAll() {
|
||||
return service.getAll();
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public MemberAuthGroupDto update(@PathVariable Long id, @RequestBody MemberAuthGroupDto dto) {
|
||||
return service.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void delete(@PathVariable Long id) {
|
||||
service.delete(id);
|
||||
}
|
||||
|
||||
@PostMapping("/replace")
|
||||
public void replaceMemberAuthGroups(@RequestBody ReplaceMemberAuthGroupsRequest request) {
|
||||
service.replaceMemberAuthGroups(request.getMemberOid(), request.getAuthGroupOids());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.dto;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.member.entity.Member;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MemberAuthGroupDto {
|
||||
private Member memberOid;
|
||||
private AuthGroup authGroupOid;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ReplaceMemberAuthGroupsRequest {
|
||||
private Long memberOid;
|
||||
private List<Long> authGroupOids;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.entity;
|
||||
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.member.entity.Member;
|
||||
import com.bio.bio_backend.global.constants.AppConstants;
|
||||
import com.bio.bio_backend.global.entity.BaseEntity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import org.hibernate.annotations.Comment;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@Table(name = AppConstants.TABLE_PREFIX + "member_auth_group")
|
||||
public class MemberAuthGroup extends BaseEntity {
|
||||
|
||||
@Comment("사용자 OID")
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "member_oid")
|
||||
private Member memberOid;
|
||||
|
||||
@Comment("권한 그룹 OID")
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "auth_group_oid")
|
||||
private AuthGroup authGroupOid;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.mapper;
|
||||
|
||||
import com.bio.bio_backend.global.config.GlobalMapperConfig;
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.entity.MemberAuthGroup;
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.dto.MemberAuthGroupDto;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(config = GlobalMapperConfig.class)
|
||||
public interface MemberAuthGroupMapper {
|
||||
MemberAuthGroup toEntity(MemberAuthGroupDto dto);
|
||||
|
||||
MemberAuthGroupDto toDto(MemberAuthGroup entity);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.entity.MemberAuthGroup;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface MemberAuthGroupRepository
|
||||
extends JpaRepository<MemberAuthGroup, Long>, MemberAuthGroupRepositoryCustom {
|
||||
|
||||
@Modifying
|
||||
@Query("delete from MemberAuthGroup mag where mag.memberOid.oid = :memberOid")
|
||||
void deleteByMemberOid(@Param("memberOid") Long memberOid);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.repository;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용한 커스텀 쿼리 메서드들을 정의하는 인터페이스
|
||||
* 복잡한 쿼리나 동적 쿼리가 필요한 경우 이 인터페이스를 구현하여 사용합니다.
|
||||
*/
|
||||
public interface MemberAuthGroupRepositoryCustom {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.entity.QMemberAuthGroup;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용하여 MemberAuthGroupRepositoryCustom 인터페이스를 구현하는 클래스
|
||||
* 복잡한 쿼리나 동적 쿼리를 QueryDSL로 작성하여 성능과 가독성을 향상시킵니다.
|
||||
*/
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class MemberAuthGroupRepositoryImpl implements MemberAuthGroupRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
|
||||
/**
|
||||
* QMemberAuthGroup 인스턴스를 생성하여 쿼리에서 사용합니다.
|
||||
* QueryDSL의 Q클래스를 통해 타입 안전한 쿼리 작성이 가능합니다.
|
||||
*/
|
||||
private final QMemberAuthGroup memberAuthGroup = QMemberAuthGroup.memberAuthGroup;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.dto.MemberAuthGroupDto;
|
||||
import java.util.List;
|
||||
|
||||
public interface MemberAuthGroupService {
|
||||
MemberAuthGroupDto create(MemberAuthGroupDto dto);
|
||||
|
||||
MemberAuthGroupDto getById(Long id);
|
||||
|
||||
List<MemberAuthGroupDto> getAll();
|
||||
|
||||
MemberAuthGroupDto update(Long id, MemberAuthGroupDto dto);
|
||||
|
||||
void delete(Long id);
|
||||
|
||||
/**
|
||||
* 특정 memberOid의 기존 매핑을 모두 삭제하고, 전달된 authGroupOid 목록으로 재등록
|
||||
*/
|
||||
void replaceMemberAuthGroups(Long memberOid, List<Long> authGroupOids);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.bio.bio_backend.domain.base.memberauthgroup.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.dto.MemberAuthGroupDto;
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.entity.MemberAuthGroup;
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.repository.MemberAuthGroupRepository;
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.mapper.MemberAuthGroupMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.AuthGroup;
|
||||
import com.bio.bio_backend.domain.base.member.entity.Member;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@Transactional(readOnly = true)
|
||||
public class MemberAuthGroupServiceImpl implements MemberAuthGroupService {
|
||||
|
||||
private final MemberAuthGroupRepository repository;
|
||||
private final MemberAuthGroupMapper mapper;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public MemberAuthGroupDto create(MemberAuthGroupDto dto) {
|
||||
MemberAuthGroup entity = mapper.toEntity(dto);
|
||||
return mapper.toDto(repository.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public MemberAuthGroupDto getById(Long id) {
|
||||
return repository.findById(id).map(mapper::toDto).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MemberAuthGroupDto> getAll() {
|
||||
return repository.findAll().stream().map(mapper::toDto).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public MemberAuthGroupDto update(Long id, MemberAuthGroupDto dto) {
|
||||
MemberAuthGroup entity = repository.findById(id).orElseThrow();
|
||||
// TODO: update fields
|
||||
return mapper.toDto(repository.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void delete(Long id) {
|
||||
repository.deleteById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void replaceMemberAuthGroups(Long memberOid, List<Long> authGroupOids) {
|
||||
repository.deleteByMemberOid(memberOid);
|
||||
|
||||
if (authGroupOids == null || authGroupOids.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Member memberRef = new Member();
|
||||
memberRef.setOid(memberOid);
|
||||
|
||||
for (Long groupOid : authGroupOids) {
|
||||
AuthGroup groupRef = new AuthGroup();
|
||||
groupRef.setOid(groupOid);
|
||||
|
||||
MemberAuthGroup entity = MemberAuthGroup.builder()
|
||||
.memberOid(memberRef)
|
||||
.authGroupOid(groupRef)
|
||||
.build();
|
||||
repository.save(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.bio.bio_backend.domain.base.resource.controller;
|
||||
|
||||
import com.bio.bio_backend.domain.base.resource.dto.ResourceDto;
|
||||
import com.bio.bio_backend.domain.base.resource.service.ResourceService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/resource")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "Resource", description = "")
|
||||
@Slf4j
|
||||
public class ResourceController {
|
||||
|
||||
private final ResourceService service;
|
||||
|
||||
@PostMapping("")
|
||||
public ResourceDto create(@RequestBody ResourceDto dto) {
|
||||
return service.createResource(dto);
|
||||
}
|
||||
|
||||
@PostMapping("/list")
|
||||
public List<ResourceDto> createList(@RequestBody List<ResourceDto> list) {
|
||||
return service.createResourceList(list);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResourceDto getById(@PathVariable Long id) {
|
||||
return service.getById(id);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<ResourceDto> getAll() {
|
||||
return service.getAll();
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResourceDto update(@PathVariable Long id, @RequestBody ResourceDto dto) {
|
||||
return service.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void delete(@PathVariable Long id) {
|
||||
service.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.bio.bio_backend.domain.base.resource.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ResourceDto {
|
||||
private String code;
|
||||
private String name;
|
||||
private long parentCode;
|
||||
private String type;
|
||||
private String path;
|
||||
private int sortOrder;
|
||||
private String description;
|
||||
private boolean menuYn;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.bio.bio_backend.domain.base.resource.entity;
|
||||
|
||||
import com.bio.bio_backend.global.constants.AppConstants;
|
||||
import com.bio.bio_backend.global.entity.BaseEntity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import org.hibernate.annotations.Comment;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@Table(name = AppConstants.TABLE_PREFIX + "resource")
|
||||
public class Resource extends BaseEntity {
|
||||
|
||||
@Column(name = "code", length = 100)
|
||||
@Comment("코드")
|
||||
private String code;
|
||||
|
||||
@Column(name = "name", length = 100)
|
||||
@Comment("리소스명")
|
||||
private String name;
|
||||
|
||||
@Column(name = "parent_code")
|
||||
@Comment("부모 코드")
|
||||
private long parentCode;
|
||||
|
||||
@Column(name = "type", length = 50)
|
||||
@Comment("리소스 유형(메뉴, 페이지, 컴포넌트)")
|
||||
private String type;
|
||||
|
||||
@Column(name = "path", length = 100)
|
||||
@Comment("주소")
|
||||
private String path;
|
||||
|
||||
@Column(name = "sort_order")
|
||||
@Comment("정렬 순서")
|
||||
private int sortOrder;
|
||||
|
||||
@Column(name = "description", length = 255)
|
||||
@Comment("설명")
|
||||
private String description;
|
||||
|
||||
@Column(name = "menu_yn")
|
||||
@Comment("메뉴여부")
|
||||
private boolean menuYn;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.bio.bio_backend.domain.base.resource.mapper;
|
||||
|
||||
import com.bio.bio_backend.global.config.GlobalMapperConfig;
|
||||
import com.bio.bio_backend.domain.base.resource.entity.Resource;
|
||||
import com.bio.bio_backend.domain.base.resource.dto.ResourceDto;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(config = GlobalMapperConfig.class)
|
||||
public interface ResourceMapper {
|
||||
Resource toEntity(ResourceDto dto);
|
||||
|
||||
ResourceDto toDto(Resource entity);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.bio.bio_backend.domain.base.resource.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.resource.entity.Resource;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface ResourceRepository extends JpaRepository<Resource, Long>, ResourceRepositoryCustom {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.bio.bio_backend.domain.base.resource.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.resource.entity.Resource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용한 커스텀 쿼리 메서드들을 정의하는 인터페이스
|
||||
* 복잡한 쿼리나 동적 쿼리가 필요한 경우 이 인터페이스를 구현하여 사용합니다.
|
||||
*/
|
||||
public interface ResourceRepositoryCustom {
|
||||
|
||||
List<Resource> findResourcesByMemberId(Long memberOId);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.bio.bio_backend.domain.base.resource.repository;
|
||||
|
||||
import com.bio.bio_backend.domain.base.resource.entity.Resource;
|
||||
import com.bio.bio_backend.domain.base.authgroup.entity.QAuthGroup;
|
||||
import com.bio.bio_backend.domain.base.authgroupresource.entity.QAuthGroupResource;
|
||||
import com.bio.bio_backend.domain.base.memberauthgroup.entity.QMemberAuthGroup;
|
||||
import com.bio.bio_backend.domain.base.resource.entity.QResource;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* QueryDSL을 활용하여 ResourceRepositoryCustom 인터페이스를 구현하는 클래스
|
||||
* 복잡한 쿼리나 동적 쿼리를 QueryDSL로 작성하여 성능과 가독성을 향상시킵니다.
|
||||
*/
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class ResourceRepositoryImpl implements ResourceRepositoryCustom {
|
||||
|
||||
private final JPAQueryFactory queryFactory;
|
||||
|
||||
/**
|
||||
* QResource 인스턴스를 생성하여 쿼리에서 사용합니다.
|
||||
* QueryDSL의 Q클래스를 통해 타입 안전한 쿼리 작성이 가능합니다.
|
||||
*/
|
||||
// private final QMember member = QMember.member;
|
||||
private final QMemberAuthGroup memberAuthGroup = QMemberAuthGroup.memberAuthGroup;
|
||||
private final QAuthGroup authGroup = QAuthGroup.authGroup;
|
||||
private final QAuthGroupResource authGroupResource = QAuthGroupResource.authGroupResource;
|
||||
private final QResource resource = QResource.resource;
|
||||
|
||||
@Override
|
||||
public List<Resource> findResourcesByMemberId(Long memberOId) {
|
||||
return queryFactory
|
||||
.select(resource).distinct()
|
||||
.from(resource)
|
||||
// join(연결할 Q-Type).on(연결 조건) 형태로 명시적 조인
|
||||
.join(authGroupResource).on(authGroupResource.resourceOid.eq(resource))
|
||||
.join(authGroup).on(authGroupResource.authGroupOid.eq(authGroup))
|
||||
.join(memberAuthGroup).on(memberAuthGroup.authGroupOid.eq(authGroup))
|
||||
// 최종적으로 Member ID로 필터링
|
||||
.where(memberAuthGroup.memberOid.oid.eq(memberOId))
|
||||
.fetch();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.bio.bio_backend.domain.base.resource.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.resource.dto.ResourceDto;
|
||||
import java.util.List;
|
||||
|
||||
public interface ResourceService {
|
||||
ResourceDto createResource(ResourceDto dto);
|
||||
|
||||
List<ResourceDto> createResourceList(List<ResourceDto> list);
|
||||
|
||||
ResourceDto getById(Long id);
|
||||
|
||||
List<ResourceDto> getAll();
|
||||
|
||||
ResourceDto update(Long id, ResourceDto dto);
|
||||
|
||||
void delete(Long id);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.bio.bio_backend.domain.base.resource.service;
|
||||
|
||||
import com.bio.bio_backend.domain.base.resource.dto.ResourceDto;
|
||||
import com.bio.bio_backend.domain.base.resource.entity.Resource;
|
||||
import com.bio.bio_backend.domain.base.resource.repository.ResourceRepository;
|
||||
import com.bio.bio_backend.domain.base.resource.mapper.ResourceMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@Transactional(readOnly = true)
|
||||
public class ResourceServiceImpl implements ResourceService {
|
||||
|
||||
private final ResourceRepository repository;
|
||||
private final ResourceMapper mapper;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ResourceDto createResource(ResourceDto dto) {
|
||||
try {
|
||||
Resource entity = mapper.toEntity(dto);
|
||||
return mapper.toDto(repository.save(entity));
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@Override
|
||||
public List<ResourceDto> createResourceList(List<ResourceDto> list) {
|
||||
|
||||
List<ResourceDto> resultList = new ArrayList<>();
|
||||
|
||||
for (ResourceDto dto : list) {
|
||||
try {
|
||||
Resource entity = mapper.toEntity(dto);
|
||||
resultList.add(mapper.toDto(repository.save(entity)));
|
||||
} catch (Exception e) {
|
||||
ResourceDto resultDto = null;
|
||||
resultList.add(resultDto);
|
||||
}
|
||||
}
|
||||
|
||||
return resultList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceDto getById(Long id) {
|
||||
return repository.findById(id).map(mapper::toDto).orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourceDto> getAll() {
|
||||
return repository.findAll().stream().map(mapper::toDto).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ResourceDto update(Long id, ResourceDto dto) {
|
||||
Resource entity = repository.findById(id).orElseThrow();
|
||||
// TODO: update fields
|
||||
return mapper.toDto(repository.save(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void delete(Long id) {
|
||||
repository.deleteById(id);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,24 +1,55 @@
|
||||
package com.bio.bio_backend.global.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
|
||||
@Value("${cors.allowed-origins:http://localhost:3000,http://localhost:8080}")
|
||||
private String allowedOrigins;
|
||||
|
||||
@Bean
|
||||
public CorsFilter corsFilter() {
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.addAllowedOriginPattern("*");
|
||||
config.addAllowedHeader("*");
|
||||
config.addAllowedMethod("*");
|
||||
|
||||
// 허용할 Origin 설정
|
||||
List<String> origins = Arrays.asList(allowedOrigins.split(","));
|
||||
config.setAllowedOrigins(origins);
|
||||
|
||||
// 허용할 헤더 설정
|
||||
config.setAllowedHeaders(Arrays.asList(
|
||||
"Authorization",
|
||||
"Content-Type",
|
||||
"X-Requested-With",
|
||||
"Accept",
|
||||
"Origin",
|
||||
"Access-Control-Request-Method",
|
||||
"Access-Control-Request-Headers"
|
||||
));
|
||||
|
||||
// 허용할 HTTP 메서드 설정
|
||||
config.setAllowedMethods(Arrays.asList(
|
||||
"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
|
||||
));
|
||||
|
||||
// 인증 정보 포함 허용 (JWT 토큰 등)
|
||||
config.setAllowCredentials(true);
|
||||
|
||||
// Preflight 요청 캐시 시간 (초)
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
// 모든 경로에 적용
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
|
||||
return new CorsFilter(source);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.bio.bio_backend.global.config;
|
||||
|
||||
import net.javacrumbs.shedlock.core.LockProvider;
|
||||
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
|
||||
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* 스케줄러 및 분산 락 설정을 위한 Configuration 클래스
|
||||
* ShedLock을 사용하여 분산 환경에서 스케줄러 중복 실행을 방지합니다.
|
||||
*/
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
|
||||
public class SchedulerConfig {
|
||||
|
||||
/**
|
||||
* ShedLock용 LockProvider Bean을 생성합니다.
|
||||
* JDBC 기반으로 분산 락을 관리합니다.
|
||||
*
|
||||
* @param dataSource 데이터소스
|
||||
* @return JdbcTemplateLockProvider 인스턴스
|
||||
*/
|
||||
@Bean
|
||||
public LockProvider lockProvider(DataSource dataSource) {
|
||||
return new JdbcTemplateLockProvider(
|
||||
JdbcTemplateLockProvider.Configuration.builder()
|
||||
.withJdbcTemplate(new JdbcTemplate(dataSource))
|
||||
.usingDbTime() // DB 시간 사용으로 서버 간 시간차 문제 해결
|
||||
.build()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.bio.bio_backend.global.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.Max;
|
||||
|
||||
/**
|
||||
* 기본 페이징 요청 DTO
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BasePagedRequestDto {
|
||||
|
||||
@Min(value = 0, message = "페이지 번호는 0 이상이어야 합니다")
|
||||
@Builder.Default
|
||||
private int page = 0;
|
||||
|
||||
@Min(value = 1, message = "페이지 크기는 1 이상이어야 합니다")
|
||||
@Max(value = 100, message = "페이지 크기는 100 이하여야 합니다")
|
||||
@Builder.Default
|
||||
private int size = 10;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.bio.bio_backend.global.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
/**
|
||||
* 기본 페이징 응답 DTO
|
||||
* 모든 페이징 응답에서 공통으로 사용되는 필드들을 포함
|
||||
*/
|
||||
@Data
|
||||
@SuperBuilder
|
||||
@NoArgsConstructor
|
||||
public class BasePagedResponseDto {
|
||||
|
||||
private int currentPage; // 현재 페이지
|
||||
private int totalPages; // 전체 페이지 수
|
||||
private long totalElements; // 전체 요소 수
|
||||
private int size; // 페이지 크기
|
||||
private boolean hasNext; // 다음 페이지 존재 여부
|
||||
private boolean hasPrevious; // 이전 페이지 존재 여부
|
||||
private boolean isFirst; // 첫 번째 페이지 여부
|
||||
private boolean isLast; // 마지막 페이지 여부
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.bio.bio_backend.global.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 페이지네이션된 결과를 담는 제네릭 클래스
|
||||
* @param <T> 페이지네이션할 데이터의 타입
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class PagedResult<T> extends BasePagedResponseDto {
|
||||
|
||||
private List<T> content;
|
||||
|
||||
public static <T> PagedResult<T> of(Page<?> page, List<T> content) {
|
||||
PagedResult<T> result = new PagedResult<>();
|
||||
result.setContent(content);
|
||||
result.setCurrentPage(page.getNumber());
|
||||
result.setTotalPages(page.getTotalPages());
|
||||
result.setTotalElements(page.getTotalElements());
|
||||
result.setSize(page.getSize());
|
||||
result.setHasNext(page.hasNext());
|
||||
result.setHasPrevious(page.hasPrevious());
|
||||
result.setFirst(page.isFirst());
|
||||
result.setLast(page.isLast());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -6,111 +6,194 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.util.ContentCachingRequestWrapper;
|
||||
import org.springframework.web.util.ContentCachingResponseWrapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@Order(2)
|
||||
public class HttpLoggingFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final int MAX_LOG_BODY = 10 * 1024; // 10 KB
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
// 요청 정보 로깅 (IP 정보 제거)
|
||||
|
||||
ContentCachingRequestWrapper wrappedRequest =
|
||||
(request instanceof ContentCachingRequestWrapper)
|
||||
? (ContentCachingRequestWrapper) request
|
||||
: new ContentCachingRequestWrapper(request);
|
||||
|
||||
ContentCachingResponseWrapper wrappedResponse =
|
||||
(response instanceof ContentCachingResponseWrapper)
|
||||
? (ContentCachingResponseWrapper) response
|
||||
: new ContentCachingResponseWrapper(response);
|
||||
|
||||
log.info("********************************************************************************");
|
||||
log.info("* HTTP REQUEST START");
|
||||
log.info("* Method: {} | URI: {}", request.getMethod(), request.getRequestURI());
|
||||
log.info("* Headers: {}", getRequestHeaders(request));
|
||||
log.info("* Body: {}", getRequestBody(request));
|
||||
log.info("* [START] HTTP LOGGING | TRACE ID: {}", getCurrentTraceId());
|
||||
log.info("* Method: {} | URI: {}", wrappedRequest.getMethod(), wrappedRequest.getRequestURI());
|
||||
log.info("* Headers: {}", getRequestHeaders(wrappedRequest));
|
||||
log.info("********************************************************************************");
|
||||
|
||||
ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
|
||||
ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);
|
||||
|
||||
|
||||
try {
|
||||
filterChain.doFilter(wrappedRequest, wrappedResponse);
|
||||
} finally {
|
||||
long duration = System.currentTimeMillis() - startTime;
|
||||
|
||||
// 응답 정보 로깅
|
||||
String reqBody = extractRequestBody(wrappedRequest);
|
||||
String resBody = extractResponseBody(wrappedResponse);
|
||||
|
||||
log.info("********************************************************************************");
|
||||
log.info("* HTTP RESPONSE END");
|
||||
log.info("* Method: {} | URI: {}", request.getMethod(), request.getRequestURI());
|
||||
log.info("* [END] HTTP LOGGING");
|
||||
log.info("* Method: {} | URI: {}", wrappedRequest.getMethod(), wrappedRequest.getRequestURI());
|
||||
log.info("* Status: {} | Duration: {}ms", wrappedResponse.getStatus(), duration);
|
||||
log.info("* Headers: {}", getResponseHeaders(wrappedResponse));
|
||||
log.info("* Body: {}", getResponseBody(wrappedResponse));
|
||||
log.info("* Req Body: {}", maskSensitiveData(reqBody));
|
||||
log.info("* Res Headers: {}", getResponseHeaders(wrappedResponse));
|
||||
log.info("* Res Body: {}", maskSensitiveData(resBody));
|
||||
log.info("********************************************************************************");
|
||||
|
||||
|
||||
wrappedResponse.copyBodyToResponse();
|
||||
}
|
||||
}
|
||||
|
||||
// 민감 정보 마스킹 메서드
|
||||
|
||||
private String extractRequestBody(ContentCachingRequestWrapper wrapper) {
|
||||
// multipart/form-data 등은 보통 로깅 제외
|
||||
String ct = Optional.ofNullable(wrapper.getContentType()).orElse("");
|
||||
if (ct.toLowerCase(Locale.ROOT).startsWith("multipart/")) {
|
||||
return "(multipart skipped)";
|
||||
}
|
||||
|
||||
byte[] buf = wrapper.getContentAsByteArray();
|
||||
if (buf == null || buf.length == 0) return "";
|
||||
Charset cs = resolveCharset(wrapper.getCharacterEncoding());
|
||||
String s = new String(buf, cs);
|
||||
return truncate(s, MAX_LOG_BODY);
|
||||
}
|
||||
|
||||
private String extractResponseBody(ContentCachingResponseWrapper wrapper) {
|
||||
byte[] buf = wrapper.getContentAsByteArray();
|
||||
if (buf == null || buf.length == 0) return "";
|
||||
|
||||
// UTF-8로 고정하여 한글 깨짐 방지
|
||||
String s = new String(buf, StandardCharsets.UTF_8);
|
||||
return truncate(s, MAX_LOG_BODY);
|
||||
}
|
||||
|
||||
private Charset resolveCharset(String enc) {
|
||||
try {
|
||||
return (enc != null) ? Charset.forName(enc) : StandardCharsets.UTF_8;
|
||||
} catch (Exception e) {
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
}
|
||||
|
||||
private String truncate(String s, int max) {
|
||||
if (s == null) return "N/A";
|
||||
if (s.length() <= max) return s;
|
||||
return s.substring(0, max) + "...(truncated)";
|
||||
}
|
||||
|
||||
// 민감 정보 마스킹 (간단/범용)
|
||||
private String maskSensitiveData(String body) {
|
||||
if (body == null || body.isEmpty()) return "N/A";
|
||||
|
||||
// 비밀번호, 토큰 등 민감 정보 마스킹
|
||||
return body.replaceAll("\"password\"\\s*:\\s*\"[^\"]*\"", "\"password\":\"***\"")
|
||||
.replaceAll("\"token\"\\s*:\\s*\"[^\"]*\"", "\"token\":\"***\"")
|
||||
.replaceAll("\"refreshToken\"\\s*:\\s*\"[^\"]*\"", "\"refreshToken\":\"***\"");
|
||||
// JSON 키 기준 토큰/비번류 마스킹 (대소문자 무시)
|
||||
String masked = body
|
||||
.replaceAll("(?i)(\"password\"\\s*:\\s*\")([^\"]+)(\")", "$1***$3")
|
||||
.replaceAll("(?i)(\"AccessToken\"\\s*:\\s*\")([^\"]+)(\")", "$1***$3")
|
||||
.replaceAll("(?i)(\"RefreshToken\"\\s*:\\s*\")([^\"]+)(\")", "$1***$3")
|
||||
.replaceAll("(?i)(\"authorization\"\\s*:\\s*\")([^\"]+)(\")", "$1***$3");
|
||||
// x-www-form-urlencoded 형태의 password 파라미터 마스킹
|
||||
masked = masked.replaceAll("(?i)(^|[&])password=([^&]*)", "$1password=***");
|
||||
return masked;
|
||||
}
|
||||
|
||||
|
||||
private String getRequestHeaders(HttpServletRequest request) {
|
||||
// 주요 헤더만 (Content-Type, Authorization, User-Agent)
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Content-Type", request.getContentType());
|
||||
headers.put("User-Agent", request.getHeader("User-Agent"));
|
||||
|
||||
// Authorization 헤더는 마스킹
|
||||
String auth = request.getHeader("Authorization");
|
||||
if (auth != null) {
|
||||
headers.put("Authorization", auth.startsWith("Bearer ") ? "Bearer ***" : "***");
|
||||
}
|
||||
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
// 필요한 헤더만 추리거나, 전부 찍고 민감한 건 마스킹
|
||||
Collections.list(request.getHeaderNames()).forEach(name -> {
|
||||
String value = request.getHeader(name);
|
||||
if (value == null) {
|
||||
headers.put(name, null);
|
||||
return;
|
||||
}
|
||||
|
||||
if ("cookie".equalsIgnoreCase(name)) {
|
||||
headers.put(name, maskCookieHeader(value));
|
||||
return;
|
||||
}
|
||||
|
||||
// 기타 헤더는 그대로 기록 (요구사항에 따라 최소 마스킹 적용)
|
||||
headers.put(name, value);
|
||||
});
|
||||
return headers.toString();
|
||||
}
|
||||
|
||||
private String getRequestBody(HttpServletRequest request) {
|
||||
try {
|
||||
ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request;
|
||||
String body = new String(wrapper.getContentAsByteArray());
|
||||
return maskSensitiveData(body);
|
||||
} catch (Exception e) {
|
||||
return "N/A";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private String getResponseHeaders(HttpServletResponse response) {
|
||||
// 응답 헤더 정보
|
||||
return "Content-Type: " + response.getContentType();
|
||||
}
|
||||
|
||||
private String getResponseBody(HttpServletResponse response) {
|
||||
try {
|
||||
ContentCachingResponseWrapper wrapper = (ContentCachingResponseWrapper) response;
|
||||
String body = new String(wrapper.getContentAsByteArray());
|
||||
return maskSensitiveData(body);
|
||||
} catch (Exception e) {
|
||||
return "N/A";
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
for (String name : response.getHeaderNames()) {
|
||||
if ("set-cookie".equalsIgnoreCase(name)) {
|
||||
List<String> values = new ArrayList<>(response.getHeaders(name));
|
||||
List<String> masked = new ArrayList<>();
|
||||
for (String v : values) {
|
||||
masked.add(maskSetCookieHeader(v));
|
||||
}
|
||||
headers.put(name, String.join(",", masked));
|
||||
continue;
|
||||
}
|
||||
|
||||
headers.put(name, String.join(",", response.getHeaders(name)));
|
||||
}
|
||||
if (response.getContentType() != null) {
|
||||
headers.putIfAbsent("Content-Type", response.getContentType());
|
||||
}
|
||||
return headers.toString();
|
||||
}
|
||||
|
||||
|
||||
// Cookie 헤더: "a=1; AccessToken=xxx; RefreshToken=yyy" 형태 중 AccessToken/RefreshToken만 마스킹
|
||||
private String maskCookieHeader(String cookieHeader) {
|
||||
if (cookieHeader == null || cookieHeader.isEmpty()) return cookieHeader;
|
||||
String masked = cookieHeader
|
||||
.replaceAll("(?i)(^|;\\s*)(AccessToken)=([^;]*)", "$1$2=***")
|
||||
.replaceAll("(?i)(^|;\\s*)(RefreshToken)=([^;]*)", "$1$2=***");
|
||||
return masked;
|
||||
}
|
||||
|
||||
// Set-Cookie: "AccessToken=xxx; Path=/; HttpOnly; ..." 형태 중 AccessToken/RefreshToken만 마스킹
|
||||
private String maskSetCookieHeader(String setCookie) {
|
||||
if (setCookie == null || setCookie.isEmpty()) return setCookie;
|
||||
String masked = setCookie
|
||||
.replaceAll("(?i)^(AccessToken)=([^;]*)", "$1=***")
|
||||
.replaceAll("(?i)^(RefreshToken)=([^;]*)", "$1=***");
|
||||
return masked;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return path.startsWith("/static/") ||
|
||||
path.startsWith("/css/") ||
|
||||
path.startsWith("/js/") ||
|
||||
path.startsWith("/images/") ||
|
||||
path.equals("/actuator/health") ||
|
||||
path.equals("/favicon.ico");
|
||||
return path.startsWith("/static/")
|
||||
|| path.startsWith("/css/")
|
||||
|| path.startsWith("/js/")
|
||||
|| path.startsWith("/images/")
|
||||
|| path.equals("/favicon.ico")
|
||||
|| path.startsWith("/actuator/health");
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 스레드의 TRACE ID를 반환합니다.
|
||||
* @return TRACE ID 또는 "N/A"
|
||||
*/
|
||||
private String getCurrentTraceId() {
|
||||
String traceId = MDC.get("traceId");
|
||||
return traceId != null ? traceId : "N/A";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package com.bio.bio_backend.global.filter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
|
||||
import com.bio.bio_backend.global.utils.HttpUtils;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
@@ -24,7 +22,7 @@ import com.bio.bio_backend.global.dto.ApiResponseDto;
|
||||
import com.bio.bio_backend.domain.base.member.service.MemberService;
|
||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
|
||||
import com.bio.bio_backend.global.utils.JwtUtils;
|
||||
import com.bio.bio_backend.global.config.SecurityPathConfig;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
@@ -35,16 +33,8 @@ public class JwtTokenValidationFilter extends OncePerRequestFilter {
|
||||
private final JwtUtils jwtUtils;
|
||||
private final HttpUtils httpUtils;
|
||||
private final MemberService memberService;
|
||||
private final Environment env;
|
||||
private final SecurityPathConfig securityPathConfig;
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
|
||||
String path = request.getRequestURI();
|
||||
String contextPath = env.getProperty("server.servlet.context-path", "");
|
||||
|
||||
return securityPathConfig.isPermittedPath(path, contextPath);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.bio.bio_backend.global.filter;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@Order(1)
|
||||
public class TraceIdFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String TRACE_ID_HEADER = "X-Trace-Id";
|
||||
private static final String TRACE_ID_MDC_KEY = "traceId";
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
try {
|
||||
// 헤더에서 TRACE ID를 가져오거나 새로 생성
|
||||
String traceId = request.getHeader(TRACE_ID_HEADER);
|
||||
if (traceId == null || traceId.trim().isEmpty()) {
|
||||
traceId = generateTraceId();
|
||||
}
|
||||
|
||||
// MDC에 TRACE ID 설정
|
||||
MDC.put(TRACE_ID_MDC_KEY, traceId);
|
||||
|
||||
// 응답 헤더에 TRACE ID 추가
|
||||
response.addHeader(TRACE_ID_HEADER, traceId);
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
|
||||
} finally {
|
||||
// 요청 처리 완료 후 MDC 정리
|
||||
MDC.remove(TRACE_ID_MDC_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
private String generateTraceId() {
|
||||
// UUID 기반 TRACE ID 생성 (8자리로 축약)
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package com.bio.bio_backend.global.security;
|
||||
|
||||
import com.bio.bio_backend.global.filter.JwtTokenIssuanceFilter;
|
||||
import com.bio.bio_backend.global.filter.JwtTokenValidationFilter;
|
||||
import com.bio.bio_backend.global.config.CorsConfig;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
@@ -14,6 +16,7 @@ import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@@ -23,7 +26,6 @@ import com.bio.bio_backend.domain.base.member.mapper.MemberMapper;
|
||||
import com.bio.bio_backend.global.exception.CustomAuthenticationFailureHandler;
|
||||
import com.bio.bio_backend.global.utils.JwtUtils;
|
||||
import com.bio.bio_backend.global.utils.HttpUtils;
|
||||
import com.bio.bio_backend.global.config.SecurityPathConfig;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Configuration
|
||||
@@ -35,12 +37,16 @@ public class WebSecurity {
|
||||
private final BCryptPasswordEncoder bCryptPasswordEncoder;
|
||||
private final JwtUtils jwtUtils;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final Environment env;
|
||||
private final SecurityPathConfig securityPathConfig;
|
||||
private final HttpUtils httpUtils;
|
||||
private final MemberMapper memberMapper;
|
||||
private final CorsConfig corsConfig; // CorsConfig 주입
|
||||
|
||||
private JwtTokenIssuanceFilter getJwtTokenIssuanceFilter(AuthenticationManager authenticationManager) throws Exception {
|
||||
// CORS 필터 빈 가져오기
|
||||
private CorsFilter getCorsFilter() {
|
||||
return corsConfig.corsFilter();
|
||||
}
|
||||
|
||||
private JwtTokenIssuanceFilter getJwtTokenIssuanceFilter(AuthenticationManager authenticationManager) {
|
||||
JwtTokenIssuanceFilter filter = new JwtTokenIssuanceFilter(authenticationManager, jwtUtils, objectMapper, memberService, httpUtils, memberMapper);
|
||||
filter.setFilterProcessesUrl("/login");
|
||||
filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler(objectMapper));
|
||||
@@ -48,14 +54,63 @@ public class WebSecurity {
|
||||
}
|
||||
|
||||
private JwtTokenValidationFilter getJwtTokenValidationFilter() {
|
||||
return new JwtTokenValidationFilter(jwtUtils, httpUtils, memberService, env, securityPathConfig);
|
||||
return new JwtTokenValidationFilter(jwtUtils, httpUtils, memberService);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 공개 경로용 SecurityFilterChain (우선순위 1)
|
||||
*
|
||||
* 처리 경로:
|
||||
* - 인증 관련: /login, /logout, /members/register
|
||||
* - API 문서: /swagger-ui/**, /api-docs/**
|
||||
* - WebSocket: /ws/**
|
||||
* - 모니터링: /actuator/**
|
||||
*
|
||||
* 모든 경로는 인증 없이 접근 가능
|
||||
*/
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
@Order(1)
|
||||
SecurityFilterChain publicChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.securityMatcher(
|
||||
// 인증 관련 공개 경로
|
||||
"/logout", "/members/register",
|
||||
|
||||
// Swagger UI 관련 경로
|
||||
"/swagger-ui/**", "/swagger-ui.html", "/swagger-ui/index.html",
|
||||
|
||||
// API 문서 관련 경로
|
||||
"/api-docs", "/api-docs/**", "/v3/api-docs", "/v3/api-docs/**",
|
||||
|
||||
// WebSocket 관련 경로
|
||||
"/ws/**",
|
||||
|
||||
// Actuator 모니터링 경로
|
||||
"/actuator/**", "/actuator/health/**", "/actuator/info"
|
||||
)
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
|
||||
.sessionManagement(session ->
|
||||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
);
|
||||
//.addFilterBefore(getCorsFilter(), UsernamePasswordAuthenticationFilter.class); // cors를 nginx 통해 처리 중
|
||||
return http.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* API 경로용 SecurityFilterChain (우선순위 2)
|
||||
*
|
||||
* 처리 경로: publicChain에서 처리되지 않는 모든 경로
|
||||
* - 비즈니스 API 엔드포인트
|
||||
* - 사용자 데이터 관련 API
|
||||
* - 관리자 기능 API
|
||||
*
|
||||
* 모든 요청에 대해 JWT 토큰 인증 필수
|
||||
*/
|
||||
@Bean
|
||||
@Order(2)
|
||||
SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
|
||||
// AuthenticationManager 설정
|
||||
AuthenticationManagerBuilder authenticationManagerBuilder =
|
||||
http.getSharedObject(AuthenticationManagerBuilder.class);
|
||||
@@ -63,25 +118,17 @@ public class WebSecurity {
|
||||
|
||||
AuthenticationManager authenticationManager = authenticationManagerBuilder.build();
|
||||
|
||||
// 설정 파일에서 허용할 경로 가져오기
|
||||
String[] permitAllPaths = securityPathConfig.getPermitAllPaths().toArray(new String[0]);
|
||||
|
||||
http.csrf(AbstractHttpConfigurer::disable) //csrf 비활성화
|
||||
.authorizeHttpRequests(request -> //request 허용 설정
|
||||
request
|
||||
.requestMatchers(permitAllPaths).permitAll() // 설정 파일에서 허용할 경로
|
||||
.anyRequest().authenticated() // 나머지 요청은 인증 필요
|
||||
)
|
||||
.authenticationManager(authenticationManager)
|
||||
.sessionManagement(session ->
|
||||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 세션 사용 안함
|
||||
)
|
||||
.logout(AbstractHttpConfigurer::disable);
|
||||
http
|
||||
// 1단계: JWT 토큰 발급 필터 (로그인 요청 처리 및 토큰 발급)
|
||||
.addFilterBefore(getJwtTokenIssuanceFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
|
||||
// 2단계: JWT 토큰 검증 필터 (자동 토큰 갱신 포함)
|
||||
.addFilterBefore(getJwtTokenValidationFilter(), UsernamePasswordAuthenticationFilter.class);
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
|
||||
.authenticationManager(authenticationManager)
|
||||
.sessionManagement(session ->
|
||||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
)
|
||||
.logout(AbstractHttpConfigurer::disable)
|
||||
//.addFilterBefore(getCorsFilter(), UsernamePasswordAuthenticationFilter.class) // cors를 nginx 통해 처리 중
|
||||
.addFilterBefore(getJwtTokenIssuanceFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class) // 토큰 발급
|
||||
.addFilterBefore(getJwtTokenValidationFilter(), UsernamePasswordAuthenticationFilter.class); // 토큰 검증
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@@ -36,16 +36,6 @@ public class JwtUtils {
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
|
||||
// Token 생성
|
||||
public String generateToken(String username, long expirationTime) {
|
||||
return Jwts.builder()
|
||||
.subject(username)
|
||||
.issuedAt(new Date(System.currentTimeMillis()))
|
||||
.expiration(new Date(System.currentTimeMillis() + expirationTime))
|
||||
.signWith(getSigningKey())
|
||||
.compact();
|
||||
}
|
||||
|
||||
// Token 생성 (사용자 정보 포함)
|
||||
public String generateToken(Long oid, String username, String name, long expirationTime) {
|
||||
return Jwts.builder()
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.bio.bio_backend.global.utils;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
|
||||
/**
|
||||
* TRACE ID 관리를 위한 유틸리티 클래스
|
||||
*/
|
||||
public class TraceIdUtils {
|
||||
|
||||
private static final String TRACE_ID_KEY = "traceId";
|
||||
|
||||
/**
|
||||
* 현재 스레드의 TRACE ID를 반환합니다.
|
||||
* @return TRACE ID 또는 null
|
||||
*/
|
||||
public static String getCurrentTraceId() {
|
||||
return MDC.get(TRACE_ID_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* TRACE ID가 존재하는지 확인합니다.
|
||||
* @return TRACE ID 존재 여부
|
||||
*/
|
||||
public static boolean hasTraceId() {
|
||||
return getCurrentTraceId() != null;
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ spring.devtools.restart.additional-paths=src/main/java
|
||||
# ========================================
|
||||
# 데이터베이스 설정
|
||||
# ========================================
|
||||
spring.datasource.url=jdbc:postgresql://stam.kr:15432/imas
|
||||
spring.datasource.url=jdbc:postgresql://stam.kr:15432/imas?options=-c%20TimeZone=Asia/Seoul
|
||||
spring.datasource.username=imas_user
|
||||
spring.datasource.password=stam1201
|
||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
@@ -24,6 +24,10 @@ spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
# spring.datasource.username=${DB_USERNAME:}
|
||||
# spring.datasource.password=${DB_PASSWORD:}
|
||||
|
||||
# 항상 schema_initial.sql, data.sql 실행
|
||||
spring.sql.init.mode=always
|
||||
spring.sql.init.schema-locations=classpath:schema_initial.sql
|
||||
|
||||
# ========================================
|
||||
# JPA/Hibernate 설정
|
||||
# ========================================
|
||||
@@ -32,7 +36,7 @@ spring.jpa.hibernate.ddl-auto=none
|
||||
spring.jpa.open-in-view=false
|
||||
spring.jpa.show-sql=false
|
||||
spring.jpa.properties.hibernate.format_sql=true
|
||||
spring.jpa.properties.hibernate.highlight_sql=true
|
||||
spring.jpa.properties.hibernate.highlight_sql=false
|
||||
spring.jpa.properties.hibernate.use_sql_comments=false
|
||||
|
||||
# 배치 처리 설정
|
||||
@@ -43,8 +47,9 @@ spring.jpa.properties.hibernate.order_updates=true
|
||||
|
||||
# 스키마 생성 설정
|
||||
spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
|
||||
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=ddl/schema.sql
|
||||
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=ddl/schema_entity.sql
|
||||
spring.jpa.properties.hibernate.hbm2ddl.schema-generation.script.append=false
|
||||
spring.jpa.properties.hibernate.hbm2ddl.charset_name=UTF-8
|
||||
|
||||
# ========================================
|
||||
# 로그 레벨 설정
|
||||
@@ -86,7 +91,6 @@ logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %m
|
||||
# P6Spy 설정 (SQL 로깅)
|
||||
# ========================================
|
||||
decorator.datasource.p6spy.enable-logging=true
|
||||
decorator.datasource.p6spy.log-format=%(sqlSingleLine)
|
||||
|
||||
# ========================================
|
||||
# JWT 설정
|
||||
@@ -111,10 +115,6 @@ springdoc.swagger-ui.disable-swagger-default-url=true
|
||||
springdoc.default-produces-media-type=application/json
|
||||
springdoc.default-consumes-media-type=application/json
|
||||
|
||||
# ========================================
|
||||
# 보안 설정 - 허용할 경로
|
||||
security.permit-all-paths=/login,/logout,/members/register,/swagger-ui/**,/swagger-ui.html,/swagger-ui/index.html,/api-docs,/api-docs/**,/v3/api-docs,/v3/api-docs/**,/ws/**,/actuator/**,/actuator/health/**,/actuator/info
|
||||
|
||||
# 파일 업로드 설정
|
||||
# ========================================
|
||||
spring.servlet.multipart.enabled=true
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<!-- 콘솔 출력 -->
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] [%X{traceId}] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<totalSizeCap>1GB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] [%X{traceId}] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
<totalSizeCap>500MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] [%X{traceId}] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
|
||||
7
src/main/resources/schema_initial.sql
Normal file
7
src/main/resources/schema_initial.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE IF NOT EXISTS shedlock (
|
||||
name varchar(64) NOT NULL,
|
||||
lock_until timestamptz(3) NOT NULL,
|
||||
locked_at timestamptz(3) NOT NULL,
|
||||
locked_by varchar(255) NOT NULL,
|
||||
CONSTRAINT shedlock_pkey PRIMARY KEY (name)
|
||||
);
|
||||
18
src/main/resources/spy.properties
Normal file
18
src/main/resources/spy.properties
Normal file
@@ -0,0 +1,18 @@
|
||||
##################################################################
|
||||
# P6Spy 기본 설정
|
||||
##################################################################
|
||||
appender=com.p6spy.engine.spy.appender.Slf4JLogger
|
||||
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
|
||||
logLevel=info
|
||||
|
||||
##################################################################
|
||||
# SQL 포맷
|
||||
##################################################################
|
||||
customLogMessageFormat=%(currentTime) | %(executionTime) ms | %(category) | connection %(connectionId) | %(sqlSingleLine)
|
||||
excludecategories=info,debug,result,commit,resultset
|
||||
|
||||
##################################################################
|
||||
# filter
|
||||
##################################################################
|
||||
filter=true
|
||||
executionThreshold=1
|
||||
Reference in New Issue
Block a user