Compare commits
	
		
			43 Commits
		
	
	
		
			kmbin92_20
			...
			f9472d1ccd
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| f9472d1ccd | |||
| 56c8893f9e | |||
| 690724c77c | |||
| b5d6d213f3 | |||
| e7105215b8 | |||
| d8fe8399f7 | |||
| 8cee267f36 | |||
| b1218ab9bb | |||
| 7ae5871ae0 | |||
| 1ce08cb981 | |||
| a4c14c69f0 | |||
| 9e7929da6b | |||
| f9cd84f740 | |||
| 224006b6cb | |||
| dbac9f4702 | |||
| 2a1f211159 | |||
| 
						 | 
					7430f1606f | ||
| 
						 | 
					1153f164fc | ||
| 
						 | 
					1850227d24 | ||
| 09e06cd10b | |||
| 6d1b89609b | |||
| baaa003d9a | |||
| d9d3be86a9 | |||
| 1b46b95ad5 | |||
| 8aa96d5fbd | |||
| 0dc32f2b39 | |||
| bfb87b8e33 | |||
| 
						 | 
					33b33ef7a3 | ||
| 
						 | 
					331d242ac3 | ||
| eff011f9fd | |||
| 
						 | 
					0f1c5443ea | ||
| baab0352d5 | |||
| 21f121c490 | |||
| 77bc400888 | |||
| d0612b61e9 | |||
| d1c82848a2 | |||
| b34636baae | |||
| a2c6c83ed7 | |||
| 6a4388f513 | |||
| 2ead0f0f12 | |||
| e0e868a282 | |||
| 
						 | 
					45f3aa0f2c | ||
| 74f8b65327 | 
							
								
								
									
										6
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										6
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							@@ -42,4 +42,8 @@ bin/
 | 
			
		||||
 | 
			
		||||
# Temporary files created by the OS
 | 
			
		||||
.DS_Store
 | 
			
		||||
Thumbs.db
 | 
			
		||||
Thumbs.db
 | 
			
		||||
/nginx-1.28.0/logs/nginx.pid
 | 
			
		||||
 | 
			
		||||
# Upload files
 | 
			
		||||
uploads/
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										289
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										289
									
								
								README.md
									
									
									
									
									
								
							@@ -8,6 +8,7 @@
 | 
			
		||||
- **Security**: Spring Security + JWT
 | 
			
		||||
- **Build Tool**: Gradle
 | 
			
		||||
- **Container**: Docker + Kubernetes
 | 
			
		||||
- **API Documentation**: Swagger (SpringDoc OpenAPI)
 | 
			
		||||
 | 
			
		||||
## 개발 가이드
 | 
			
		||||
 | 
			
		||||
@@ -16,22 +17,172 @@
 | 
			
		||||
```
 | 
			
		||||
src/main/java/com/bio/bio_backend/
 | 
			
		||||
├── domain/                    # 도메인별 패키지
 | 
			
		||||
│   └── user/
 | 
			
		||||
│   └── base/                 # 기본 도메인
 | 
			
		||||
│       └── member/           # 회원 도메인
 | 
			
		||||
│           ├── controller/    # API 엔드포인트
 | 
			
		||||
│           ├── service/       # 비즈니스 로직
 | 
			
		||||
│           ├── repository/    # 데이터 접근
 | 
			
		||||
│           ├── entity/        # JPA 엔티티
 | 
			
		||||
│           └── dto/          # 데이터 전송 객체
 | 
			
		||||
│           ├── dto/          # 데이터 전송 객체
 | 
			
		||||
│           ├── mapper/       # MapStruct 매퍼
 | 
			
		||||
│           └── enums/        # 도메인 열거형
 | 
			
		||||
├── global/                    # 공통 설정
 | 
			
		||||
│   ├── config/               # 설정 클래스
 | 
			
		||||
│   ├── security/             # 보안 설정
 | 
			
		||||
│   ├── exception/            # 예외 처리
 | 
			
		||||
│   └── utils/                # 유틸리티
 | 
			
		||||
└── BioBackendApplication.java
 | 
			
		||||
│   ├── aop/                  # AOP 로깅
 | 
			
		||||
│   ├── filter/               # HTTP 로깅 필터
 | 
			
		||||
│   ├── utils/                # 유틸리티
 | 
			
		||||
│   ├── constants/            # 상수 정의
 | 
			
		||||
│   ├── dto/                  # 공통 DTO
 | 
			
		||||
│   ├── entity/               # 공통 엔티티
 | 
			
		||||
│   └── annotation/           # 커스텀 어노테이션
 | 
			
		||||
├── BioBackendApplication.java
 | 
			
		||||
└── ServletInitializer.java
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
### 2. 트랜잭션 관리
 | 
			
		||||
### 2. API 응답 표준화 (ApiResponseDto)
 | 
			
		||||
 | 
			
		||||
#### 응답 구조
 | 
			
		||||
 | 
			
		||||
모든 API 응답은 `ApiResponseDto<T>` 형태로 표준화되어 있습니다.
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
public class ApiResponseDto<T> {
 | 
			
		||||
    private int code;           // HTTP 상태 코드
 | 
			
		||||
    private String message;     // 응답 메시지 (ApiResponseCode enum 값)
 | 
			
		||||
    private String description; // 응답 설명
 | 
			
		||||
    private T data;            // 실제 데이터 (제네릭 타입)
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
#### 응답 예시
 | 
			
		||||
 | 
			
		||||
**성공 응답 (201 Created)**
 | 
			
		||||
 | 
			
		||||
```json
 | 
			
		||||
{
 | 
			
		||||
  "code": 201,
 | 
			
		||||
  "message": "COMMON_SUCCESS_CREATED",
 | 
			
		||||
  "description": "Created successfully",
 | 
			
		||||
  "data": {
 | 
			
		||||
    "seq": 1,
 | 
			
		||||
    "userId": "user123",
 | 
			
		||||
    "name": "홍길동"
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
**실패 응답 (409 Conflict)**
 | 
			
		||||
 | 
			
		||||
```json
 | 
			
		||||
{
 | 
			
		||||
  "code": 409,
 | 
			
		||||
  "message": "USER_ID_DUPLICATE",
 | 
			
		||||
  "description": "User ID already exists"
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
#### 사용 방법
 | 
			
		||||
 | 
			
		||||
**Controller에서 응답 생성**
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
@PostMapping("/members")
 | 
			
		||||
public ResponseEntity<ApiResponseDto<CreateMemberResponseDto>> createMember(@RequestBody CreateMemberRequestDto requestDto) {
 | 
			
		||||
    // ... 비즈니스 로직 ...
 | 
			
		||||
 | 
			
		||||
    // 성공 응답
 | 
			
		||||
    ApiResponseDto<CreateMemberResponseDto> apiResponse =
 | 
			
		||||
        ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS_CREATED, responseDto);
 | 
			
		||||
 | 
			
		||||
    return ResponseEntity.status(HttpStatus.CREATED).body(apiResponse);
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
**공용 응답 코드 사용**
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
// ApiResponseCode.java
 | 
			
		||||
public enum ApiResponseCode {
 | 
			
		||||
    // 공용 성공 코드
 | 
			
		||||
    COMMON_SUCCESS(HttpStatus.OK.value(), "요청 성공"),
 | 
			
		||||
    COMMON_SUCCESS_CREATED(HttpStatus.CREATED.value(), "성공적으로 생성되었습니다"),
 | 
			
		||||
    COMMON_SUCCESS_UPDATED(HttpStatus.OK.value(), "성공적으로 수정되었습니다"),
 | 
			
		||||
    COMMON_SUCCESS_DELETED(HttpStatus.OK.value(), "성공적으로 삭제되었습니다"),
 | 
			
		||||
    COMMON_SUCCESS_RETRIEVED(HttpStatus.OK.value(), "성공적으로 조회되었습니다"),
 | 
			
		||||
 | 
			
		||||
    // 공용 오류 코드
 | 
			
		||||
    COMMON_BAD_REQUEST(HttpStatus.BAD_REQUEST.value(), "필수 요청 본문이 누락되었거나 오류가 발생했습니다"),
 | 
			
		||||
    COMMON_UNAUTHORIZED(HttpStatus.UNAUTHORIZED.value(), "인증에 실패했습니다"),
 | 
			
		||||
    COMMON_FORBIDDEN(HttpStatus.FORBIDDEN.value(), "접근이 거부되었습니다"),
 | 
			
		||||
    COMMON_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "리소스를 찾을 수 없습니다"),
 | 
			
		||||
    COMMON_CONFLICT(HttpStatus.CONFLICT.value(), "충돌이 발생했습니다"),
 | 
			
		||||
    COMMON_INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "서버에서 오류가 발생했습니다"),
 | 
			
		||||
 | 
			
		||||
    // 사용자 관련 코드
 | 
			
		||||
    USER_ID_DUPLICATE(HttpStatus.CONFLICT.value(), "이미 존재하는 사용자 ID입니다"),
 | 
			
		||||
    USER_NOT_FOUND(HttpStatus.UNAUTHORIZED.value(), "사용자를 찾을 수 없습니다. 인증에 실패했습니다"),
 | 
			
		||||
    USER_PASSWORD_INVALID(HttpStatus.UNAUTHORIZED.value(), "비밀번호가 올바르지 않습니다")
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
#### 핵심 규칙
 | 
			
		||||
 | 
			
		||||
- **모든 API 응답**: `ApiResponseDto<T>`로 감싸서 반환
 | 
			
		||||
- **공용 응답 코드**: `COMMON_` 접두사로 시작하는 범용 코드 사용
 | 
			
		||||
- **일관된 구조**: `code`, `message`, `description`, `data` 필드로 표준화
 | 
			
		||||
- **제네릭 활용**: `<T>`를 통해 다양한 데이터 타입 지원
 | 
			
		||||
 | 
			
		||||
### 3. JWT 인증 시스템
 | 
			
		||||
 | 
			
		||||
#### 토큰 구성
 | 
			
		||||
 | 
			
		||||
- **Access Token**: 15분 (900,000ms) - API 요청 시 사용
 | 
			
		||||
- **Refresh Token**: 7일 (604,800,000ms) - 쿠키에 저장, 자동 갱신
 | 
			
		||||
 | 
			
		||||
#### 자동 토큰 갱신
 | 
			
		||||
 | 
			
		||||
**모든 API 요청마다 자동으로 처리됩니다:**
 | 
			
		||||
 | 
			
		||||
1. **Access Token 유효**: 정상 요청 처리
 | 
			
		||||
2. **Access Token 만료**: Refresh Token으로 자동 갱신
 | 
			
		||||
3. **새 Access Token 발급**: 응답 헤더에 자동 설정
 | 
			
		||||
4. **Refresh Token 갱신**: 보안을 위해 매번 새로운 토큰 발급
 | 
			
		||||
 | 
			
		||||
#### 주요 컴포넌트
 | 
			
		||||
 | 
			
		||||
- **`JwtTokenIssuanceFilter`**: 로그인 시 토큰 발급
 | 
			
		||||
- **`JwtTokenValidationFilter`**: 요청마다 토큰 검증 및 갱신
 | 
			
		||||
- **`JwtUtils`**: 토큰 생성, 검증, 갱신 유틸리티
 | 
			
		||||
 | 
			
		||||
### 4. API 문서화 (Swagger)
 | 
			
		||||
 | 
			
		||||
#### Swagger UI 접속
 | 
			
		||||
 | 
			
		||||
- **URL**: `http://localhost:8080/service/swagger-ui.html`
 | 
			
		||||
- **API Docs**: `http://localhost:8080/service/api-docs`
 | 
			
		||||
 | 
			
		||||
#### 주요 어노테이션
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
@Tag(name = "Member", description = "회원 관리 API")
 | 
			
		||||
@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)))
 | 
			
		||||
})
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
#### 설정 파일
 | 
			
		||||
 | 
			
		||||
- **SwaggerConfig.java**: OpenAPI 기본 정보 설정
 | 
			
		||||
- **application.properties**: Swagger UI 커스터마이징
 | 
			
		||||
 | 
			
		||||
### 5. 트랜잭션 관리
 | 
			
		||||
 | 
			
		||||
#### 기본 설정
 | 
			
		||||
 | 
			
		||||
@@ -54,3 +205,131 @@ public class MemberServiceImpl {
 | 
			
		||||
- **클래스 레벨**: `@Transactional(readOnly = true)` 기본 설정
 | 
			
		||||
- **메서드별**: 데이터 수정 시에만 `@Transactional` 개별 적용
 | 
			
		||||
- **설정**: `spring.jpa.open-in-view=false` (성능 최적화)
 | 
			
		||||
 | 
			
		||||
### 6. 오류 등록 및 사용
 | 
			
		||||
 | 
			
		||||
#### 오류 코드 등록
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
// ApiResponseCode.java
 | 
			
		||||
public enum ApiResponseCode {
 | 
			
		||||
    USER_ID_DUPLICATE(HttpStatus.CONFLICT.value(), "User ID already exists"),
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
#### 오류 사용 방법
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
// Service에서 예외 발생
 | 
			
		||||
throw new ApiException(ApiResponseCode.USER_ID_DUPLICATE);
 | 
			
		||||
 | 
			
		||||
// Controller에서 예외 처리 (자동)
 | 
			
		||||
// GlobalExceptionHandler가 ApiException을 잡아서 응답 변환
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
#### 핵심 규칙
 | 
			
		||||
 | 
			
		||||
- **오류 코드**: `ApiResponseCode` enum에 모든 오류 정의
 | 
			
		||||
- **예외 클래스**: `ApiException`으로 비즈니스 로직 예외 처리
 | 
			
		||||
- **자동 처리**: `GlobalExceptionHandler`가 일관된 응답 형태로 변환
 | 
			
		||||
 | 
			
		||||
### 7. 로깅 시스템
 | 
			
		||||
 | 
			
		||||
#### @LogExecution 어노테이션 사용법
 | 
			
		||||
 | 
			
		||||
**메서드 실행 로깅을 위한 필수 어노테이션입니다.**
 | 
			
		||||
 | 
			
		||||
##### 기본 사용법
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
@LogExecution("회원 등록")
 | 
			
		||||
@PostMapping("/register")
 | 
			
		||||
public ResponseEntity<ApiResponseDto<CreateMemberResponseDto>> createMember(@RequestBody CreateMemberRequestDto requestDto) {
 | 
			
		||||
    // 메서드 실행 시 자동으로 로그 출력
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
##### 로그 출력 예시
 | 
			
		||||
 | 
			
		||||
**메서드 시작 시:**
 | 
			
		||||
 | 
			
		||||
```
 | 
			
		||||
[START] 회원 등록 | 호출경로: MemberController.createMember | 사용자: 고명빈(kmbin92)
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
**메서드 성공 시:**
 | 
			
		||||
 | 
			
		||||
```
 | 
			
		||||
[SUCCESS] 회원 등록 | 호출경로: MemberController.createMember | 사용자: 고명빈(kmbin92) | 시간: 200ms
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
**메서드 실패 시:**
 | 
			
		||||
 | 
			
		||||
```
 | 
			
		||||
[FAILED] 회원 등록 | 호출경로: MemberController.createMember | 사용자: 고명빈(kmbin92) | 시간: 23ms | 오류: 이미 존재하는 사용자 ID입니다
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
##### 어노테이션 설정
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
@LogExecution("사용자 정보 조회")
 | 
			
		||||
public UserDto getUserInfo() { }
 | 
			
		||||
 | 
			
		||||
@LogExecution("주문 처리")
 | 
			
		||||
public OrderDto processOrder() { }
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
##### 로깅 시스템 구성
 | 
			
		||||
 | 
			
		||||
1. **MethodExecutionLoggingAspect**: 메서드 실행 로깅 (AOP)
 | 
			
		||||
2. **HttpLoggingFilter**: HTTP 요청/응답 로깅 (필터)
 | 
			
		||||
3. **logback-spring.xml**: 로그 파일 관리 및 설정
 | 
			
		||||
 | 
			
		||||
**중요**: `@LogExecution` 어노테이션이 없으면 메서드 실행 로그가 출력되지 않습니다
 | 
			
		||||
 | 
			
		||||
### 8. MapStruct
 | 
			
		||||
 | 
			
		||||
**매퍼 인터페이스**
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
@Mapper(componentModel = "spring")
 | 
			
		||||
public interface MemberMapper {
 | 
			
		||||
    MemberDto toDto(Member member);
 | 
			
		||||
    Member toEntity(MemberDto dto);
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
**사용 예시**
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
// Entity → DTO
 | 
			
		||||
MemberDto dto = memberMapper.toDto(member);
 | 
			
		||||
 | 
			
		||||
// DTO → Entity
 | 
			
		||||
Member entity = memberMapper.toEntity(dto);
 | 
			
		||||
```
 | 
			
		||||
 | 
			
		||||
**자동 생성**: 컴파일 시 `MemberMapperImpl` 구현체 생성
 | 
			
		||||
 | 
			
		||||
### 9. BaseEntity 상속
 | 
			
		||||
 | 
			
		||||
**모든 엔티티는 `BaseEntity` 상속을 원칙으로 합니다.**
 | 
			
		||||
 | 
			
		||||
#### 자동 생성 필드
 | 
			
		||||
 | 
			
		||||
- **OID**: `@PrePersist`에서 자동 생성 (고유 식별자)
 | 
			
		||||
- **생성일시**: `@CreatedDate`로 자동 설정
 | 
			
		||||
- **수정일시**: `@LastModifiedDate`로 자동 갱신
 | 
			
		||||
- **생성자/수정자 OID**: 사용자 추적용
 | 
			
		||||
 | 
			
		||||
#### 사용 예시
 | 
			
		||||
 | 
			
		||||
```java
 | 
			
		||||
@Entity
 | 
			
		||||
@Table(name = "st_members")
 | 
			
		||||
public class Member extends BaseEntity {
 | 
			
		||||
    // OID, 생성일시, 수정일시 등이 자동으로 관리됨
 | 
			
		||||
    private String userId;
 | 
			
		||||
    private String name;
 | 
			
		||||
}
 | 
			
		||||
```
 | 
			
		||||
 
 | 
			
		||||
@@ -26,6 +26,7 @@ repositories {
 | 
			
		||||
dependencies {
 | 
			
		||||
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
 | 
			
		||||
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
 | 
			
		||||
 | 
			
		||||
	// PostgreSQL JDBC
 | 
			
		||||
    runtimeOnly 'org.postgresql:postgresql'
 | 
			
		||||
	implementation 'org.springframework.boot:spring-boot-starter-web'
 | 
			
		||||
@@ -45,6 +46,8 @@ dependencies {
 | 
			
		||||
 | 
			
		||||
	// jwt
 | 
			
		||||
	implementation 'io.jsonwebtoken:jjwt-api:0.12.5'
 | 
			
		||||
	runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.5'
 | 
			
		||||
	runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.5'
 | 
			
		||||
 | 
			
		||||
	// lombok
 | 
			
		||||
	compileOnly 'org.projectlombok:lombok'
 | 
			
		||||
@@ -61,6 +64,9 @@ dependencies {
 | 
			
		||||
 | 
			
		||||
	// p6spy
 | 
			
		||||
	implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.9.0'
 | 
			
		||||
	
 | 
			
		||||
	// SpringDoc OpenAPI (Swagger)
 | 
			
		||||
	implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.9'
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
tasks.named('test') {
 | 
			
		||||
 
 | 
			
		||||
@@ -1,4 +1,23 @@
 | 
			
		||||
 | 
			
		||||
    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)
 | 
			
		||||
    );
 | 
			
		||||
 | 
			
		||||
    create table st_member (
 | 
			
		||||
        use_flag boolean not null,
 | 
			
		||||
        created_at timestamp(6) not null,
 | 
			
		||||
@@ -7,10 +26,15 @@
 | 
			
		||||
        oid bigint not null,
 | 
			
		||||
        updated_at timestamp(6) not null,
 | 
			
		||||
        updated_oid bigint,
 | 
			
		||||
        role varchar(40) not null check (role in ('MEMBER','ADMIN','USER','SYSTEM_ADMIN')),
 | 
			
		||||
        role varchar(40) not null check (role in ('MEMBER','ADMIN','SYSTEM_ADMIN')),
 | 
			
		||||
        login_ip varchar(45),
 | 
			
		||||
        name varchar(100) not null,
 | 
			
		||||
        password varchar(100) not null,
 | 
			
		||||
        user_id varchar(100) not null,
 | 
			
		||||
        refresh_token varchar(200),
 | 
			
		||||
        refresh_token varchar(1024),
 | 
			
		||||
        created_id varchar(255),
 | 
			
		||||
        email varchar(255) not null,
 | 
			
		||||
        updated_id varchar(255),
 | 
			
		||||
        primary key (oid)
 | 
			
		||||
    );
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
@@ -1,38 +1,49 @@
 | 
			
		||||
# ./nginx/nginx.conf
 | 
			
		||||
 | 
			
		||||
# 이벤트 블록은 Nginx가 어떻게 연결을 처리할지 정의합니다.
 | 
			
		||||
events {
 | 
			
		||||
    worker_connections 1024;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
# HTTP 블록은 웹 서버의 동작을 정의합니다.
 | 
			
		||||
http {
 | 
			
		||||
    # MIME 타입 파일을 포함하여 파일 확장자에 따라 콘텐츠 타입을 결정합니다.
 | 
			
		||||
    include /etc/nginx/mime.types;
 | 
			
		||||
 | 
			
		||||
    # 기본 서버 설정을 정의합니다.
 | 
			
		||||
    include mime.types;
 | 
			
		||||
    default_type application/octet-stream;
 | 
			
		||||
    sendfile on;
 | 
			
		||||
    keepalive_timeout 65;
 | 
			
		||||
 | 
			
		||||
    # (선택) 로그 위치
 | 
			
		||||
    access_log logs/access.log;
 | 
			
		||||
    error_log  logs/error.log warn;
 | 
			
		||||
 | 
			
		||||
    # 웹소켓용
 | 
			
		||||
    map $http_upgrade $connection_upgrade {
 | 
			
		||||
        default upgrade;
 | 
			
		||||
        ''      close;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    server {
 | 
			
		||||
        # 80번 포트에서 요청을 받습니다.
 | 
			
		||||
        listen 80;
 | 
			
		||||
        server_name localhost; # 서버 이름을 localhost로 설정
 | 
			
		||||
        server_name localhost;
 | 
			
		||||
 | 
			
		||||
        # 루트 경로(/)로 들어오는 모든 요청을 처리합니다.
 | 
			
		||||
        # Nuxt(개발서버 3000)
 | 
			
		||||
        location / {
 | 
			
		||||
            # 요청을 다른 서버(여기서는 Nuxt.js)로 전달합니다.
 | 
			
		||||
            proxy_pass http://localhost: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 Upgrade $http_upgrade;
 | 
			
		||||
            proxy_set_header Connection $connection_upgrade;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
            # 프록시 헤더를 설정하여 원본 요청 정보를 유지합니다.
 | 
			
		||||
        # Spring Boot(8080) — /service 접두어 제거
 | 
			
		||||
        location /service/ {
 | 
			
		||||
            proxy_pass http://localhost:8080;  # 끝에 슬래시 넣으면 /service가 제거됨
 | 
			
		||||
            proxy_set_header Host $host;
 | 
			
		||||
            proxy_set_header X-Real-IP $remote_addr;
 | 
			
		||||
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        # /api/ 경로로 들어오는 요청을 처리합니다. (Spring Boot 컨테이너를 가리킨다고 가정)
 | 
			
		||||
        location /service {
 | 
			
		||||
            proxy_pass http://localhost: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;
 | 
			
		||||
        }
 | 
			
		||||
        # (선택) 업로드 크게 받을 때
 | 
			
		||||
        # client_max_body_size 50m;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										0
									
								
								nginx-1.28.0/logs/.gitkeep
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								nginx-1.28.0/logs/.gitkeep
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										0
									
								
								nginx-1.28.0/temp/.gitkeep
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								nginx-1.28.0/temp/.gitkeep
									
									
									
									
									
										Normal file
									
								
							@@ -2,10 +2,12 @@ package com.bio.bio_backend;
 | 
			
		||||
 | 
			
		||||
import org.springframework.boot.SpringApplication;
 | 
			
		||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
 | 
			
		||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
 | 
			
		||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
 | 
			
		||||
 | 
			
		||||
@SpringBootApplication
 | 
			
		||||
@EnableJpaAuditing
 | 
			
		||||
@EnableConfigurationProperties
 | 
			
		||||
public class BioBackendApplication {
 | 
			
		||||
 | 
			
		||||
	public static void main(String[] args) {
 | 
			
		||||
 
 | 
			
		||||
@@ -0,0 +1,101 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.controller;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.FileUploadRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.FileUploadResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.MultipleFileUploadRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.MultipleFileUploadResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.service.FileService;
 | 
			
		||||
import com.bio.bio_backend.global.dto.ApiResponseDto;
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.global.annotation.LogExecution;
 | 
			
		||||
import com.bio.bio_backend.global.utils.FileUtils;
 | 
			
		||||
import io.swagger.v3.oas.annotations.Operation;
 | 
			
		||||
import io.swagger.v3.oas.annotations.tags.Tag;
 | 
			
		||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
 | 
			
		||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
 | 
			
		||||
import io.swagger.v3.oas.annotations.media.Content;
 | 
			
		||||
import io.swagger.v3.oas.annotations.media.Schema;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.springframework.core.io.ByteArrayResource;
 | 
			
		||||
import org.springframework.http.HttpHeaders;
 | 
			
		||||
import org.springframework.http.ResponseEntity;
 | 
			
		||||
import org.springframework.web.bind.annotation.*;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.entity.File;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@Tag(name = "File", description = "파일 업로드/다운로드 API")
 | 
			
		||||
@RestController
 | 
			
		||||
@RequestMapping("/files")
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class FileController {
 | 
			
		||||
 | 
			
		||||
    private final FileService fileService;
 | 
			
		||||
    
 | 
			
		||||
    @LogExecution("파일 업로드")
 | 
			
		||||
    @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)))
 | 
			
		||||
    })
 | 
			
		||||
    @PostMapping("/upload")
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<FileUploadResponseDto>> uploadFile(
 | 
			
		||||
            @ModelAttribute FileUploadRequestDto requestDto) {
 | 
			
		||||
        
 | 
			
		||||
        FileUploadResponseDto responseDto = fileService.uploadFile(requestDto);
 | 
			
		||||
        
 | 
			
		||||
        return ResponseEntity.ok(ApiResponseDto.success(ApiResponseCode.FILE_UPLOAD_SUCCESS, responseDto));
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @LogExecution("다중 파일 업로드")
 | 
			
		||||
    @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)))
 | 
			
		||||
    })
 | 
			
		||||
    @PostMapping("/upload-multiple")
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<MultipleFileUploadResponseDto>> uploadMultipleFiles(
 | 
			
		||||
            @ModelAttribute MultipleFileUploadRequestDto requestDto) {
 | 
			
		||||
        
 | 
			
		||||
        MultipleFileUploadResponseDto responseDto = fileService.uploadMultipleFiles(requestDto);
 | 
			
		||||
        
 | 
			
		||||
        return ResponseEntity.ok(ApiResponseDto.success(ApiResponseCode.FILE_UPLOAD_SUCCESS, responseDto));
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @LogExecution("파일 다운로드")
 | 
			
		||||
    @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)))
 | 
			
		||||
    })
 | 
			
		||||
    @GetMapping("/download/{oid}")
 | 
			
		||||
    public ResponseEntity<ByteArrayResource> downloadFile(@PathVariable Long oid) {
 | 
			
		||||
        // 파일 정보 먼저 조회
 | 
			
		||||
        File file = fileService.getFileByOid(oid);
 | 
			
		||||
        byte[] fileData = fileService.downloadFile(oid);
 | 
			
		||||
        ByteArrayResource resource = new ByteArrayResource(fileData);
 | 
			
		||||
        
 | 
			
		||||
        return ResponseEntity.ok()
 | 
			
		||||
                .header(HttpHeaders.CONTENT_DISPOSITION, 
 | 
			
		||||
                    "attachment; filename=\"" + file.getOriginalFileName() + "\"")
 | 
			
		||||
                .header(HttpHeaders.CONTENT_TYPE, file.getContentType())
 | 
			
		||||
                .body(resource);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @LogExecution("파일 논리적 삭제")
 | 
			
		||||
    @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)))
 | 
			
		||||
    })
 | 
			
		||||
    @DeleteMapping("/{oid}")
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<Void>> deleteFile(@PathVariable Long oid) {
 | 
			
		||||
        fileService.deleteFile(oid);
 | 
			
		||||
        return ResponseEntity.ok(ApiResponseDto.success(ApiResponseCode.FILE_DELETE_SUCCESS));
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,11 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.dto;
 | 
			
		||||
 | 
			
		||||
import lombok.Data;
 | 
			
		||||
import org.springframework.web.multipart.MultipartFile;
 | 
			
		||||
 | 
			
		||||
@Data
 | 
			
		||||
public class FileUploadRequestDto {
 | 
			
		||||
    private MultipartFile file;
 | 
			
		||||
    private String description;
 | 
			
		||||
    private Long groupOid;
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,12 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.dto;
 | 
			
		||||
 | 
			
		||||
import lombok.Builder;
 | 
			
		||||
import lombok.Data;
 | 
			
		||||
 | 
			
		||||
@Data
 | 
			
		||||
@Builder
 | 
			
		||||
public class FileUploadResponseDto {
 | 
			
		||||
    private Long oid;
 | 
			
		||||
    private String originalFileName;
 | 
			
		||||
    private String downloadUrl;
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,11 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.dto;
 | 
			
		||||
 | 
			
		||||
import lombok.Data;
 | 
			
		||||
import org.springframework.web.multipart.MultipartFile;
 | 
			
		||||
import java.util.List;
 | 
			
		||||
 | 
			
		||||
@Data
 | 
			
		||||
public class MultipleFileUploadRequestDto {
 | 
			
		||||
    private List<MultipartFile> files;
 | 
			
		||||
    private String description;
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,15 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.dto;
 | 
			
		||||
 | 
			
		||||
import lombok.Builder;
 | 
			
		||||
import lombok.Data;
 | 
			
		||||
import java.util.List;
 | 
			
		||||
 | 
			
		||||
@Data
 | 
			
		||||
@Builder
 | 
			
		||||
public class MultipleFileUploadResponseDto {
 | 
			
		||||
    private List<FileUploadResponseDto> files;
 | 
			
		||||
    private int totalCount;
 | 
			
		||||
    private int successCount;
 | 
			
		||||
    private int failureCount;
 | 
			
		||||
    private List<String> errorMessages;
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,41 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.entity;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.global.constants.AppConstants;
 | 
			
		||||
import com.bio.bio_backend.global.entity.BaseEntity;
 | 
			
		||||
import jakarta.persistence.*;
 | 
			
		||||
import lombok.*;
 | 
			
		||||
 | 
			
		||||
@Entity
 | 
			
		||||
@Table(name = AppConstants.TABLE_PREFIX + "file")
 | 
			
		||||
@Getter
 | 
			
		||||
@Setter
 | 
			
		||||
@NoArgsConstructor
 | 
			
		||||
@AllArgsConstructor
 | 
			
		||||
@Builder
 | 
			
		||||
public class File extends BaseEntity {
 | 
			
		||||
    
 | 
			
		||||
    @Column(nullable = false)
 | 
			
		||||
    private String originalFileName;
 | 
			
		||||
    
 | 
			
		||||
    @Column(nullable = false)
 | 
			
		||||
    private String storedFileName;
 | 
			
		||||
    
 | 
			
		||||
    @Column(nullable = false)
 | 
			
		||||
    private String filePath;
 | 
			
		||||
    
 | 
			
		||||
    @Column(nullable = false)
 | 
			
		||||
    private Long fileSize;
 | 
			
		||||
    
 | 
			
		||||
    @Column(nullable = false)
 | 
			
		||||
    private String contentType;
 | 
			
		||||
    
 | 
			
		||||
    @Column
 | 
			
		||||
    private String description;
 | 
			
		||||
    
 | 
			
		||||
    @Column
 | 
			
		||||
    private Long groupOid;
 | 
			
		||||
    
 | 
			
		||||
    @Column(nullable = false)
 | 
			
		||||
    @Builder.Default
 | 
			
		||||
    private Boolean useFlag = true;
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,20 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.repository;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.entity.File;
 | 
			
		||||
import org.springframework.data.jpa.repository.JpaRepository;
 | 
			
		||||
import org.springframework.data.jpa.repository.Query;
 | 
			
		||||
import org.springframework.stereotype.Repository;
 | 
			
		||||
 | 
			
		||||
import java.util.List;
 | 
			
		||||
import java.util.Optional;
 | 
			
		||||
 | 
			
		||||
@Repository
 | 
			
		||||
public interface FileRepository extends JpaRepository<File, Long> {
 | 
			
		||||
    
 | 
			
		||||
    // use_flag가 true인 파일만 조회
 | 
			
		||||
    Optional<File> findByOidAndUseFlagTrue(Long id);
 | 
			
		||||
    
 | 
			
		||||
    // use_flag가 true인 파일만 조회 (List 형태로 필요시 사용)
 | 
			
		||||
    @Query("SELECT f FROM File f WHERE f.useFlag = true")
 | 
			
		||||
    List<File> findAllActiveFiles();
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,15 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.service;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.FileUploadRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.FileUploadResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.MultipleFileUploadRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.MultipleFileUploadResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.entity.File;
 | 
			
		||||
 | 
			
		||||
public interface FileService {
 | 
			
		||||
    FileUploadResponseDto uploadFile(FileUploadRequestDto requestDto);
 | 
			
		||||
    MultipleFileUploadResponseDto uploadMultipleFiles(MultipleFileUploadRequestDto requestDto);
 | 
			
		||||
    File getFileByOid(Long oid);
 | 
			
		||||
    byte[] downloadFile(Long oid);
 | 
			
		||||
    void deleteFile(Long oid); // 논리적 삭제 (use_flag를 false로 변경)
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,211 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.file.service;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.FileUploadRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.FileUploadResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.MultipleFileUploadRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.dto.MultipleFileUploadResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.entity.File;
 | 
			
		||||
import com.bio.bio_backend.domain.base.file.repository.FileRepository;
 | 
			
		||||
import com.bio.bio_backend.global.exception.ApiException;
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.global.utils.FileUtils;
 | 
			
		||||
import com.bio.bio_backend.global.utils.OidUtils;
 | 
			
		||||
import com.bio.bio_backend.global.utils.SecurityUtils;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.springframework.beans.factory.annotation.Value;
 | 
			
		||||
import org.springframework.stereotype.Service;
 | 
			
		||||
import org.springframework.transaction.annotation.Transactional;
 | 
			
		||||
import org.springframework.web.multipart.MultipartFile;
 | 
			
		||||
 | 
			
		||||
import java.io.IOException;
 | 
			
		||||
import java.nio.file.Files;
 | 
			
		||||
import java.nio.file.Path;
 | 
			
		||||
import java.nio.file.Paths;
 | 
			
		||||
import java.util.ArrayList;
 | 
			
		||||
import java.util.List;
 | 
			
		||||
 | 
			
		||||
import static com.bio.bio_backend.global.utils.OidUtils.generateOid;
 | 
			
		||||
 | 
			
		||||
@Service
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
@Transactional(readOnly = true)
 | 
			
		||||
public class FileServiceImpl implements FileService {
 | 
			
		||||
 | 
			
		||||
    private final FileRepository fileRepository;
 | 
			
		||||
    
 | 
			
		||||
    @Value("${app.file.upload.path}")
 | 
			
		||||
    private String uploadPath;
 | 
			
		||||
    
 | 
			
		||||
    @Value("${server.servlet.context-path}")
 | 
			
		||||
    private String contextPath;
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public FileUploadResponseDto uploadFile(FileUploadRequestDto requestDto) {
 | 
			
		||||
        MultipartFile multipartFile = requestDto.getFile();
 | 
			
		||||
        
 | 
			
		||||
        try {
 | 
			
		||||
            // 파일 유효성 검사
 | 
			
		||||
            FileUtils.validateFile(multipartFile);
 | 
			
		||||
        } catch (IllegalArgumentException e) {
 | 
			
		||||
            throw new ApiException(ApiResponseCode.FILE_EMPTY);
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        // 파일 업로드 처리
 | 
			
		||||
        File savedFile = processFileUpload(multipartFile, requestDto.getDescription(), generateOid());
 | 
			
		||||
        
 | 
			
		||||
        // 응답 DTO 생성 및 반환
 | 
			
		||||
        return createUploadResponse(savedFile);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public MultipleFileUploadResponseDto uploadMultipleFiles(MultipleFileUploadRequestDto requestDto) {
 | 
			
		||||
        List<MultipartFile> files = requestDto.getFiles();
 | 
			
		||||
        
 | 
			
		||||
        try {
 | 
			
		||||
            // 파일 리스트 유효성 검사
 | 
			
		||||
            FileUtils.validateFileList(files);
 | 
			
		||||
        } catch (IllegalArgumentException e) {
 | 
			
		||||
            throw new ApiException(ApiResponseCode.FILE_EMPTY);
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        List<FileUploadResponseDto> uploadedFiles = new ArrayList<>();
 | 
			
		||||
        List<String> errorMessages = new ArrayList<>();
 | 
			
		||||
        int successCount = 0;
 | 
			
		||||
        int failureCount = 0;
 | 
			
		||||
 | 
			
		||||
        Long groupOid = generateOid();
 | 
			
		||||
        for (MultipartFile multipartFile : files) {
 | 
			
		||||
            try {
 | 
			
		||||
                // 개별 파일 유효성 검사
 | 
			
		||||
                if (multipartFile.isEmpty()) {
 | 
			
		||||
                    String errorMsg = "파일 '" + multipartFile.getOriginalFilename() + "'이 비어있습니다.";
 | 
			
		||||
                    errorMessages.add(errorMsg);
 | 
			
		||||
                    failureCount++;
 | 
			
		||||
                    continue;
 | 
			
		||||
                }
 | 
			
		||||
                
 | 
			
		||||
                // 단일 파일 업로드 처리
 | 
			
		||||
                File savedFile = processFileUpload(multipartFile, requestDto.getDescription(), groupOid);
 | 
			
		||||
                FileUploadResponseDto uploadedFile = createUploadResponse(savedFile);
 | 
			
		||||
                
 | 
			
		||||
                uploadedFiles.add(uploadedFile);
 | 
			
		||||
                successCount++;
 | 
			
		||||
                
 | 
			
		||||
                log.info("파일 업로드 성공: {}", multipartFile.getOriginalFilename());
 | 
			
		||||
                
 | 
			
		||||
            } catch (Exception ex) {
 | 
			
		||||
                String fileName = multipartFile.getOriginalFilename() != null ? multipartFile.getOriginalFilename() : "알 수 없는 파일";
 | 
			
		||||
                log.error("파일 업로드 실패: {}", fileName, ex);
 | 
			
		||||
                errorMessages.add("파일 '" + fileName + "' 업로드 실패: " + ex.getMessage());
 | 
			
		||||
                failureCount++;
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        // 다중 파일 업로드 결과 반환
 | 
			
		||||
        return MultipleFileUploadResponseDto.builder()
 | 
			
		||||
                .files(uploadedFiles)
 | 
			
		||||
                .totalCount(files.size())
 | 
			
		||||
                .successCount(successCount)
 | 
			
		||||
                .failureCount(failureCount)
 | 
			
		||||
                .errorMessages(errorMessages)
 | 
			
		||||
                .build();
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일 업로드 처리
 | 
			
		||||
     */
 | 
			
		||||
    private File processFileUpload(MultipartFile multipartFile, String description, Long groupOid) {
 | 
			
		||||
        String originalFileName = FileUtils.cleanFileName(multipartFile.getOriginalFilename());
 | 
			
		||||
        
 | 
			
		||||
        try {
 | 
			
		||||
            // 항상 년월일 기반으로 폴더 생성 (예: uploads/2024/01/15/)
 | 
			
		||||
            Path uploadDir = FileUtils.createYearMonthUploadDirectory(uploadPath);
 | 
			
		||||
            log.debug("년월 기반 폴더 사용: {}", uploadDir);
 | 
			
		||||
            
 | 
			
		||||
            // 파일명 및 확장자 처리
 | 
			
		||||
            String fileExtension = FileUtils.extractFileExtension(originalFileName);
 | 
			
		||||
            String storedFileName = FileUtils.generateUniqueFileName(fileExtension);
 | 
			
		||||
            
 | 
			
		||||
            // 파일 저장
 | 
			
		||||
            Path targetLocation = FileUtils.saveFileToDisk(multipartFile, uploadDir, storedFileName);
 | 
			
		||||
            
 | 
			
		||||
            // DB에 파일 정보 저장
 | 
			
		||||
            File file = createFileEntity(originalFileName, storedFileName, targetLocation, multipartFile, description, groupOid);
 | 
			
		||||
            file.setCreator(SecurityUtils.getCurrentUserOid(), SecurityUtils.getCurrentUserId());
 | 
			
		||||
            
 | 
			
		||||
            return fileRepository.save(file);
 | 
			
		||||
            
 | 
			
		||||
        } catch (IOException ex) {
 | 
			
		||||
            log.error("파일 업로드 실패: {}", originalFileName, ex);
 | 
			
		||||
            throw new ApiException(ApiResponseCode.FILE_UPLOAD_FAILED, ex);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private File createFileEntity(String originalFileName, String storedFileName, Path targetLocation, 
 | 
			
		||||
                                MultipartFile multipartFile, String description, Long groupOid) {
 | 
			
		||||
        return File.builder()
 | 
			
		||||
                .originalFileName(originalFileName)
 | 
			
		||||
                .storedFileName(storedFileName)
 | 
			
		||||
                .filePath(targetLocation.toString())
 | 
			
		||||
                .fileSize(multipartFile.getSize())
 | 
			
		||||
                .contentType(multipartFile.getContentType())
 | 
			
		||||
                .description(description)
 | 
			
		||||
                .groupOid(groupOid)
 | 
			
		||||
                .build();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private FileUploadResponseDto createUploadResponse(File savedFile) {
 | 
			
		||||
        return FileUploadResponseDto.builder()
 | 
			
		||||
                .oid(savedFile.getOid())
 | 
			
		||||
                .originalFileName(savedFile.getOriginalFileName())
 | 
			
		||||
                .downloadUrl(contextPath + "/files/download/" + savedFile.getOid())
 | 
			
		||||
                .build();
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    public File getFileByOid(Long oid) {
 | 
			
		||||
        return fileRepository.findByOidAndUseFlagTrue(oid)
 | 
			
		||||
                .orElseThrow(() -> new ApiException(ApiResponseCode.FILE_NOT_FOUND));
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    public byte[] downloadFile(Long oid) {
 | 
			
		||||
        File file = fileRepository.findByOidAndUseFlagTrue(oid)
 | 
			
		||||
                .orElseThrow(() -> new ApiException(ApiResponseCode.FILE_NOT_FOUND));
 | 
			
		||||
        
 | 
			
		||||
        try {
 | 
			
		||||
            Path filePath = Paths.get(file.getFilePath());
 | 
			
		||||
            return Files.readAllBytes(filePath);
 | 
			
		||||
        } catch (IOException ex) {
 | 
			
		||||
            log.error("파일 다운로드 실패: {}", file.getOriginalFileName(), ex);
 | 
			
		||||
            throw new ApiException(ApiResponseCode.FILE_DOWNLOAD_FAILED, ex);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public void deleteFile(Long oid) {
 | 
			
		||||
        File file = fileRepository.findByOidAndUseFlagTrue(oid)
 | 
			
		||||
                .orElseThrow(() -> new ApiException(ApiResponseCode.FILE_NOT_FOUND));
 | 
			
		||||
        
 | 
			
		||||
        Long currentUserOid = SecurityUtils.getCurrentUserOid();
 | 
			
		||||
        String currentUserId = SecurityUtils.getCurrentUserId();
 | 
			
		||||
        // 현재 사용자가 파일 소유자인지 확인
 | 
			
		||||
        if (currentUserId == null || !currentUserId.equals(file.getCreatedId())) {
 | 
			
		||||
            throw new ApiException(ApiResponseCode.COMMON_FORBIDDEN);
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        // 수정자 정보 업데이트
 | 
			
		||||
        file.setUpdater(currentUserOid, currentUserId);
 | 
			
		||||
        
 | 
			
		||||
        // 논리적 삭제: use_flag를 false로 변경
 | 
			
		||||
        file.setUseFlag(false);
 | 
			
		||||
        fileRepository.save(file);
 | 
			
		||||
        
 | 
			
		||||
        log.info("파일 논리적 삭제 완료: oid={}, fileName={}", oid, file.getOriginalFileName());
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,73 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.controller;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.global.dto.ApiResponseDto;
 | 
			
		||||
import io.swagger.v3.oas.annotations.tags.Tag;
 | 
			
		||||
import org.springframework.http.HttpStatus;
 | 
			
		||||
import org.springframework.http.ResponseEntity;
 | 
			
		||||
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.CreateMemberRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.dto.CreateMemberResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.service.MemberService;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.mapper.MemberMapper;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import io.swagger.v3.oas.annotations.Operation;
 | 
			
		||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
 | 
			
		||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
 | 
			
		||||
import io.swagger.v3.oas.annotations.media.Content;
 | 
			
		||||
import io.swagger.v3.oas.annotations.media.Schema;
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.global.annotation.LogExecution;
 | 
			
		||||
import com.bio.bio_backend.global.utils.SecurityUtils;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@Tag(name = "Member", description = "회원 관련 API")
 | 
			
		||||
@RestController
 | 
			
		||||
@RequestMapping("/members")
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class MemberController {
 | 
			
		||||
 | 
			
		||||
    private final MemberService memberService;
 | 
			
		||||
    private final MemberMapper memberMapper;
 | 
			
		||||
 | 
			
		||||
    @LogExecution("회원 등록")
 | 
			
		||||
    @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)))
 | 
			
		||||
    })
 | 
			
		||||
    @PostMapping("/register")
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<CreateMemberResponseDto>> createMember(@RequestBody @Valid CreateMemberRequestDto requestDto) {
 | 
			
		||||
        MemberDto createdMember = memberService.createMember(memberMapper.toMemberDto(requestDto));
 | 
			
		||||
        CreateMemberResponseDto responseDto = memberMapper.toCreateMemberResponseDto(createdMember);
 | 
			
		||||
        ApiResponseDto<CreateMemberResponseDto> apiResponse = ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS_CREATED, responseDto);
 | 
			
		||||
        
 | 
			
		||||
        return ResponseEntity.status(HttpStatus.CREATED).body(apiResponse);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @LogExecution("로그아웃")
 | 
			
		||||
    @Operation(summary = "로그아웃", description = "사용자 로그아웃을 처리합니다.")
 | 
			
		||||
    @ApiResponses({
 | 
			
		||||
        @ApiResponse(responseCode = "200", description = "로그아웃 성공"),
 | 
			
		||||
        @ApiResponse(responseCode = "401", description = "인증 실패", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
 | 
			
		||||
    })
 | 
			
		||||
    @PostMapping("/logout")
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<Void>> logout() {
 | 
			
		||||
        try {
 | 
			
		||||
            String userId = SecurityUtils.getCurrentUserId();
 | 
			
		||||
            memberService.deleteRefreshToken(userId);
 | 
			
		||||
            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));
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,4 +1,4 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.dto;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.dto;
 | 
			
		||||
 | 
			
		||||
import lombok.AllArgsConstructor;
 | 
			
		||||
import lombok.Builder;
 | 
			
		||||
@@ -6,6 +6,7 @@ import lombok.Data;
 | 
			
		||||
import lombok.NoArgsConstructor;
 | 
			
		||||
 | 
			
		||||
import jakarta.validation.constraints.NotBlank;
 | 
			
		||||
import jakarta.validation.constraints.Email;
 | 
			
		||||
 | 
			
		||||
@Data
 | 
			
		||||
@Builder
 | 
			
		||||
@@ -18,4 +19,11 @@ public class CreateMemberRequestDto {
 | 
			
		||||
    
 | 
			
		||||
    @NotBlank(message = "비밀번호는 필수입니다.")
 | 
			
		||||
    private String password;
 | 
			
		||||
    
 | 
			
		||||
    @NotBlank(message = "사용자명은 필수입니다.")
 | 
			
		||||
    private String name;
 | 
			
		||||
    
 | 
			
		||||
    @NotBlank(message = "이메일은 필수입니다.")
 | 
			
		||||
    @Email(message = "올바른 이메일 형식이 아닙니다.")
 | 
			
		||||
    private String email;
 | 
			
		||||
}
 | 
			
		||||
@@ -1,6 +1,6 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.dto;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.dto;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.enums.MemberRole;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.enums.MemberRole;
 | 
			
		||||
import lombok.AllArgsConstructor;
 | 
			
		||||
import lombok.Builder;
 | 
			
		||||
import lombok.Data;
 | 
			
		||||
@@ -1,4 +1,4 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.dto;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.dto;
 | 
			
		||||
 | 
			
		||||
import lombok.AllArgsConstructor;
 | 
			
		||||
import lombok.Builder;
 | 
			
		||||
@@ -1,4 +1,4 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.dto;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.dto;
 | 
			
		||||
 | 
			
		||||
import lombok.AllArgsConstructor;
 | 
			
		||||
import lombok.Builder;
 | 
			
		||||
@@ -1,6 +1,6 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.dto;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.dto;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.enums.MemberRole;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.enums.MemberRole;
 | 
			
		||||
import lombok.AllArgsConstructor;
 | 
			
		||||
import lombok.Builder;
 | 
			
		||||
import lombok.Data;
 | 
			
		||||
@@ -22,9 +22,12 @@ public class MemberDto implements UserDetails {
 | 
			
		||||
    private Long oid;
 | 
			
		||||
    private String userId;
 | 
			
		||||
    private String password;
 | 
			
		||||
    private String name;
 | 
			
		||||
    private String email;
 | 
			
		||||
    private MemberRole role;
 | 
			
		||||
    private Boolean useFlag;
 | 
			
		||||
    private String refreshToken;
 | 
			
		||||
    private String loginIp;
 | 
			
		||||
    private LocalDateTime lastLoginAt;
 | 
			
		||||
    private LocalDateTime createdAt;
 | 
			
		||||
    private LocalDateTime updatedAt;
 | 
			
		||||
@@ -39,21 +42,11 @@ public class MemberDto implements UserDetails {
 | 
			
		||||
        return this.userId;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    public boolean isAccountNonExpired() {
 | 
			
		||||
        return true;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    public boolean isAccountNonLocked() {
 | 
			
		||||
        return this.useFlag != null && this.useFlag;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    public boolean isCredentialsNonExpired() {
 | 
			
		||||
        return true;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    public boolean isEnabled() {
 | 
			
		||||
        return this.useFlag != null && this.useFlag;
 | 
			
		||||
@@ -1,6 +1,7 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.entity;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.entity;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.enums.MemberRole;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.enums.MemberRole;
 | 
			
		||||
import com.bio.bio_backend.global.constants.AppConstants;
 | 
			
		||||
import com.bio.bio_backend.global.entity.BaseEntity;
 | 
			
		||||
import jakarta.persistence.*;
 | 
			
		||||
import lombok.AllArgsConstructor;
 | 
			
		||||
@@ -17,7 +18,7 @@ import java.time.LocalDateTime;
 | 
			
		||||
@AllArgsConstructor
 | 
			
		||||
@Builder
 | 
			
		||||
@Table(
 | 
			
		||||
    name = "st_member",
 | 
			
		||||
    name = AppConstants.TABLE_PREFIX + "member",
 | 
			
		||||
    indexes = {
 | 
			
		||||
        @Index(name = "idx_member_user_id", columnList = "user_id")
 | 
			
		||||
    }
 | 
			
		||||
@@ -30,6 +31,12 @@ public class Member extends BaseEntity {
 | 
			
		||||
    @Column(name = "password", nullable = false, length = 100)
 | 
			
		||||
    private String password;
 | 
			
		||||
 | 
			
		||||
    @Column(name = "name", nullable = false, length = 100)
 | 
			
		||||
    private String name;
 | 
			
		||||
 | 
			
		||||
    @Column(name = "email", nullable = false, length = 255)
 | 
			
		||||
    private String email;
 | 
			
		||||
 | 
			
		||||
    @Enumerated(EnumType.STRING)
 | 
			
		||||
    @Column(name = "role", nullable = false, length = 40)
 | 
			
		||||
    private MemberRole role;
 | 
			
		||||
@@ -38,9 +45,12 @@ public class Member extends BaseEntity {
 | 
			
		||||
    @Builder.Default
 | 
			
		||||
    private Boolean useFlag = true;
 | 
			
		||||
 | 
			
		||||
    @Column(name = "refresh_token", length = 200)
 | 
			
		||||
    @Column(name = "refresh_token", length = 1024)
 | 
			
		||||
    private String refreshToken;
 | 
			
		||||
 | 
			
		||||
    @Column(name = "login_ip", length = 45)  // IPv6 지원을 위해 45자
 | 
			
		||||
    private String loginIp;
 | 
			
		||||
 | 
			
		||||
    @Column(name = "last_login_at")
 | 
			
		||||
    private LocalDateTime lastLoginAt;
 | 
			
		||||
    
 | 
			
		||||
@@ -1,4 +1,4 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.enums;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.enums;
 | 
			
		||||
 | 
			
		||||
import lombok.Getter;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
@@ -12,7 +12,6 @@ public enum MemberRole {
 | 
			
		||||
    
 | 
			
		||||
    MEMBER("MEMBER", "일반 회원"),
 | 
			
		||||
    ADMIN("ADMIN", "관리자"),
 | 
			
		||||
    USER("USER", "사용자"),
 | 
			
		||||
    SYSTEM_ADMIN("SYSTEM_ADMIN", "시스템 관리자");
 | 
			
		||||
    
 | 
			
		||||
    private final String value;
 | 
			
		||||
@@ -1,10 +1,10 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.mapper;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.mapper;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.CreateMemberRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.CreateMemberResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.MemberDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.entity.Member;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.enums.MemberRole;
 | 
			
		||||
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.MemberDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.entity.Member;
 | 
			
		||||
import com.bio.bio_backend.global.annotation.IgnoreBaseEntityMapping;
 | 
			
		||||
import org.mapstruct.Mapper;
 | 
			
		||||
import org.mapstruct.Mapping;
 | 
			
		||||
import org.mapstruct.factory.Mappers;
 | 
			
		||||
@@ -20,9 +20,10 @@ public interface MemberMapper {
 | 
			
		||||
     * 기본값 설정: role = MemberRole.MEMBER, useFlag = true
 | 
			
		||||
     */
 | 
			
		||||
    @Mapping(target = "oid", ignore = true)
 | 
			
		||||
    @Mapping(target = "role", expression = "java(com.bio.bio_backend.domain.user.member.enums.MemberRole.getDefault())")
 | 
			
		||||
    @Mapping(target = "role", expression = "java(com.bio.bio_backend.domain.base.member.enums.MemberRole.getDefault())")
 | 
			
		||||
    @Mapping(target = "useFlag", constant = "true")
 | 
			
		||||
    @Mapping(target = "refreshToken", ignore = true)
 | 
			
		||||
    @Mapping(target = "loginIp", ignore = true)
 | 
			
		||||
    @Mapping(target = "lastLoginAt", ignore = true)
 | 
			
		||||
    @Mapping(target = "createdAt", ignore = true)
 | 
			
		||||
    @Mapping(target = "updatedAt", ignore = true)
 | 
			
		||||
@@ -47,4 +48,10 @@ public interface MemberMapper {
 | 
			
		||||
     * MemberDto를 CreateMemberResponseDto로 변환
 | 
			
		||||
     */
 | 
			
		||||
    CreateMemberResponseDto toCreateMemberResponseDto(MemberDto memberDto);
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * MemberDto의 값으로 기존 Member 엔티티 업데이트 (null이 아닌 필드만)
 | 
			
		||||
     */
 | 
			
		||||
    @IgnoreBaseEntityMapping
 | 
			
		||||
    void updateMemberFromDto(MemberDto memberDto, @org.mapstruct.MappingTarget Member member);
 | 
			
		||||
}
 | 
			
		||||
@@ -1,17 +1,17 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.repository;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.repository;
 | 
			
		||||
 | 
			
		||||
import org.springframework.data.jpa.repository.JpaRepository;
 | 
			
		||||
import org.springframework.stereotype.Repository;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.entity.Member;
 | 
			
		||||
import java.util.Optional;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.entity.Member;
 | 
			
		||||
import java.util.List;
 | 
			
		||||
 | 
			
		||||
@Repository
 | 
			
		||||
public interface MemberRepository extends JpaRepository<Member, Long> {
 | 
			
		||||
    
 | 
			
		||||
    // 사용자 ID로 회원 조회 (Optional 반환)
 | 
			
		||||
    Optional<Member> findByUserId(String userId);
 | 
			
		||||
    
 | 
			
		||||
public interface MemberRepository extends JpaRepository<Member, Long>, MemberRepositoryCustom {
 | 
			
		||||
 | 
			
		||||
    // 사용자 ID 존재 여부 확인
 | 
			
		||||
    boolean existsByUserId(String userId);
 | 
			
		||||
} 
 | 
			
		||||
    
 | 
			
		||||
    // 활성화된 회원 목록 조회
 | 
			
		||||
    List<Member> findByUseFlagTrue();
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,19 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.repository;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.entity.Member;
 | 
			
		||||
import java.util.Optional;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * QueryDSL을 활용한 커스텀 쿼리 메서드들을 정의하는 인터페이스
 | 
			
		||||
 * 복잡한 쿼리나 동적 쿼리가 필요한 경우 이 인터페이스를 구현하여 사용합니다.
 | 
			
		||||
 */
 | 
			
		||||
public interface MemberRepositoryCustom {
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 활성화된 사용자 중에서 사용자 ID로 검색하여 조회합니다.
 | 
			
		||||
     *
 | 
			
		||||
     * @param userId 사용자 ID
 | 
			
		||||
     * @return Optional<Member> 회원 정보 (없으면 empty)
 | 
			
		||||
     */
 | 
			
		||||
    Optional<Member> findActiveMemberByUserId(String userId);
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,38 @@
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.repository;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.entity.Member;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.entity.QMember;
 | 
			
		||||
import com.querydsl.jpa.impl.JPAQueryFactory;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import org.springframework.stereotype.Repository;
 | 
			
		||||
 | 
			
		||||
import java.util.Optional;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * QueryDSL을 활용하여 MemberRepositoryCustom 인터페이스를 구현하는 클래스
 | 
			
		||||
 * 복잡한 쿼리나 동적 쿼리를 QueryDSL로 작성하여 성능과 가독성을 향상시킵니다.
 | 
			
		||||
 */
 | 
			
		||||
@Repository
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
public class MemberRepositoryImpl implements MemberRepositoryCustom {
 | 
			
		||||
 | 
			
		||||
    private final JPAQueryFactory queryFactory;
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * QMember 인스턴스를 생성하여 쿼리에서 사용합니다.
 | 
			
		||||
     * QueryDSL의 Q클래스를 통해 타입 안전한 쿼리 작성이 가능합니다.
 | 
			
		||||
     */
 | 
			
		||||
    private final QMember member = QMember.member;
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public Optional<Member> findActiveMemberByUserId(String userId) {
 | 
			
		||||
        // 활성화된 사용자 중에서 사용자 ID로 검색
 | 
			
		||||
        Member foundMember = queryFactory
 | 
			
		||||
                .selectFrom(member)
 | 
			
		||||
                .where(member.userId.eq(userId)
 | 
			
		||||
                        .and(member.useFlag.eq(true)))
 | 
			
		||||
                .fetchOne();
 | 
			
		||||
 | 
			
		||||
        return Optional.ofNullable(foundMember);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,4 +1,4 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.service;
 | 
			
		||||
package com.bio.bio_backend.domain.base.member.service;
 | 
			
		||||
 | 
			
		||||
import java.util.List;
 | 
			
		||||
import java.util.Map;
 | 
			
		||||
@@ -6,7 +6,7 @@ import java.util.Map;
 | 
			
		||||
import org.springframework.security.core.userdetails.UserDetails;
 | 
			
		||||
import org.springframework.security.core.userdetails.UserDetailsService;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.MemberDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
 | 
			
		||||
 | 
			
		||||
public interface MemberService extends UserDetailsService {
 | 
			
		||||
 | 
			
		||||
@@ -14,17 +14,11 @@ public interface MemberService extends UserDetailsService {
 | 
			
		||||
 | 
			
		||||
    MemberDto createMember(MemberDto memberDTO);
 | 
			
		||||
 | 
			
		||||
    void updateRefreshToken(MemberDto memberDTO);
 | 
			
		||||
 | 
			
		||||
    String getRefreshToken(String id);
 | 
			
		||||
 | 
			
		||||
    int deleteRefreshToken(String id);
 | 
			
		||||
 | 
			
		||||
    List<MemberDto> selectMemberList(Map<String, String> params);
 | 
			
		||||
 | 
			
		||||
    MemberDto selectMember(long seq);
 | 
			
		||||
 | 
			
		||||
    int updateMember(MemberDto member);
 | 
			
		||||
 | 
			
		||||
    int deleteMember(MemberDto member);
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,102 @@
 | 
			
		||||
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.entity.Member;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.enums.MemberRole;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.mapper.MemberMapper;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.repository.MemberRepository;
 | 
			
		||||
import com.bio.bio_backend.global.exception.ApiException;
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.global.constants.AppConstants;
 | 
			
		||||
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.security.crypto.bcrypt.BCryptPasswordEncoder;
 | 
			
		||||
import org.springframework.stereotype.Service;
 | 
			
		||||
import org.springframework.transaction.annotation.Transactional;
 | 
			
		||||
 | 
			
		||||
import java.util.List;
 | 
			
		||||
import java.util.Map;
 | 
			
		||||
 | 
			
		||||
import static com.bio.bio_backend.global.utils.OidUtils.generateOid;
 | 
			
		||||
 | 
			
		||||
@Service
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
@Transactional(readOnly = true)
 | 
			
		||||
public class MemberServiceImpl implements MemberService {
 | 
			
		||||
 | 
			
		||||
    private final MemberMapper memberMapper;  // MapStruct Mapper 사용
 | 
			
		||||
    private final MemberRepository memberRepository;
 | 
			
		||||
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
 | 
			
		||||
        Member member = memberRepository.findActiveMemberByUserId(id)
 | 
			
		||||
                .orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다: " + id));
 | 
			
		||||
        return memberMapper.toMemberDto(member);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public MemberDto createMember(MemberDto memberDto) {
 | 
			
		||||
        // userId 중복 체크
 | 
			
		||||
        if (memberRepository.existsByUserId(memberDto.getUserId())) {
 | 
			
		||||
            throw new ApiException(ApiResponseCode.USER_ID_DUPLICATE);
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        Member member = Member.builder()
 | 
			
		||||
                .userId(memberDto.getUserId())
 | 
			
		||||
                .password(bCryptPasswordEncoder.encode(memberDto.getPassword()))
 | 
			
		||||
                .name(memberDto.getName())
 | 
			
		||||
                .email(memberDto.getEmail())
 | 
			
		||||
                .role(MemberRole.getDefault())
 | 
			
		||||
                .build();
 | 
			
		||||
 | 
			
		||||
        Long oid = generateOid();
 | 
			
		||||
        member.setOid(oid);
 | 
			
		||||
        member.setCreator(AppConstants.ADMIN_OID, AppConstants.ADMIN_USER_ID);
 | 
			
		||||
        
 | 
			
		||||
        Member savedMember = memberRepository.save(member);
 | 
			
		||||
        
 | 
			
		||||
        return memberMapper.toMemberDto(savedMember);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public int updateMember(MemberDto memberDto) {
 | 
			
		||||
        Member member = memberRepository.findActiveMemberByUserId(memberDto.getUserId())
 | 
			
		||||
                .orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND));
 | 
			
		||||
        
 | 
			
		||||
        memberMapper.updateMemberFromDto(memberDto, member);
 | 
			
		||||
        memberRepository.save(member);
 | 
			
		||||
        return 1;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public String getRefreshToken(String id) {
 | 
			
		||||
        Member member = memberRepository.findActiveMemberByUserId(id)
 | 
			
		||||
                .orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND));
 | 
			
		||||
        
 | 
			
		||||
        return member.getRefreshToken();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public int deleteRefreshToken(String id) {
 | 
			
		||||
        Member member = memberRepository.findActiveMemberByUserId(id)
 | 
			
		||||
                .orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND));
 | 
			
		||||
        
 | 
			
		||||
        member.setRefreshToken(null);
 | 
			
		||||
        memberRepository.save(member);
 | 
			
		||||
        return 1;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public List<MemberDto> selectMemberList(Map<String, String> params) {
 | 
			
		||||
        List<Member> members = memberRepository.findByUseFlagTrue();
 | 
			
		||||
        
 | 
			
		||||
        return memberMapper.toMemberDtoList(members);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,106 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.controller;
 | 
			
		||||
 | 
			
		||||
import org.springframework.http.HttpStatus;
 | 
			
		||||
import org.springframework.http.ResponseEntity;
 | 
			
		||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 | 
			
		||||
import org.springframework.web.bind.annotation.GetMapping;
 | 
			
		||||
import org.springframework.web.bind.annotation.PostMapping;
 | 
			
		||||
import org.springframework.web.bind.annotation.RequestBody;
 | 
			
		||||
import org.springframework.web.bind.annotation.RestController;
 | 
			
		||||
 | 
			
		||||
import jakarta.validation.Valid;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.MemberDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.CreateMemberRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.CreateMemberResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.service.MemberService;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.mapper.MemberMapper;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
 | 
			
		||||
@RestController
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class MemberController {
 | 
			
		||||
 | 
			
		||||
    private final MemberService memberService;
 | 
			
		||||
    private final MemberMapper memberMapper;
 | 
			
		||||
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
 | 
			
		||||
 | 
			
		||||
    @PostMapping("/members")
 | 
			
		||||
    public ResponseEntity<CreateMemberResponseDto> createMember(@RequestBody @Valid CreateMemberRequestDto requestDto) {
 | 
			
		||||
        MemberDto member = memberMapper.toMemberDto(requestDto);
 | 
			
		||||
        MemberDto createdMember = memberService.createMember(member);
 | 
			
		||||
        CreateMemberResponseDto responseDto = memberMapper.toCreateMemberResponseDto(createdMember);
 | 
			
		||||
 | 
			
		||||
        return ResponseEntity.status(HttpStatus.CREATED).body(responseDto);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // @PostMapping("/member/list")
 | 
			
		||||
    // public ResponseEntity<List<ResponseMember>> getMemberList(@RequestBody(required = false) Map<String, String> params) {
 | 
			
		||||
 | 
			
		||||
    //     if(params == null){
 | 
			
		||||
    //         params = new HashMap<>();
 | 
			
		||||
    //     }
 | 
			
		||||
 | 
			
		||||
    //     Iterable<MemberDTO> memberList = memberService.selectMemberList(params);
 | 
			
		||||
 | 
			
		||||
    //     List<ResponseMember> result = new ArrayList<>();
 | 
			
		||||
 | 
			
		||||
    //     memberList.forEach(m -> {
 | 
			
		||||
    //         result.add(new ModelMapper().map(m, ResponseMember.class));
 | 
			
		||||
    //     });
 | 
			
		||||
 | 
			
		||||
    //     return ResponseEntity.status(HttpStatus.OK).body(result);
 | 
			
		||||
    // }
 | 
			
		||||
 | 
			
		||||
    // @GetMapping("/member/{seq}")
 | 
			
		||||
    // public ResponseEntity<ResponseMember> selectMember(@PathVariable("seq") int seq) {
 | 
			
		||||
 | 
			
		||||
    //     MemberDTO member = memberService.selectMember(seq);
 | 
			
		||||
 | 
			
		||||
    //     ResponseMember responseMember = mapper.map(member, ResponseMember.class);
 | 
			
		||||
 | 
			
		||||
    //     return ResponseEntity.status(HttpStatus.OK).body(responseMember);
 | 
			
		||||
    // }
 | 
			
		||||
 | 
			
		||||
    // @PutMapping("/member")
 | 
			
		||||
    // public CustomApiResponse<Void> updateMember(@RequestBody @Valid CreateMemberRequestDTO requestMember, @AuthenticationPrincipal MemberDTO registrant) {
 | 
			
		||||
    //     // 현재 JWT는 사용자 id 값을 통하여 생성, 회원정보 변경 시 JWT 재발급 여부 검토
 | 
			
		||||
 | 
			
		||||
    //     MemberDTO member = mapper.map(requestMember, MemberDTO.class);
 | 
			
		||||
 | 
			
		||||
    //     if (requestMember.getPassword() != null) {
 | 
			
		||||
    //         member.setPw(bCryptPasswordEncoder.encode(requestMember.getPassword()));
 | 
			
		||||
    //     }
 | 
			
		||||
 | 
			
		||||
    //     member.setRegSeq(registrant.getSeq());
 | 
			
		||||
    //     memberService.updateMember(member);
 | 
			
		||||
 | 
			
		||||
    //     return CustomApiResponse.success(ApiResponseCode.USER_INFO_CHANGE, null);
 | 
			
		||||
    // }
 | 
			
		||||
 | 
			
		||||
    // @DeleteMapping("/member")
 | 
			
		||||
    // public CustomApiResponse<Void> deleteMember(@RequestBody @Valid CreateMemberRequestDTO requestMember){
 | 
			
		||||
 | 
			
		||||
    //     MemberDTO member = mapper.map(requestMember, MemberDTO.class);
 | 
			
		||||
 | 
			
		||||
    //     memberService.deleteMember(member);
 | 
			
		||||
 | 
			
		||||
    //     return CustomApiResponse.success(ApiResponseCode.USER_DELETE_SUCCESSFUL, null);
 | 
			
		||||
    // }
 | 
			
		||||
 | 
			
		||||
    // @PostMapping("/logout")
 | 
			
		||||
    // public CustomApiResponse<Void> logout(@AuthenticationPrincipal MemberDTO member) {
 | 
			
		||||
 | 
			
		||||
    //     String id = member.getId();
 | 
			
		||||
 | 
			
		||||
    //     try {
 | 
			
		||||
    //         memberService.deleteRefreshToken(id);
 | 
			
		||||
    //     } catch (Exception e) {
 | 
			
		||||
    //         return CustomApiResponse.fail(ApiResponseCode.INTERNAL_SERVER_ERROR, null);
 | 
			
		||||
    //     }
 | 
			
		||||
 | 
			
		||||
    //     return CustomApiResponse.success(ApiResponseCode.LOGOUT_SUCCESSFUL, null);
 | 
			
		||||
    // }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@@ -1,12 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.exception;
 | 
			
		||||
 | 
			
		||||
public class UserDuplicateException extends RuntimeException {
 | 
			
		||||
    
 | 
			
		||||
    public UserDuplicateException(String message) {
 | 
			
		||||
        super(message);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    public UserDuplicateException(String message, Throwable cause) {
 | 
			
		||||
        super(message, cause);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,68 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.repository;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.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 {
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 사용자 ID로 회원을 조회합니다.
 | 
			
		||||
     * QueryDSL을 사용하여 더 유연한 쿼리 작성이 가능합니다.
 | 
			
		||||
     *
 | 
			
		||||
     * @param userId 사용자 ID
 | 
			
		||||
     * @return Optional<Member> 회원 정보 (없으면 empty)
 | 
			
		||||
     */
 | 
			
		||||
    Optional<Member> findByUserIdCustom(String userId);
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 역할(Role)별로 회원 목록을 조회합니다.
 | 
			
		||||
     *
 | 
			
		||||
     * @param role 회원 역할
 | 
			
		||||
     * @return List<Member> 해당 역할을 가진 회원 목록
 | 
			
		||||
     */
 | 
			
		||||
    List<Member> findByRole(String role);
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 사용 여부별로 회원 목록을 조회합니다.
 | 
			
		||||
     *
 | 
			
		||||
     * @param useFlag 사용 여부
 | 
			
		||||
     * @return List<Member> 해당 사용 여부를 가진 회원 목록
 | 
			
		||||
     */
 | 
			
		||||
    List<Member> findByUseFlag(Boolean useFlag);
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 사용자 ID와 사용 여부로 회원을 조회합니다.
 | 
			
		||||
     *
 | 
			
		||||
     * @param userId 사용자 ID
 | 
			
		||||
     * @param useFlag 사용 여부
 | 
			
		||||
     * @return Optional<Member> 회원 정보
 | 
			
		||||
     */
 | 
			
		||||
    Optional<Member> findByUserIdAndUseFlag(String userId, Boolean useFlag);
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 검색 조건에 따른 회원 목록을 페이징하여 조회합니다.
 | 
			
		||||
     *
 | 
			
		||||
     * @param userId 사용자 ID (부분 검색)
 | 
			
		||||
     * @param role 회원 역할
 | 
			
		||||
     * @param useFlag 사용 여부
 | 
			
		||||
     * @param pageable 페이징 정보
 | 
			
		||||
     * @return Page<Member> 페이징된 회원 목록
 | 
			
		||||
     */
 | 
			
		||||
    Page<Member> findMembersByCondition(String userId, String role, Boolean useFlag, Pageable pageable);
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 마지막 로그인 시간이 특정 시간 이후인 회원들을 조회합니다.
 | 
			
		||||
     *
 | 
			
		||||
     * @param lastLoginAfter 마지막 로그인 기준 시간
 | 
			
		||||
     * @return List<Member> 해당 조건을 만족하는 회원 목록
 | 
			
		||||
     */
 | 
			
		||||
    List<Member> findActiveMembersByLastLogin(java.time.LocalDateTime lastLoginAfter);
 | 
			
		||||
}
 | 
			
		||||
@@ -1,131 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.repository;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.entity.Member;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.entity.QMember;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.enums.MemberRole;
 | 
			
		||||
import com.querydsl.core.BooleanBuilder;
 | 
			
		||||
import com.querydsl.core.types.dsl.BooleanExpression;
 | 
			
		||||
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 java.time.LocalDateTime;
 | 
			
		||||
import java.util.List;
 | 
			
		||||
import java.util.Optional;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * QueryDSL을 활용하여 MemberRepositoryCustom 인터페이스를 구현하는 클래스
 | 
			
		||||
 * 복잡한 쿼리나 동적 쿼리를 QueryDSL로 작성하여 성능과 가독성을 향상시킵니다.
 | 
			
		||||
 */
 | 
			
		||||
@Repository
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
public class MemberRepositoryImpl implements MemberRepositoryCustom {
 | 
			
		||||
 | 
			
		||||
    private final JPAQueryFactory queryFactory;
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * QMember 인스턴스를 생성하여 쿼리에서 사용합니다.
 | 
			
		||||
     * QueryDSL의 Q클래스를 통해 타입 안전한 쿼리 작성이 가능합니다.
 | 
			
		||||
     */
 | 
			
		||||
    private final QMember member = QMember.member;
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public Optional<Member> findByUserIdCustom(String userId) {
 | 
			
		||||
        // QueryDSL을 사용하여 사용자 ID로 회원을 조회합니다.
 | 
			
		||||
        // eq() 메서드를 사용하여 정확한 일치 조건을 설정합니다.
 | 
			
		||||
        Member foundMember = queryFactory
 | 
			
		||||
                .selectFrom(member)
 | 
			
		||||
                .where(member.userId.eq(userId))
 | 
			
		||||
                .fetchOne();
 | 
			
		||||
 | 
			
		||||
        return Optional.ofNullable(foundMember);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public List<Member> findByRole(String role) {
 | 
			
		||||
        // 역할별로 회원을 조회합니다.
 | 
			
		||||
        // String을 MemberRole enum으로 변환하여 비교합니다.
 | 
			
		||||
        return queryFactory
 | 
			
		||||
                .selectFrom(member)
 | 
			
		||||
                .where(member.role.eq(MemberRole.fromValue(role)))
 | 
			
		||||
                .fetch();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public List<Member> findByUseFlag(Boolean useFlag) {
 | 
			
		||||
        // 사용 여부별로 회원을 조회합니다.
 | 
			
		||||
        return queryFactory
 | 
			
		||||
                .selectFrom(member)
 | 
			
		||||
                .where(member.useFlag.eq(useFlag))
 | 
			
		||||
                .fetch();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public Optional<Member> findByUserIdAndUseFlag(String userId, Boolean useFlag) {
 | 
			
		||||
        // 사용자 ID와 사용 여부를 모두 만족하는 회원을 조회합니다.
 | 
			
		||||
        // and() 메서드를 사용하여 여러 조건을 결합합니다.
 | 
			
		||||
        Member foundMember = queryFactory
 | 
			
		||||
                .selectFrom(member)
 | 
			
		||||
                .where(member.userId.eq(userId)
 | 
			
		||||
                        .and(member.useFlag.eq(useFlag)))
 | 
			
		||||
                .fetchOne();
 | 
			
		||||
 | 
			
		||||
        return Optional.ofNullable(foundMember);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public Page<Member> findMembersByCondition(String userId, String role, Boolean useFlag, Pageable pageable) {
 | 
			
		||||
        // BooleanBuilder를 사용하여 동적 쿼리를 구성합니다.
 | 
			
		||||
        // null이 아닌 조건만 쿼리에 포함시킵니다.
 | 
			
		||||
        BooleanBuilder builder = new BooleanBuilder();
 | 
			
		||||
 | 
			
		||||
        // 사용자 ID가 제공된 경우 부분 검색 조건을 추가합니다.
 | 
			
		||||
        if (userId != null && !userId.trim().isEmpty()) {
 | 
			
		||||
            builder.and(member.userId.containsIgnoreCase(userId));
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // 역할이 제공된 경우 정확한 일치 조건을 추가합니다.
 | 
			
		||||
        if (role != null && !role.trim().isEmpty()) {
 | 
			
		||||
            builder.and(member.role.eq(MemberRole.fromValue(role)));
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // 사용 여부가 제공된 경우 정확한 일치 조건을 추가합니다.
 | 
			
		||||
        if (useFlag != null) {
 | 
			
		||||
            builder.and(member.useFlag.eq(useFlag));
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // 전체 개수를 조회합니다.
 | 
			
		||||
        long total = queryFactory
 | 
			
		||||
                .selectFrom(member)
 | 
			
		||||
                .where(builder)
 | 
			
		||||
                .fetchCount();
 | 
			
		||||
 | 
			
		||||
        // 페이징 조건을 적용하여 결과를 조회합니다.
 | 
			
		||||
        List<Member> content = queryFactory
 | 
			
		||||
                .selectFrom(member)
 | 
			
		||||
                .where(builder)
 | 
			
		||||
                .orderBy(member.createdAt.desc()) // 생성일 기준 내림차순 정렬
 | 
			
		||||
                .offset(pageable.getOffset())
 | 
			
		||||
                .limit(pageable.getPageSize())
 | 
			
		||||
                .fetch();
 | 
			
		||||
 | 
			
		||||
        // Page 객체를 생성하여 반환합니다.
 | 
			
		||||
        return new PageImpl<>(content, pageable, total);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public List<Member> findActiveMembersByLastLogin(LocalDateTime lastLoginAfter) {
 | 
			
		||||
        // 마지막 로그인 시간이 특정 시간 이후인 활성 회원들을 조회합니다.
 | 
			
		||||
        // 여러 조건을 조합하여 복잡한 쿼리를 작성합니다.
 | 
			
		||||
        return queryFactory
 | 
			
		||||
                .selectFrom(member)
 | 
			
		||||
                .where(member.useFlag.eq(true) // 사용 중인 상태
 | 
			
		||||
                        .and(member.lastLoginAt.isNotNull()) // 마지막 로그인 시간이 존재
 | 
			
		||||
                        .and(member.lastLoginAt.after(lastLoginAfter))) // 특정 시간 이후
 | 
			
		||||
                .orderBy(member.lastLoginAt.desc()) // 마지막 로그인 시간 기준 내림차순 정렬
 | 
			
		||||
                .fetch();
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,147 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.domain.user.member.service;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.MemberDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.entity.Member;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.enums.MemberRole;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.mapper.MemberMapper;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.repository.MemberRepository;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.exception.UserDuplicateException;
 | 
			
		||||
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.security.crypto.bcrypt.BCryptPasswordEncoder;
 | 
			
		||||
import org.springframework.stereotype.Service;
 | 
			
		||||
import org.springframework.transaction.annotation.Transactional;
 | 
			
		||||
 | 
			
		||||
import java.util.List;
 | 
			
		||||
import java.util.Map;
 | 
			
		||||
 | 
			
		||||
import static com.bio.bio_backend.global.utils.OidUtil.generateOid;
 | 
			
		||||
 | 
			
		||||
@Service
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
@Transactional(readOnly = true)
 | 
			
		||||
public class MemberServiceImpl implements MemberService {
 | 
			
		||||
 | 
			
		||||
    private final MemberMapper memberMapper;  // MapStruct Mapper 사용
 | 
			
		||||
    private final MemberRepository memberRepository;
 | 
			
		||||
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
 | 
			
		||||
        // JPA 레파지토리를 사용하여 회원 조회
 | 
			
		||||
        Member member = memberRepository.findByUserId(id)
 | 
			
		||||
                .orElseThrow(() -> new UsernameNotFoundException("User not found with id : " + id));
 | 
			
		||||
        
 | 
			
		||||
        // MapStruct를 사용하여 Member 엔티티를 MemberDto로 변환
 | 
			
		||||
        MemberDto memberDto = memberMapper.toMemberDto(member);
 | 
			
		||||
        
 | 
			
		||||
        return memberDto;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public MemberDto createMember(MemberDto memberDTO) {
 | 
			
		||||
        // userId 중복 체크
 | 
			
		||||
        if (memberRepository.existsByUserId(memberDTO.getUserId())) {
 | 
			
		||||
            throw new UserDuplicateException("User ID already exists");
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        Member member = Member.builder()
 | 
			
		||||
                .userId(memberDTO.getUserId())
 | 
			
		||||
                .password(bCryptPasswordEncoder.encode(memberDTO.getPassword()))
 | 
			
		||||
                .role(MemberRole.getDefault())
 | 
			
		||||
                .build();
 | 
			
		||||
 | 
			
		||||
        Long oid = generateOid();
 | 
			
		||||
        member.setOid(oid);
 | 
			
		||||
        member.setCreatedOid(oid);
 | 
			
		||||
        
 | 
			
		||||
        Member savedMember = memberRepository.save(member);
 | 
			
		||||
        
 | 
			
		||||
        return memberMapper.toMemberDto(savedMember);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public void updateRefreshToken(MemberDto memberDTO) {
 | 
			
		||||
        // JPA를 사용하여 refresh token 업데이트
 | 
			
		||||
        Member member = memberRepository.findByUserId(memberDTO.getUserId())
 | 
			
		||||
                .orElseThrow(() -> new RuntimeException("회원을 찾을 수 없습니다. id: " + memberDTO.getUserId()));
 | 
			
		||||
        
 | 
			
		||||
        member.setRefreshToken(memberDTO.getRefreshToken());
 | 
			
		||||
        memberRepository.save(member);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public String getRefreshToken(String id) {
 | 
			
		||||
        Member member = memberRepository.findByUserId(id)
 | 
			
		||||
                .orElseThrow(() -> new RuntimeException("회원을 찾을 수 없습니다. id: " + id));
 | 
			
		||||
        
 | 
			
		||||
        return member.getRefreshToken();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public int deleteRefreshToken(String id) {
 | 
			
		||||
        Member member = memberRepository.findByUserId(id)
 | 
			
		||||
                .orElseThrow(() -> new RuntimeException("회원을 찾을 수 없습니다. id: " + id));
 | 
			
		||||
        
 | 
			
		||||
        member.setRefreshToken(null);
 | 
			
		||||
        memberRepository.save(member);
 | 
			
		||||
        return 1; // 성공 시 1 반환
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public List<MemberDto> selectMemberList(Map<String, String> params) {
 | 
			
		||||
        // JPA를 사용하여 회원 목록 조회 (간단한 구현)
 | 
			
		||||
        List<Member> members = memberRepository.findAll();
 | 
			
		||||
        
 | 
			
		||||
        // MapStruct를 사용하여 Member 엔티티 리스트를 MemberDto 리스트로 변환
 | 
			
		||||
        return memberMapper.toMemberDtoList(members);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public MemberDto selectMember(long seq) {
 | 
			
		||||
        // JPA 레파지토리를 사용하여 회원 조회
 | 
			
		||||
        Member member = memberRepository.findById(seq)
 | 
			
		||||
                .orElseThrow(() -> new RuntimeException("회원을 찾을 수 없습니다. seq: " + seq));
 | 
			
		||||
        
 | 
			
		||||
        // MapStruct를 사용하여 Member 엔티티를 MemberDto로 자동 변환
 | 
			
		||||
        return memberMapper.toMemberDto(member);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public int updateMember(MemberDto memberDto) {
 | 
			
		||||
        Member member = memberRepository.findByUserId(memberDto.getUserId())
 | 
			
		||||
                .orElseThrow(() -> new RuntimeException("회원을 찾을 수 없습니다. id: " + memberDto.getUserId()));
 | 
			
		||||
        
 | 
			
		||||
        // 비밀번호가 변경된 경우 암호화
 | 
			
		||||
        if (memberDto.getPassword() != null && !memberDto.getPassword().isEmpty()) {
 | 
			
		||||
            member.setPassword(bCryptPasswordEncoder.encode(memberDto.getPassword()));
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        member.setRole(memberDto.getRole());
 | 
			
		||||
        member.setUseFlag(memberDto.getUseFlag());
 | 
			
		||||
        
 | 
			
		||||
        memberRepository.save(member);
 | 
			
		||||
        return 1; // 성공 시 1 반환
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public int deleteMember(MemberDto memberDto) {
 | 
			
		||||
        Member member = memberRepository.findByUserId(memberDto.getUserId())
 | 
			
		||||
                .orElseThrow(() -> new RuntimeException("회원을 찾을 수 없습니다. id: " + memberDto.getUserId()));
 | 
			
		||||
 | 
			
		||||
        member.setUseFlag(false);
 | 
			
		||||
        
 | 
			
		||||
        log.info("회원 삭제 처리: {}", member.toString());
 | 
			
		||||
        
 | 
			
		||||
        memberRepository.save(member);
 | 
			
		||||
        return 1; // 성공 시 1 반환
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,24 @@
 | 
			
		||||
package com.bio.bio_backend.global.annotation;
 | 
			
		||||
 | 
			
		||||
import org.mapstruct.Mapping;
 | 
			
		||||
 | 
			
		||||
import java.lang.annotation.ElementType;
 | 
			
		||||
import java.lang.annotation.Retention;
 | 
			
		||||
import java.lang.annotation.RetentionPolicy;
 | 
			
		||||
import java.lang.annotation.Target;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * BaseEntity의 감사 필드들을 ignore 처리하는 MapStruct 커스텀 어노테이션
 | 
			
		||||
 * 여러 매퍼에서 공통으로 사용할 수 있습니다.
 | 
			
		||||
 */
 | 
			
		||||
@Target(ElementType.METHOD)
 | 
			
		||||
@Retention(RetentionPolicy.CLASS)
 | 
			
		||||
@Mapping(target = "oid", ignore = true)
 | 
			
		||||
@Mapping(target = "createdAt", ignore = true)
 | 
			
		||||
@Mapping(target = "updatedAt", ignore = true)
 | 
			
		||||
@Mapping(target = "createdOid", ignore = true)
 | 
			
		||||
@Mapping(target = "updatedOid", ignore = true)
 | 
			
		||||
@Mapping(target = "createdId", ignore = true)
 | 
			
		||||
@Mapping(target = "updatedId", ignore = true)
 | 
			
		||||
public @interface IgnoreBaseEntityMapping {
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,15 @@
 | 
			
		||||
package com.bio.bio_backend.global.annotation;
 | 
			
		||||
 | 
			
		||||
import java.lang.annotation.ElementType;
 | 
			
		||||
import java.lang.annotation.Retention;
 | 
			
		||||
import java.lang.annotation.RetentionPolicy;
 | 
			
		||||
import java.lang.annotation.Target;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * 메서드 실행 로깅 어노테이션
 | 
			
		||||
 */
 | 
			
		||||
@Target(ElementType.METHOD)
 | 
			
		||||
@Retention(RetentionPolicy.RUNTIME)
 | 
			
		||||
public @interface LogExecution {
 | 
			
		||||
    String value() default "";
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,55 @@
 | 
			
		||||
package com.bio.bio_backend.global.aop;
 | 
			
		||||
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.aspectj.lang.ProceedingJoinPoint;
 | 
			
		||||
import org.aspectj.lang.annotation.Around;
 | 
			
		||||
import org.aspectj.lang.annotation.Aspect;
 | 
			
		||||
import org.springframework.security.core.Authentication;
 | 
			
		||||
import org.springframework.security.core.context.SecurityContextHolder;
 | 
			
		||||
import org.springframework.stereotype.Component;
 | 
			
		||||
 | 
			
		||||
@Aspect
 | 
			
		||||
@Component
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class MethodExecutionLoggingAspect {
 | 
			
		||||
    
 | 
			
		||||
    @Around("@annotation(logExecution)")
 | 
			
		||||
    public Object logExecution(ProceedingJoinPoint pjp, com.bio.bio_backend.global.annotation.LogExecution logExecution) throws Throwable {
 | 
			
		||||
        String message = logExecution.value().isEmpty() ? 
 | 
			
		||||
            pjp.getSignature().getName() : logExecution.value();
 | 
			
		||||
        
 | 
			
		||||
        String className = pjp.getTarget().getClass().getSimpleName();
 | 
			
		||||
        String methodName = pjp.getSignature().getName();
 | 
			
		||||
        
 | 
			
		||||
        String userInfo = getCurrentUser();
 | 
			
		||||
        
 | 
			
		||||
        long startTime = System.currentTimeMillis();
 | 
			
		||||
        log.info("[START] {} | 호출경로: {}.{} | 사용자: {}", 
 | 
			
		||||
                message, className, methodName, userInfo);
 | 
			
		||||
        
 | 
			
		||||
        try {
 | 
			
		||||
            Object result = pjp.proceed();
 | 
			
		||||
            long duration = System.currentTimeMillis() - startTime;
 | 
			
		||||
            log.info("[SUCCESS] {} | 호출경로: {}.{} | 사용자: {} | 시간: {}ms", 
 | 
			
		||||
                    message, className, methodName, userInfo, duration);
 | 
			
		||||
            return result;
 | 
			
		||||
        } catch (Exception e) {
 | 
			
		||||
            long duration = System.currentTimeMillis() - startTime;
 | 
			
		||||
            log.error("[FAILED] {} | 호출경로: {}.{} | 사용자: {} | 시간: {}ms | 오류: {}", 
 | 
			
		||||
                    message, className, methodName, userInfo, duration, e.getMessage());
 | 
			
		||||
            throw e;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    private String getCurrentUser() {
 | 
			
		||||
        try {
 | 
			
		||||
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
 | 
			
		||||
            if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getName())) {
 | 
			
		||||
                return auth.getName();
 | 
			
		||||
            }
 | 
			
		||||
            return "인증되지 않은 사용자";
 | 
			
		||||
        } catch (Exception e) {
 | 
			
		||||
            return "알 수 없는 사용자";
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,9 +1,16 @@
 | 
			
		||||
package com.bio.bio_backend.global.config;
 | 
			
		||||
 | 
			
		||||
import com.fasterxml.jackson.databind.ObjectMapper;
 | 
			
		||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
 | 
			
		||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
 | 
			
		||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
 | 
			
		||||
import org.springframework.context.annotation.Bean;
 | 
			
		||||
import org.springframework.context.annotation.Configuration;
 | 
			
		||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 | 
			
		||||
 | 
			
		||||
import java.time.LocalDateTime;
 | 
			
		||||
import java.time.format.DateTimeFormatter;
 | 
			
		||||
 | 
			
		||||
@Configuration
 | 
			
		||||
public class AppConfig {
 | 
			
		||||
    
 | 
			
		||||
@@ -11,4 +18,21 @@ public class AppConfig {
 | 
			
		||||
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
 | 
			
		||||
        return new BCryptPasswordEncoder();
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @Bean
 | 
			
		||||
    public ObjectMapper objectMapper() {
 | 
			
		||||
        ObjectMapper mapper = new ObjectMapper();
 | 
			
		||||
        
 | 
			
		||||
        // JavaTimeModule 등록
 | 
			
		||||
        JavaTimeModule javaTimeModule = new JavaTimeModule();
 | 
			
		||||
        
 | 
			
		||||
        // LocalDateTime 직렬화/역직렬화 설정
 | 
			
		||||
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
 | 
			
		||||
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
 | 
			
		||||
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
 | 
			
		||||
        
 | 
			
		||||
        mapper.registerModule(javaTimeModule);
 | 
			
		||||
        
 | 
			
		||||
        return mapper;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,42 @@
 | 
			
		||||
package com.bio.bio_backend.global.config;
 | 
			
		||||
 | 
			
		||||
import lombok.Getter;
 | 
			
		||||
import lombok.Setter;
 | 
			
		||||
import org.springframework.boot.context.properties.ConfigurationProperties;
 | 
			
		||||
import org.springframework.stereotype.Component;
 | 
			
		||||
 | 
			
		||||
import java.util.ArrayList;
 | 
			
		||||
import java.util.List;
 | 
			
		||||
 | 
			
		||||
@Getter
 | 
			
		||||
@Setter
 | 
			
		||||
@Component
 | 
			
		||||
@ConfigurationProperties(prefix = "security")
 | 
			
		||||
public class SecurityPathConfig {
 | 
			
		||||
    
 | 
			
		||||
    private List<String> permitAllPaths = new ArrayList<>();
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 주어진 경로가 허용된 경로인지 확인
 | 
			
		||||
     * @param path 확인할 경로
 | 
			
		||||
     * @param contextPath 컨텍스트 경로
 | 
			
		||||
     * @return 허용 여부
 | 
			
		||||
     */
 | 
			
		||||
    public boolean isPermittedPath(String path, String contextPath) {
 | 
			
		||||
        if (permitAllPaths == null) {
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        return permitAllPaths.stream()
 | 
			
		||||
                .anyMatch(permittedPath -> {
 | 
			
		||||
                    String fullPath = contextPath + permittedPath;
 | 
			
		||||
                    if (permittedPath.endsWith("/**")) {
 | 
			
		||||
                        // /** 패턴 처리
 | 
			
		||||
                        String basePath = fullPath.substring(0, fullPath.length() - 2);
 | 
			
		||||
                        return path.startsWith(basePath);
 | 
			
		||||
                    } else {
 | 
			
		||||
                        return path.equals(fullPath);
 | 
			
		||||
                    }
 | 
			
		||||
                });
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,26 @@
 | 
			
		||||
package com.bio.bio_backend.global.config;
 | 
			
		||||
 | 
			
		||||
import io.swagger.v3.oas.models.OpenAPI;
 | 
			
		||||
import io.swagger.v3.oas.models.info.Info;
 | 
			
		||||
import io.swagger.v3.oas.models.info.License;
 | 
			
		||||
import io.swagger.v3.oas.models.servers.Server;
 | 
			
		||||
import org.springframework.context.annotation.Bean;
 | 
			
		||||
import org.springframework.context.annotation.Configuration;
 | 
			
		||||
 | 
			
		||||
import java.util.List;
 | 
			
		||||
 | 
			
		||||
@Configuration
 | 
			
		||||
public class SwaggerConfig {
 | 
			
		||||
 | 
			
		||||
    @Bean
 | 
			
		||||
    public OpenAPI openAPI() {
 | 
			
		||||
        return new OpenAPI()
 | 
			
		||||
                .info(new Info()
 | 
			
		||||
                        .title("대상 미생물 분석 시스템 Backend API")
 | 
			
		||||
                        .description("대상 미생물 분석 시스템 Backend 서비스의 REST API 문서")
 | 
			
		||||
                        .version("v1.0.0")
 | 
			
		||||
                        .license(new License()
 | 
			
		||||
                                .name("STAM License")
 | 
			
		||||
                                .url("https://stam.kr/")));
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,90 @@
 | 
			
		||||
package com.bio.bio_backend.global.constants;
 | 
			
		||||
 | 
			
		||||
import lombok.AllArgsConstructor;
 | 
			
		||||
import lombok.Getter;
 | 
			
		||||
import org.springframework.http.HttpStatus;
 | 
			
		||||
 | 
			
		||||
/*
 | 
			
		||||
 * API 관련 RESPONSE ENUM
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
@Getter
 | 
			
		||||
@AllArgsConstructor
 | 
			
		||||
public enum ApiResponseCode {
 | 
			
		||||
    
 | 
			
		||||
    /*공통 Code*/
 | 
			
		||||
    // 200 OK
 | 
			
		||||
    COMMON_SUCCESS(HttpStatus.OK.value(), "요청 성공"),
 | 
			
		||||
    COMMON_SUCCESS_CREATED(HttpStatus.CREATED.value(), "성공적으로 생성되었습니다"),
 | 
			
		||||
    COMMON_SUCCESS_UPDATED(HttpStatus.OK.value(), "성공적으로 수정되었습니다"),
 | 
			
		||||
    COMMON_SUCCESS_DELETED(HttpStatus.OK.value(), "성공적으로 삭제되었습니다"),
 | 
			
		||||
    COMMON_SUCCESS_RETRIEVED(HttpStatus.OK.value(), "성공적으로 조회되었습니다"),
 | 
			
		||||
 | 
			
		||||
    // 400 Bad Request
 | 
			
		||||
    COMMON_BAD_REQUEST(HttpStatus.BAD_REQUEST.value(), "필수 요청 본문이 누락되었거나 오류가 발생했습니다"),
 | 
			
		||||
    COMMON_FORMAT_WRONG(HttpStatus.BAD_REQUEST.value(), "요청 형식이 올바르지 않습니다"),
 | 
			
		||||
    COMMON_ARGUMENT_NOT_VALID(HttpStatus.BAD_REQUEST.value(), "인자가 유효하지 않습니다"),
 | 
			
		||||
 | 
			
		||||
    // 401 Unauthorized
 | 
			
		||||
    COMMON_UNAUTHORIZED(HttpStatus.UNAUTHORIZED.value(), "인증에 실패했습니다"),
 | 
			
		||||
 | 
			
		||||
    // 403 Forbidden
 | 
			
		||||
    COMMON_FORBIDDEN(HttpStatus.FORBIDDEN.value(), "접근이 거부되었습니다"),
 | 
			
		||||
 | 
			
		||||
    // 404 Not Found
 | 
			
		||||
    COMMON_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "리소스를 찾을 수 없습니다"),
 | 
			
		||||
 | 
			
		||||
    // 405 Method Not Allowed
 | 
			
		||||
    COMMON_METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED.value(), "허용되지 않는 메소드입니다"),
 | 
			
		||||
 | 
			
		||||
    // 409 Conflict
 | 
			
		||||
    COMMON_CONFLICT(HttpStatus.CONFLICT.value(), "충돌이 발생했습니다"),
 | 
			
		||||
 | 
			
		||||
    // 500 Internal Server Error
 | 
			
		||||
    COMMON_INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "서버에서 오류가 발생했습니다"),
 | 
			
		||||
    COMMON_INDEX_OUT_OF_BOUND(HttpStatus.INTERNAL_SERVER_ERROR.value(), "인덱스가 범위를 벗어났습니다"),
 | 
			
		||||
    COMMON_JSON_PROCESSING_EXCEPTION(HttpStatus.INTERNAL_SERVER_ERROR.value(), "유효한 JSON 형식인지 확인해주세요"),
 | 
			
		||||
 | 
			
		||||
    /*사용자 관련 Code*/
 | 
			
		||||
    // 200 OK
 | 
			
		||||
    LOGIN_SUCCESSFUL(HttpStatus.OK.value(), "로그인에 성공했습니다"),
 | 
			
		||||
    LOGOUT_SUCCESSFUL(HttpStatus.OK.value(), "로그아웃에 성공했습니다"),
 | 
			
		||||
    USER_INFO_CHANGE(HttpStatus.OK.value(), "사용자 정보가 성공적으로 수정되었습니다"),
 | 
			
		||||
    USER_DELETE_SUCCESSFUL(HttpStatus.OK.value(), "사용자가 성공적으로 삭제되었습니다"),
 | 
			
		||||
 | 
			
		||||
    // 409 Conflict
 | 
			
		||||
    USER_ID_DUPLICATE(HttpStatus.CONFLICT.value(), "이미 존재하는 사용자 ID입니다"),
 | 
			
		||||
 | 
			
		||||
    // 401 Unauthorized
 | 
			
		||||
    USER_NOT_FOUND(HttpStatus.UNAUTHORIZED.value(), "사용자를 찾을 수 없습니다. 인증에 실패했습니다"),
 | 
			
		||||
    USER_PASSWORD_INVALID(HttpStatus.UNAUTHORIZED.value(), "비밀번호가 올바르지 않습니다"),
 | 
			
		||||
 | 
			
		||||
    // JWT 관련
 | 
			
		||||
    JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT 서명이 일치하지 않습니다. 인증에 실패했습니다"),
 | 
			
		||||
    JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT 토큰이 null입니다"),
 | 
			
		||||
    JWT_TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED.value(), "토큰이 만료되었습니다"),
 | 
			
		||||
    INVALID_CLIENT_IP(HttpStatus.UNAUTHORIZED.value(), "클라이언트 IP 주소가 일치하지 않습니다"),
 | 
			
		||||
    ALL_TOKEN_INVALID(HttpStatus.UNAUTHORIZED.value(), "액세스 토큰과 리프레시 토큰이 모두 만료되었거나 유효하지 않습니다"),
 | 
			
		||||
 | 
			
		||||
    /*파일 관련 Code*/
 | 
			
		||||
    // 200 OK
 | 
			
		||||
    FILE_UPLOAD_SUCCESS(HttpStatus.OK.value(), "파일이 성공적으로 업로드되었습니다"),
 | 
			
		||||
    FILE_DOWNLOAD_SUCCESS(HttpStatus.OK.value(), "파일 다운로드가 성공했습니다"),
 | 
			
		||||
    FILE_DELETE_SUCCESS(HttpStatus.OK.value(), "파일이 성공적으로 삭제되었습니다"),
 | 
			
		||||
 | 
			
		||||
    // 400 Bad Request
 | 
			
		||||
    FILE_EMPTY(HttpStatus.BAD_REQUEST.value(), "업로드할 파일이 없습니다"),
 | 
			
		||||
    FILE_INVALID_FORMAT(HttpStatus.BAD_REQUEST.value(), "지원하지 않는 파일 형식입니다"),
 | 
			
		||||
 | 
			
		||||
    // 404 Not Found
 | 
			
		||||
    FILE_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "파일을 찾을 수 없습니다"),
 | 
			
		||||
 | 
			
		||||
    // 500 Internal Server Error
 | 
			
		||||
    FILE_UPLOAD_FAILED(HttpStatus.INTERNAL_SERVER_ERROR.value(), "파일 업로드에 실패했습니다"),
 | 
			
		||||
    FILE_DOWNLOAD_FAILED(HttpStatus.INTERNAL_SERVER_ERROR.value(), "파일 다운로드에 실패했습니다"),
 | 
			
		||||
    FILE_DELETE_FAILED(HttpStatus.INTERNAL_SERVER_ERROR.value(), "파일 삭제에 실패했습니다");
 | 
			
		||||
 | 
			
		||||
    private final int statusCode;
 | 
			
		||||
    private final String description;
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,10 @@
 | 
			
		||||
package com.bio.bio_backend.global.constants;
 | 
			
		||||
 | 
			
		||||
public class AppConstants {
 | 
			
		||||
    public static final String TABLE_PREFIX = "st_";
 | 
			
		||||
    
 | 
			
		||||
    // 관리자 관련 상수
 | 
			
		||||
    public static final Long ADMIN_OID = 1000000000000000L;
 | 
			
		||||
    public static final String ADMIN_USER_ID = "admin";
 | 
			
		||||
    public static final String ADMIN_NAME = "시스템관리자";
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,46 @@
 | 
			
		||||
package com.bio.bio_backend.global.dto;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
import com.fasterxml.jackson.annotation.JsonInclude;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
import lombok.Data;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
 | 
			
		||||
@Data
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@JsonInclude(JsonInclude.Include.NON_NULL)
 | 
			
		||||
public class ApiResponseDto<T> {
 | 
			
		||||
 | 
			
		||||
    private int code;
 | 
			
		||||
    private String message;
 | 
			
		||||
    private String description;
 | 
			
		||||
    private T data;
 | 
			
		||||
 | 
			
		||||
    private static final int SUCCESS = 200;
 | 
			
		||||
 | 
			
		||||
    private ApiResponseDto(int code, String message, String description, T data){
 | 
			
		||||
        this.code = code;
 | 
			
		||||
        this.message = message;
 | 
			
		||||
        this.description = description;
 | 
			
		||||
        this.data = data;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public static <T> ApiResponseDto<T> success(ApiResponseCode responseCode, T data) {
 | 
			
		||||
        return new ApiResponseDto<T>(SUCCESS, responseCode.name(), responseCode.getDescription(), data);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public static <T> ApiResponseDto<T> success(ApiResponseCode responseCode) {
 | 
			
		||||
        return new ApiResponseDto<T>(SUCCESS, responseCode.name(), responseCode.getDescription(), null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public static <T> ApiResponseDto<T> fail(ApiResponseCode responseCode, T data) {
 | 
			
		||||
        return new ApiResponseDto<T>(responseCode.getStatusCode(), responseCode.name(), responseCode.getDescription(), data);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public static <T> ApiResponseDto<T> fail(ApiResponseCode responseCode) {
 | 
			
		||||
        return new ApiResponseDto<T>(responseCode.getStatusCode(), responseCode.name(), responseCode.getDescription(), null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@@ -1,39 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.global.dto;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
import com.fasterxml.jackson.annotation.JsonInclude;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.global.utils.ApiResponseCode;
 | 
			
		||||
import lombok.Data;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
 | 
			
		||||
//공통 response Class
 | 
			
		||||
@Data
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@JsonInclude(JsonInclude.Include.NON_NULL)
 | 
			
		||||
public class CustomApiResponse<T> {
 | 
			
		||||
 | 
			
		||||
    private int code;
 | 
			
		||||
    private String message;
 | 
			
		||||
    private String description;
 | 
			
		||||
    private T data;
 | 
			
		||||
 | 
			
		||||
    private static final int SUCCESS = 200;
 | 
			
		||||
 | 
			
		||||
    private CustomApiResponse(int code, String message, String description, T data){
 | 
			
		||||
        this.code = code;
 | 
			
		||||
        this.message = message;
 | 
			
		||||
        this.description = description;
 | 
			
		||||
        this.data = data;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public static <T> CustomApiResponse<T> success(ApiResponseCode responseCode, T data) {
 | 
			
		||||
        return new CustomApiResponse<T>(SUCCESS, responseCode.name(), responseCode.getDescription(), data);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public static <T> CustomApiResponse<T> fail(ApiResponseCode responseCode, T data) {
 | 
			
		||||
        return new CustomApiResponse<T>(responseCode.getStatusCode(), responseCode.name(), responseCode.getDescription(), data);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@@ -9,7 +9,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
 | 
			
		||||
 | 
			
		||||
import java.time.LocalDateTime;
 | 
			
		||||
 | 
			
		||||
import static com.bio.bio_backend.global.utils.OidUtil.generateOid;
 | 
			
		||||
import static com.bio.bio_backend.global.utils.OidUtils.generateOid;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * 모든 엔티티가 상속받는 기본 엔티티 클래스
 | 
			
		||||
@@ -38,10 +38,38 @@ public abstract class BaseEntity {
 | 
			
		||||
 | 
			
		||||
    @Column(name = "updated_oid")
 | 
			
		||||
    private Long updatedOid;
 | 
			
		||||
 | 
			
		||||
    @Column(name = "created_id", updatable = false)
 | 
			
		||||
    private String createdId;
 | 
			
		||||
 | 
			
		||||
    @Column(name = "updated_id")
 | 
			
		||||
    private String updatedId;
 | 
			
		||||
    
 | 
			
		||||
    @PrePersist
 | 
			
		||||
    protected void onCreate() {
 | 
			
		||||
        if(this.oid == null) this.oid = generateOid();
 | 
			
		||||
        if(this.createdOid != null && this.updatedOid == null) this.updatedOid = this.createdOid;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 생성자 정보를 설정합니다.
 | 
			
		||||
     * @param createdOid 생성자 OID
 | 
			
		||||
     * @param createdId 생성자 ID
 | 
			
		||||
     */
 | 
			
		||||
    public void setCreator(Long createdOid, String createdId) {
 | 
			
		||||
        this.createdOid = createdOid;
 | 
			
		||||
        this.createdId = createdId;
 | 
			
		||||
        this.updatedOid = createdOid;
 | 
			
		||||
        this.updatedId = createdId;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 수정자 정보를 설정합니다.
 | 
			
		||||
     * @param updatedOid 수정자 OID
 | 
			
		||||
     * @param updatedId 수정자 ID
 | 
			
		||||
     */
 | 
			
		||||
    public void setUpdater(Long updatedOid, String updatedId) {
 | 
			
		||||
        this.updatedOid = updatedOid;
 | 
			
		||||
        this.updatedId = updatedId;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -0,0 +1,24 @@
 | 
			
		||||
package com.bio.bio_backend.global.exception;
 | 
			
		||||
 | 
			
		||||
import lombok.Getter;
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
 | 
			
		||||
@Getter
 | 
			
		||||
public class ApiException extends RuntimeException {
 | 
			
		||||
    private final ApiResponseCode responseCode;
 | 
			
		||||
 | 
			
		||||
    public ApiException(ApiResponseCode responseCode) {
 | 
			
		||||
        super(responseCode.getDescription());
 | 
			
		||||
        this.responseCode = responseCode;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public ApiException(ApiResponseCode responseCode, String message) {
 | 
			
		||||
        super(message);
 | 
			
		||||
        this.responseCode = responseCode;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public ApiException(ApiResponseCode responseCode, Throwable cause) {
 | 
			
		||||
        super(responseCode.getDescription(), cause);
 | 
			
		||||
        this.responseCode = responseCode;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -14,8 +14,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
 | 
			
		||||
import jakarta.servlet.ServletException;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
import com.bio.bio_backend.global.dto.CustomApiResponse;
 | 
			
		||||
import com.bio.bio_backend.global.utils.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.global.dto.ApiResponseDto;
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
 | 
			
		||||
@@ -29,25 +29,21 @@ public class CustomAuthenticationFailureHandler implements AuthenticationFailure
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
 | 
			
		||||
 | 
			
		||||
        log.info("exception : " + exception.toString());
 | 
			
		||||
 | 
			
		||||
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
 | 
			
		||||
        response.setCharacterEncoding("UTF-8");
 | 
			
		||||
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
 | 
			
		||||
 | 
			
		||||
        CustomApiResponse<String> apiResponse;
 | 
			
		||||
        ApiResponseDto<String> apiResponse;
 | 
			
		||||
        if (exception instanceof UsernameNotFoundException) {
 | 
			
		||||
            apiResponse = CustomApiResponse.fail(ApiResponseCode.USER_NOT_FOUND, null);
 | 
			
		||||
            apiResponse = ApiResponseDto.fail(ApiResponseCode.USER_NOT_FOUND);
 | 
			
		||||
        } else if (exception instanceof BadCredentialsException) {
 | 
			
		||||
            apiResponse = CustomApiResponse.fail(ApiResponseCode.AUTHENTICATION_FAILED, null);
 | 
			
		||||
            apiResponse = ApiResponseDto.fail(ApiResponseCode.COMMON_UNAUTHORIZED);
 | 
			
		||||
        } else {
 | 
			
		||||
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
 | 
			
		||||
            apiResponse = CustomApiResponse.fail(ApiResponseCode.INTERNAL_SERVER_ERROR, null);
 | 
			
		||||
            apiResponse = ApiResponseDto.fail(ApiResponseCode.COMMON_INTERNAL_SERVER_ERROR);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        String jsonResponse = objectMapper.writeValueAsString(apiResponse);
 | 
			
		||||
        response.getWriter().write(jsonResponse);
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -1,80 +1,44 @@
 | 
			
		||||
package com.bio.bio_backend.global.exception;
 | 
			
		||||
 | 
			
		||||
import java.util.Objects;
 | 
			
		||||
 | 
			
		||||
import org.springframework.http.converter.HttpMessageNotReadableException;
 | 
			
		||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
 | 
			
		||||
import org.springframework.web.bind.annotation.ExceptionHandler;
 | 
			
		||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
 | 
			
		||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
 | 
			
		||||
import org.springframework.web.bind.MethodArgumentNotValidException;
 | 
			
		||||
 | 
			
		||||
import com.fasterxml.jackson.core.JsonProcessingException;
 | 
			
		||||
 | 
			
		||||
import io.jsonwebtoken.ExpiredJwtException;
 | 
			
		||||
import io.jsonwebtoken.JwtException;
 | 
			
		||||
import io.jsonwebtoken.MalformedJwtException;
 | 
			
		||||
import io.jsonwebtoken.security.SignatureException;
 | 
			
		||||
import com.bio.bio_backend.global.dto.CustomApiResponse;
 | 
			
		||||
import com.bio.bio_backend.global.utils.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.exception.UserDuplicateException;
 | 
			
		||||
import com.bio.bio_backend.global.dto.ApiResponseDto;
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
import org.springframework.http.HttpStatus;
 | 
			
		||||
import org.springframework.http.ResponseEntity;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
 | 
			
		||||
@RestControllerAdvice
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class GlobalExceptionHandler {
 | 
			
		||||
    @ExceptionHandler(HttpMessageNotReadableException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
 | 
			
		||||
        if (Objects.requireNonNull(e.getMessage()).contains("JSON parse error")) {
 | 
			
		||||
            return CustomApiResponse.fail(ApiResponseCode.COMMON_FORMAT_WRONG, null);
 | 
			
		||||
        }
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.COMMON_BAD_REQUEST, null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.COMMON_METHOD_NOT_ALLOWED, null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(NoResourceFoundException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleNoResourceFoundException(NoResourceFoundException e){
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.COMMON_NOT_FOUND, null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(IllegalArgumentException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleIllegalArgumentException(IllegalArgumentException e){
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.ARGUMENT_NOT_VALID, null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(IndexOutOfBoundsException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleIndexOutOfBoundsException(IndexOutOfBoundsException e){
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.INDEX_OUT_OF_BOUND, null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(SignatureException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleSignatureException(SignatureException e) {
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.JWT_SIGNATURE_MISMATCH, null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(MalformedJwtException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleMalformedJwtException(MalformedJwtException e) {
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.JWT_SIGNATURE_MISMATCH, null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(JwtException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleJwtExceptionException(JwtException e) {
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.JWT_TOKEN_NULL, null);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(ExpiredJwtException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleExpiredJwtException(ExpiredJwtException e) {
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.JWT_TOKEN_EXPIRED, null);
 | 
			
		||||
    @ExceptionHandler(ApiException.class)
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<Void>> handleApiException(ApiException e) {
 | 
			
		||||
        ApiResponseDto<Void> response = ApiResponseDto.fail(e.getResponseCode());
 | 
			
		||||
        return ResponseEntity.status(e.getResponseCode().getStatusCode()).body(response);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @ExceptionHandler(JsonProcessingException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleExpiredJwtException(JsonProcessingException e) {
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.JSON_PROCESSING_EXCEPTION, null);
 | 
			
		||||
    @ExceptionHandler(MethodArgumentNotValidException.class)
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<Object>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
 | 
			
		||||
        // 검증 실패한 필드들의 상세 오류 정보 추출
 | 
			
		||||
        var errors = e.getBindingResult().getFieldErrors().stream()
 | 
			
		||||
            .map(error -> new ValidationError(error.getField(), error.getDefaultMessage()))
 | 
			
		||||
            .toList();
 | 
			
		||||
        
 | 
			
		||||
        ApiResponseDto<Object> response = ApiResponseDto.fail(ApiResponseCode.COMMON_ARGUMENT_NOT_VALID, errors);
 | 
			
		||||
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @ExceptionHandler(UserDuplicateException.class)
 | 
			
		||||
    public CustomApiResponse<Void> handleUserDuplicateException(UserDuplicateException e) {
 | 
			
		||||
        return CustomApiResponse.fail(ApiResponseCode.USER_ID_DUPLICATE, null);
 | 
			
		||||
 | 
			
		||||
    // 검증 오류 상세 정보를 위한 내부 클래스
 | 
			
		||||
    private record ValidationError(String field, String message) {}
 | 
			
		||||
 | 
			
		||||
    @ExceptionHandler(Exception.class)
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<Void>> handleException(Exception e) {
 | 
			
		||||
        log.error("Unexpected error occurred", e);
 | 
			
		||||
        
 | 
			
		||||
        ApiResponseDto<Void> response = ApiResponseDto.fail(ApiResponseCode.COMMON_INTERNAL_SERVER_ERROR);
 | 
			
		||||
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -1,42 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.global.exception;
 | 
			
		||||
 | 
			
		||||
import java.io.IOException;
 | 
			
		||||
 | 
			
		||||
import org.springframework.beans.factory.annotation.Qualifier;
 | 
			
		||||
import org.springframework.http.MediaType;
 | 
			
		||||
import org.springframework.security.access.AccessDeniedException;
 | 
			
		||||
import org.springframework.security.web.access.AccessDeniedHandler;
 | 
			
		||||
import org.springframework.stereotype.Component;
 | 
			
		||||
import org.springframework.web.servlet.HandlerExceptionResolver;
 | 
			
		||||
 | 
			
		||||
import com.fasterxml.jackson.databind.ObjectMapper;
 | 
			
		||||
 | 
			
		||||
import jakarta.servlet.ServletException;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
import com.bio.bio_backend.global.dto.CustomApiResponse;
 | 
			
		||||
import com.bio.bio_backend.global.utils.ApiResponseCode;
 | 
			
		||||
 | 
			
		||||
@Component
 | 
			
		||||
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
 | 
			
		||||
    private final HandlerExceptionResolver resolver;
 | 
			
		||||
 | 
			
		||||
    public JwtAccessDeniedHandler(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
 | 
			
		||||
        this.resolver = resolver;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
 | 
			
		||||
 | 
			
		||||
        Exception exception = (Exception) request.getAttribute("exception");
 | 
			
		||||
 | 
			
		||||
        if (exception != null) {
 | 
			
		||||
            resolver.resolveException(request, response, null, exception);
 | 
			
		||||
        } else {
 | 
			
		||||
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
 | 
			
		||||
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
 | 
			
		||||
            new ObjectMapper().writeValue(response.getWriter(),
 | 
			
		||||
                    CustomApiResponse.fail(ApiResponseCode.COMMON_FORBIDDEN, null));
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,35 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.global.exception;
 | 
			
		||||
 | 
			
		||||
import jakarta.servlet.ServletException;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.springframework.beans.factory.annotation.Qualifier;
 | 
			
		||||
import org.springframework.security.core.AuthenticationException;
 | 
			
		||||
import org.springframework.security.web.AuthenticationEntryPoint;
 | 
			
		||||
import org.springframework.stereotype.Component;
 | 
			
		||||
import org.springframework.web.servlet.HandlerExceptionResolver;
 | 
			
		||||
 | 
			
		||||
import java.io.IOException;
 | 
			
		||||
 | 
			
		||||
@Component
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
 | 
			
		||||
    private final HandlerExceptionResolver resolver;
 | 
			
		||||
 | 
			
		||||
    public JwtAuthenticationEntryPoint(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
 | 
			
		||||
        this.resolver = resolver;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
 | 
			
		||||
 | 
			
		||||
        Exception exception = (Exception) request.getAttribute("exception");
 | 
			
		||||
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
 | 
			
		||||
 | 
			
		||||
        if (exception == null) {
 | 
			
		||||
            return;
 | 
			
		||||
        }
 | 
			
		||||
        resolver.resolveException(request, response, null, exception);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,57 +1,109 @@
 | 
			
		||||
//package com.bio.bio_backend.filter;
 | 
			
		||||
//
 | 
			
		||||
//import java.io.IOException;
 | 
			
		||||
//import java.sql.Timestamp;
 | 
			
		||||
//
 | 
			
		||||
//import org.springframework.security.core.Authentication;
 | 
			
		||||
//import org.springframework.security.core.context.SecurityContextHolder;
 | 
			
		||||
//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 com.bio.bio_backend.domain.common.dto.AccessLogDTO;
 | 
			
		||||
//import com.bio.bio_backend.domain.common.service.AccessLogService;
 | 
			
		||||
//import com.bio.bio_backend.domain.user.member.dto.MemberDTO;
 | 
			
		||||
//import com.bio.bio_backend.global.utils.HttpUtils;
 | 
			
		||||
//
 | 
			
		||||
//public class HttpLoggingFilter extends OncePerRequestFilter {
 | 
			
		||||
//
 | 
			
		||||
////	private AccessLogService accessLogService;
 | 
			
		||||
//	private HttpUtils httpUtils;
 | 
			
		||||
//
 | 
			
		||||
//	public HttpLoggingFilter(AccessLogService accessLogService, HttpUtils httpUtils) {
 | 
			
		||||
//		this.accessLogService = accessLogService;
 | 
			
		||||
//		this.httpUtils = httpUtils;
 | 
			
		||||
//	}
 | 
			
		||||
//
 | 
			
		||||
//	@Override
 | 
			
		||||
//	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
 | 
			
		||||
//			throws ServletException, IOException {
 | 
			
		||||
//		// Request 요청 시간
 | 
			
		||||
//		Long startedAt = System.currentTimeMillis();
 | 
			
		||||
//		filterChain.doFilter(request, response);
 | 
			
		||||
//		Long finishedAt = System.currentTimeMillis();
 | 
			
		||||
//
 | 
			
		||||
//		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
 | 
			
		||||
//		MemberDTO member = null;
 | 
			
		||||
//		if(auth != null && auth.getPrincipal() instanceof MemberDTO) {
 | 
			
		||||
//			member = (MemberDTO) auth.getPrincipal();
 | 
			
		||||
//		}
 | 
			
		||||
//
 | 
			
		||||
//		AccessLogDTO log = new AccessLogDTO();
 | 
			
		||||
//		log.setMbrSeq(member == null ? -1 : member.getSeq());
 | 
			
		||||
//		log.setType(httpUtils.getResponseType(response.getContentType()));
 | 
			
		||||
//		log.setMethod(request.getMethod());
 | 
			
		||||
//		log.setIp(httpUtils.getClientIp());
 | 
			
		||||
//		log.setUri(request.getRequestURI());
 | 
			
		||||
//		log.setReqAt(new Timestamp(startedAt));
 | 
			
		||||
//		log.setResAt(new Timestamp(finishedAt));
 | 
			
		||||
//		log.setElapsedTime(finishedAt - startedAt);
 | 
			
		||||
//		log.setResStatus(String.valueOf(response.getStatus()));
 | 
			
		||||
//
 | 
			
		||||
//		accessLogService.createAccessLog(log);
 | 
			
		||||
//	}
 | 
			
		||||
//
 | 
			
		||||
//}
 | 
			
		||||
package com.bio.bio_backend.global.filter;
 | 
			
		||||
 | 
			
		||||
import jakarta.servlet.FilterChain;
 | 
			
		||||
import jakarta.servlet.ServletException;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.springframework.stereotype.Component;
 | 
			
		||||
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;
 | 
			
		||||
 | 
			
		||||
@Slf4j
 | 
			
		||||
@Component
 | 
			
		||||
public class HttpLoggingFilter extends OncePerRequestFilter {
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
 | 
			
		||||
            throws ServletException, IOException {
 | 
			
		||||
        
 | 
			
		||||
        long startTime = System.currentTimeMillis();
 | 
			
		||||
        
 | 
			
		||||
        // 요청 정보 로깅 (IP 정보 제거)
 | 
			
		||||
        log.info("HTTP REQUEST: {} {} | Headers: {} | Body: {}", 
 | 
			
		||||
            request.getMethod(), request.getRequestURI(),
 | 
			
		||||
            getRequestHeaders(request), getRequestBody(request));
 | 
			
		||||
        
 | 
			
		||||
        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
 | 
			
		||||
        ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);
 | 
			
		||||
        
 | 
			
		||||
        try {
 | 
			
		||||
            filterChain.doFilter(wrappedRequest, wrappedResponse);
 | 
			
		||||
        } finally {
 | 
			
		||||
            long duration = System.currentTimeMillis() - startTime;
 | 
			
		||||
            
 | 
			
		||||
            // 응답 정보 로깅
 | 
			
		||||
            log.info("HTTP RESPONSE: {} {} | Status: {} | Time: {}ms | Headers: {} | Body: {}", 
 | 
			
		||||
                request.getMethod(), request.getRequestURI(),
 | 
			
		||||
                wrappedResponse.getStatus(), duration, getResponseHeaders(wrappedResponse), getResponseBody(wrappedResponse));
 | 
			
		||||
            
 | 
			
		||||
            wrappedResponse.copyBodyToResponse();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    // 민감 정보 마스킹 메서드
 | 
			
		||||
    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\":\"***\"");
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    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 ***" : "***");
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        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";
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    @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");
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -1,22 +1,20 @@
 | 
			
		||||
package com.bio.bio_backend.global.security;
 | 
			
		||||
package com.bio.bio_backend.global.filter;
 | 
			
		||||
 | 
			
		||||
import com.fasterxml.jackson.databind.ObjectMapper;
 | 
			
		||||
import jakarta.servlet.FilterChain;
 | 
			
		||||
import jakarta.servlet.ServletException;
 | 
			
		||||
import jakarta.servlet.http.Cookie;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
import com.bio.bio_backend.global.dto.CustomApiResponse;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.LoginRequestDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.LoginResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.dto.MemberDto;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.service.MemberService;
 | 
			
		||||
import com.bio.bio_backend.global.utils.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.global.dto.ApiResponseDto;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.dto.LoginRequestDto;
 | 
			
		||||
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.service.MemberService;
 | 
			
		||||
import com.bio.bio_backend.global.constants.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.global.utils.JwtUtils;
 | 
			
		||||
import com.bio.bio_backend.global.utils.HttpUtils;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.SneakyThrows;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.springframework.core.env.Environment;
 | 
			
		||||
import org.springframework.http.HttpStatus;
 | 
			
		||||
import org.springframework.http.MediaType;
 | 
			
		||||
import org.springframework.security.authentication.AuthenticationManager;
 | 
			
		||||
@@ -31,38 +29,30 @@ import org.springframework.security.core.userdetails.UserDetails;
 | 
			
		||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
 | 
			
		||||
 | 
			
		||||
import java.io.IOException;
 | 
			
		||||
import java.sql.Timestamp;
 | 
			
		||||
import java.time.LocalDateTime;
 | 
			
		||||
import java.util.Objects;
 | 
			
		||||
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
 | 
			
		||||
public class JwtTokenIssuanceFilter extends UsernamePasswordAuthenticationFilter {
 | 
			
		||||
 | 
			
		||||
    private final AuthenticationManager authenticationManager;
 | 
			
		||||
    private final MemberService memberService;
 | 
			
		||||
    private final JwtUtils jwtUtils;
 | 
			
		||||
    private final Environment env;
 | 
			
		||||
    private final ObjectMapper objectMapper;
 | 
			
		||||
    private final MemberService memberService;
 | 
			
		||||
    private final HttpUtils httpUtils;
 | 
			
		||||
 | 
			
		||||
    // 사용자 login 인증 처리
 | 
			
		||||
    @SneakyThrows
 | 
			
		||||
    @Override
 | 
			
		||||
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
 | 
			
		||||
            throws AuthenticationException {
 | 
			
		||||
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
 | 
			
		||||
        try {
 | 
			
		||||
            LoginRequestDto requestDto = new ObjectMapper().readValue(request.getInputStream(), LoginRequestDto.class);
 | 
			
		||||
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
 | 
			
		||||
                requestDto.getUserId(), requestDto.getPassword());
 | 
			
		||||
 | 
			
		||||
        LoginRequestDto requestDto = new ObjectMapper().readValue(request.getInputStream(), LoginRequestDto.class);
 | 
			
		||||
 | 
			
		||||
//        UsernamePasswordAuthenticationToken authToken;
 | 
			
		||||
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(requestDto.getUserId(), requestDto.getPassword());
 | 
			
		||||
 | 
			
		||||
        /*
 | 
			
		||||
        if (req.getLoginLogFlag() == 1) {
 | 
			
		||||
            authToken = new UsernamePasswordAuthenticationToken("admin2", "test123!"); // 비밀번호는 실제 비밀번호로 설정해야 함
 | 
			
		||||
        } else {
 | 
			
		||||
            throw new AuthenticationServiceException("login fail");
 | 
			
		||||
            return authenticationManager.authenticate(authToken);
 | 
			
		||||
        } catch (IOException e) {
 | 
			
		||||
            throw new AuthenticationServiceException("로그인 요청 파싱 중 오류가 발생했습니다", e);
 | 
			
		||||
        }
 | 
			
		||||
         */
 | 
			
		||||
        return authenticationManager.authenticate(authToken);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // 사용자 인증 성공 후 token 발급
 | 
			
		||||
@@ -71,36 +61,22 @@ public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilte
 | 
			
		||||
                                            FilterChain chain, Authentication authResult) throws IOException, ServletException {
 | 
			
		||||
 | 
			
		||||
        UserDetails userDetails = (UserDetails) authResult.getPrincipal();
 | 
			
		||||
 | 
			
		||||
        MemberDto member = (MemberDto) userDetails;
 | 
			
		||||
        
 | 
			
		||||
        String accessToken = jwtUtils.generateToken(member.getUserId(), member.getRole().getValue(),
 | 
			
		||||
                Long.parseLong(Objects.requireNonNull(env.getProperty("token.expiration_time_access"))));
 | 
			
		||||
 | 
			
		||||
        String refreshToken = jwtUtils.generateToken(member.getUserId(), member.getRole().getValue(),
 | 
			
		||||
                Long.parseLong(Objects.requireNonNull(env.getProperty("token.expiration_time_refresh"))));
 | 
			
		||||
        // 토큰 생성
 | 
			
		||||
        String accessToken = jwtUtils.createAccessToken(member.getUserId(), member.getRole().getValue());
 | 
			
		||||
        String refreshToken = jwtUtils.createRefreshToken(member.getUserId(), member.getRole().getValue());
 | 
			
		||||
        
 | 
			
		||||
 | 
			
		||||
        member.setRefreshToken(refreshToken);
 | 
			
		||||
        member.setLoginIp(httpUtils.getClientIp());
 | 
			
		||||
        member.setLastLoginAt(LocalDateTime.now());
 | 
			
		||||
 | 
			
		||||
        memberService.updateRefreshToken(member);
 | 
			
		||||
        memberService.updateMember(member);
 | 
			
		||||
 | 
			
		||||
        // Refresh 토큰 쿠키 저장
 | 
			
		||||
        Cookie refreshTokenCookie = new Cookie("RefreshToken", refreshToken);
 | 
			
		||||
        refreshTokenCookie.setHttpOnly(true);
 | 
			
		||||
        refreshTokenCookie.setSecure(false);
 | 
			
		||||
        refreshTokenCookie.setPath("/");
 | 
			
		||||
        refreshTokenCookie.setMaxAge(Integer.parseInt(env.getProperty("token.expiration_time_refresh")));
 | 
			
		||||
        jwtUtils.setRefreshTokenCookie(response, refreshToken);
 | 
			
		||||
 | 
			
		||||
        // JWT 토큰 전달
 | 
			
		||||
        // Access 토큰 전달
 | 
			
		||||
        response.setHeader("Authorization", "Bearer " + accessToken);
 | 
			
		||||
//        response.addCookie(refreshTokenCookie);
 | 
			
		||||
        response.addHeader("Set-Cookie", 
 | 
			
		||||
        	    String.format("%s=%s; HttpOnly; Secure; Path=/; Max-Age=%d; SameSite=None", 
 | 
			
		||||
        	    refreshTokenCookie.getName(), 
 | 
			
		||||
        	    refreshTokenCookie.getValue(), 
 | 
			
		||||
        	    refreshTokenCookie.getMaxAge()));
 | 
			
		||||
 | 
			
		||||
        SecurityContextHolderStrategy contextHolder = SecurityContextHolder.getContextHolderStrategy();
 | 
			
		||||
        SecurityContext context = contextHolder.createEmptyContext();
 | 
			
		||||
@@ -114,8 +90,10 @@ public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilte
 | 
			
		||||
 | 
			
		||||
        // login 성공 메시지 전송
 | 
			
		||||
        response.setStatus(HttpStatus.OK.value());
 | 
			
		||||
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
 | 
			
		||||
        new ObjectMapper().writeValue(response.getWriter(),
 | 
			
		||||
                CustomApiResponse.success(ApiResponseCode.LOGIN_SUCCESSFUL, memberData));
 | 
			
		||||
        response.setContentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8");
 | 
			
		||||
        objectMapper.writeValue(
 | 
			
		||||
            response.getWriter(),
 | 
			
		||||
            ApiResponseDto.success(ApiResponseCode.LOGIN_SUCCESSFUL, memberData)
 | 
			
		||||
        );
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -0,0 +1,131 @@
 | 
			
		||||
package com.bio.bio_backend.global.filter;
 | 
			
		||||
 | 
			
		||||
import java.io.IOException;
 | 
			
		||||
import java.util.Objects;
 | 
			
		||||
 | 
			
		||||
import org.springframework.core.env.Environment;
 | 
			
		||||
import org.springframework.http.MediaType;
 | 
			
		||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 | 
			
		||||
import org.springframework.security.core.context.SecurityContextHolder;
 | 
			
		||||
import org.springframework.security.core.userdetails.UserDetails;
 | 
			
		||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
 | 
			
		||||
import org.springframework.web.filter.OncePerRequestFilter;
 | 
			
		||||
 | 
			
		||||
import com.fasterxml.jackson.databind.ObjectMapper;
 | 
			
		||||
 | 
			
		||||
import jakarta.servlet.FilterChain;
 | 
			
		||||
import jakarta.servlet.ServletException;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
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;
 | 
			
		||||
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class JwtTokenValidationFilter extends OncePerRequestFilter {
 | 
			
		||||
 | 
			
		||||
    private final JwtUtils jwtUtils;
 | 
			
		||||
    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,
 | 
			
		||||
                                    FilterChain filterChain) throws ServletException, IOException {
 | 
			
		||||
 | 
			
		||||
        log.debug("JWT 토큰 검증 필터 실행 - URI: {}", request.getRequestURI());
 | 
			
		||||
 | 
			
		||||
        String accessToken = jwtUtils.extractAccessJwtFromRequest(request);
 | 
			
		||||
        String refreshToken = jwtUtils.extractRefreshJwtFromCookie(request);
 | 
			
		||||
 | 
			
		||||
        // Access Token이 있고 유효한 경우
 | 
			
		||||
        if (accessToken != null && jwtUtils.validateAccessToken(accessToken)) {
 | 
			
		||||
            String username = jwtUtils.extractUsername(accessToken);
 | 
			
		||||
            UserDetails userDetails = memberService.loadUserByUsername(username);
 | 
			
		||||
 | 
			
		||||
            if (userDetails != null) {
 | 
			
		||||
                UsernamePasswordAuthenticationToken authentication =
 | 
			
		||||
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
 | 
			
		||||
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
 | 
			
		||||
                SecurityContextHolder.getContext().setAuthentication(authentication);
 | 
			
		||||
                
 | 
			
		||||
                log.debug("Access Token 인증 성공: {}", username);
 | 
			
		||||
                filterChain.doFilter(request, response);
 | 
			
		||||
                return;
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // Access Token이 없거나 만료된 경우, Refresh Token으로 갱신 시도
 | 
			
		||||
        if (refreshToken != null) {
 | 
			
		||||
            // 1. Refresh Token 유효성 검증
 | 
			
		||||
            if (!jwtUtils.isValidRefreshToken(refreshToken)) {
 | 
			
		||||
                log.warn("Refresh Token이 유효하지 않습니다. URI: {}", request.getRequestURI());
 | 
			
		||||
                sendJsonResponse(response, ApiResponseDto.fail(ApiResponseCode.JWT_TOKEN_EXPIRED));
 | 
			
		||||
                return;
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            // 2. IP 주소 검증
 | 
			
		||||
            if (!jwtUtils.isValidClientIp(refreshToken, request.getRemoteAddr())) {
 | 
			
		||||
                log.warn("클라이언트 IP 주소가 일치하지 않습니다. URI: {}, IP: {}", 
 | 
			
		||||
                        request.getRequestURI(), request.getRemoteAddr());
 | 
			
		||||
                sendJsonResponse(response, ApiResponseDto.fail(ApiResponseCode.INVALID_CLIENT_IP));
 | 
			
		||||
                return;
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            // 모든 검증을 통과한 경우 토큰 갱신 진행
 | 
			
		||||
            String username = jwtUtils.extractUsername(refreshToken);
 | 
			
		||||
            String role = jwtUtils.extractRole(refreshToken);
 | 
			
		||||
            
 | 
			
		||||
            // 새로운 Access Token 생성
 | 
			
		||||
            String newAccessToken = jwtUtils.generateToken(username, role,
 | 
			
		||||
                    Long.parseLong(Objects.requireNonNull(env.getProperty("token.expiration_time_access"))));
 | 
			
		||||
            
 | 
			
		||||
            // 새로운 Access Token을 응답 헤더에 설정
 | 
			
		||||
            response.setHeader("Authorization", "Bearer " + newAccessToken);
 | 
			
		||||
            
 | 
			
		||||
            // Refresh Token 갱신
 | 
			
		||||
            String newRefreshToken = jwtUtils.refreshTokens(username, role);
 | 
			
		||||
            jwtUtils.setRefreshTokenCookie(response, newRefreshToken);
 | 
			
		||||
            
 | 
			
		||||
            // 인증 정보 설정
 | 
			
		||||
            UserDetails userDetails = memberService.loadUserByUsername(username);
 | 
			
		||||
            if (userDetails != null) {
 | 
			
		||||
                UsernamePasswordAuthenticationToken authentication =
 | 
			
		||||
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
 | 
			
		||||
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
 | 
			
		||||
                SecurityContextHolder.getContext().setAuthentication(authentication);
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            log.info("토큰 자동 갱신 성공: {}", username);
 | 
			
		||||
            filterChain.doFilter(request, response);
 | 
			
		||||
            return;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // 토큰이 없거나 모두 유효하지 않은 경우
 | 
			
		||||
        log.warn("유효한 JWT 토큰이 없습니다. URI: {}", request.getRequestURI());
 | 
			
		||||
        sendJsonResponse(response, ApiResponseDto.fail(ApiResponseCode.JWT_TOKEN_NULL));
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private void sendJsonResponse(HttpServletResponse response, ApiResponseDto<?> apiResponse) throws IOException {
 | 
			
		||||
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
 | 
			
		||||
        response.setCharacterEncoding("UTF-8");
 | 
			
		||||
        response.setStatus(apiResponse.getCode());
 | 
			
		||||
 | 
			
		||||
        ObjectMapper objectMapper = new ObjectMapper();
 | 
			
		||||
        String jsonResponse = objectMapper.writeValueAsString(apiResponse);
 | 
			
		||||
        response.getWriter().write(jsonResponse);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,11 +1,9 @@
 | 
			
		||||
package com.bio.bio_backend.global.security;
 | 
			
		||||
package com.bio.bio_backend.global.filter;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
import java.util.Arrays;
 | 
			
		||||
import java.util.regex.Pattern;
 | 
			
		||||
 | 
			
		||||
import org.springframework.beans.factory.annotation.Autowired;
 | 
			
		||||
import org.springframework.context.annotation.Bean;
 | 
			
		||||
import org.springframework.stereotype.Component;
 | 
			
		||||
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
@@ -1,104 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.global.security;
 | 
			
		||||
 | 
			
		||||
import java.io.IOException;
 | 
			
		||||
import java.util.Arrays;
 | 
			
		||||
import java.util.Objects;
 | 
			
		||||
 | 
			
		||||
import org.springframework.beans.factory.annotation.Autowired;
 | 
			
		||||
import org.springframework.core.env.Environment;
 | 
			
		||||
import org.springframework.http.MediaType;
 | 
			
		||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 | 
			
		||||
import org.springframework.security.core.context.SecurityContextHolder;
 | 
			
		||||
import org.springframework.security.core.userdetails.UserDetails;
 | 
			
		||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
 | 
			
		||||
import org.springframework.web.filter.OncePerRequestFilter;
 | 
			
		||||
 | 
			
		||||
import com.fasterxml.jackson.databind.ObjectMapper;
 | 
			
		||||
 | 
			
		||||
import io.jsonwebtoken.ExpiredJwtException;
 | 
			
		||||
import jakarta.servlet.FilterChain;
 | 
			
		||||
import jakarta.servlet.ServletException;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
import com.bio.bio_backend.global.dto.CustomApiResponse;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.service.MemberService;
 | 
			
		||||
import com.bio.bio_backend.global.utils.ApiResponseCode;
 | 
			
		||||
import com.bio.bio_backend.global.utils.JwtUtils;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@Slf4j
 | 
			
		||||
public class JwtTokenFilter extends OncePerRequestFilter {
 | 
			
		||||
 | 
			
		||||
    private final JwtUtils jwtUtils;
 | 
			
		||||
    private final MemberService memberService;
 | 
			
		||||
    private final Environment env;
 | 
			
		||||
 | 
			
		||||
    private final UriAllowFilter uriAllowFilter;
 | 
			
		||||
    
 | 
			
		||||
    @Override
 | 
			
		||||
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
 | 
			
		||||
    	return uriAllowFilter.authExceptionAllow(request);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
 | 
			
		||||
                                    FilterChain filterChain) throws ServletException, IOException {
 | 
			
		||||
 | 
			
		||||
        String accessToken = jwtUtils.extractAccessJwtFromRequest(request);
 | 
			
		||||
        String refreshToken = jwtUtils.extractRefreshJwtFromCookie(request);
 | 
			
		||||
 | 
			
		||||
        if(accessToken == null){
 | 
			
		||||
            sendJsonResponse(response, CustomApiResponse.fail(ApiResponseCode.JWT_TOKEN_NULL, null));
 | 
			
		||||
            return;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        try {
 | 
			
		||||
            // 토큰 유효성 검사
 | 
			
		||||
            try {
 | 
			
		||||
                if (jwtUtils.validateAccessToken(accessToken)) {
 | 
			
		||||
                    String username = jwtUtils.extractUsername(accessToken);
 | 
			
		||||
                    UserDetails userDetails = memberService.loadUserByUsername(username);
 | 
			
		||||
 | 
			
		||||
                    if (userDetails != null) {
 | 
			
		||||
                        UsernamePasswordAuthenticationToken authentication =
 | 
			
		||||
                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
 | 
			
		||||
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
 | 
			
		||||
                        SecurityContextHolder.getContext().setAuthentication(authentication);
 | 
			
		||||
                        filterChain.doFilter(request, response);
 | 
			
		||||
                        return;
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
            } catch (ExpiredJwtException ignored) {
 | 
			
		||||
                // Access Token이 만료된 경우에만 ignored >> Refresh Token 검증 수행
 | 
			
		||||
            }
 | 
			
		||||
            // Refresh Token 유효성 검사
 | 
			
		||||
            if (refreshToken != null && jwtUtils.validateRefreshToken(refreshToken)) {
 | 
			
		||||
                String username = jwtUtils.extractUsername(refreshToken);
 | 
			
		||||
                String role = (String) jwtUtils.extractAllClaims(refreshToken).get("role");
 | 
			
		||||
                String newAccessToken = jwtUtils.generateToken(username, role,
 | 
			
		||||
                        Long.parseLong(Objects.requireNonNull(env.getProperty("token.expiration_time_access"))));
 | 
			
		||||
                // 새로운 Access Token을 응답 헤더에 설정
 | 
			
		||||
                response.setHeader("Authorization", "Bearer " + newAccessToken);
 | 
			
		||||
                filterChain.doFilter(request, response);
 | 
			
		||||
            } else {
 | 
			
		||||
                sendJsonResponse(response, CustomApiResponse.fail(ApiResponseCode.All_TOKEN_INVALID, null));
 | 
			
		||||
            }
 | 
			
		||||
        } catch (Exception e) {
 | 
			
		||||
            request.setAttribute("exception", e);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        filterChain.doFilter(request, response);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private void sendJsonResponse(HttpServletResponse response, CustomApiResponse<?> apiResponse) throws IOException {
 | 
			
		||||
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
 | 
			
		||||
        response.setCharacterEncoding("UTF-8");
 | 
			
		||||
        response.setStatus(apiResponse.getCode());
 | 
			
		||||
 | 
			
		||||
        ObjectMapper objectMapper = new ObjectMapper();
 | 
			
		||||
        String jsonResponse = objectMapper.writeValueAsString(apiResponse);
 | 
			
		||||
        response.getWriter().write(jsonResponse);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,5 +1,7 @@
 | 
			
		||||
package com.bio.bio_backend.global.security;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.global.filter.JwtTokenIssuanceFilter;
 | 
			
		||||
import com.bio.bio_backend.global.filter.JwtTokenValidationFilter;
 | 
			
		||||
import org.springframework.context.annotation.Bean;
 | 
			
		||||
import org.springframework.context.annotation.Configuration;
 | 
			
		||||
import org.springframework.core.env.Environment;
 | 
			
		||||
@@ -8,22 +10,19 @@ import org.springframework.security.config.annotation.authentication.builders.Au
 | 
			
		||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
 | 
			
		||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 | 
			
		||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
 | 
			
		||||
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;
 | 
			
		||||
 | 
			
		||||
import jakarta.servlet.Filter;
 | 
			
		||||
//import com.bio.bio_backend.domain.common.service.AccessLogService;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.service.MemberService;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.service.MemberService;
 | 
			
		||||
import com.bio.bio_backend.global.exception.CustomAuthenticationFailureHandler;
 | 
			
		||||
import com.bio.bio_backend.global.exception.JwtAccessDeniedHandler;
 | 
			
		||||
import com.bio.bio_backend.global.exception.JwtAuthenticationEntryPoint;
 | 
			
		||||
//import com.bio.bio_backend.global.filter.HttpLoggingFilter;
 | 
			
		||||
import com.bio.bio_backend.global.utils.HttpUtils;
 | 
			
		||||
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
 | 
			
		||||
@@ -34,27 +33,23 @@ public class WebSecurity {
 | 
			
		||||
    private final MemberService memberService;
 | 
			
		||||
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
 | 
			
		||||
    private final JwtUtils jwtUtils;
 | 
			
		||||
//    private final AccessLogService accessLogService;
 | 
			
		||||
    private final CorsFilter corsFilter;
 | 
			
		||||
    private final ObjectMapper objectMapper;
 | 
			
		||||
    private final HttpUtils httpUtils;
 | 
			
		||||
    private final Environment env;
 | 
			
		||||
    private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
 | 
			
		||||
    private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
 | 
			
		||||
    
 | 
			
		||||
    private final UriAllowFilter uriAllowFilter;
 | 
			
		||||
    
 | 
			
		||||
    private final SecurityPathConfig securityPathConfig;
 | 
			
		||||
    private final HttpUtils httpUtils;
 | 
			
		||||
 | 
			
		||||
    private JwtAuthenticationFilter getJwtAuthenticationFilter(AuthenticationManager authenticationManager) throws Exception {
 | 
			
		||||
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter(authenticationManager, memberService, jwtUtils, env);
 | 
			
		||||
        filter.setFilterProcessesUrl("/login"); // 로그인 EndPoint
 | 
			
		||||
    private JwtTokenIssuanceFilter getJwtTokenIssuanceFilter(AuthenticationManager authenticationManager) throws Exception {
 | 
			
		||||
        JwtTokenIssuanceFilter filter = new JwtTokenIssuanceFilter(authenticationManager, jwtUtils, objectMapper, memberService, httpUtils);
 | 
			
		||||
        filter.setFilterProcessesUrl("/login");
 | 
			
		||||
        filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler(objectMapper));
 | 
			
		||||
        return filter;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private Filter getJwtTokenFilter() {
 | 
			
		||||
        return new JwtTokenFilter(jwtUtils, memberService, env, uriAllowFilter);
 | 
			
		||||
    private JwtTokenValidationFilter getJwtTokenValidationFilter() {
 | 
			
		||||
        return new JwtTokenValidationFilter(jwtUtils, memberService, env, securityPathConfig);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
    
 | 
			
		||||
    @Bean
 | 
			
		||||
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
 | 
			
		||||
@@ -66,35 +61,25 @@ public class WebSecurity {
 | 
			
		||||
 | 
			
		||||
        AuthenticationManager authenticationManager = authenticationManagerBuilder.build();
 | 
			
		||||
 | 
			
		||||
        // 설정 파일에서 허용할 경로 가져오기
 | 
			
		||||
        String[] permitAllPaths = securityPathConfig.getPermitAllPaths().toArray(new String[0]);
 | 
			
		||||
 | 
			
		||||
        http.csrf(AbstractHttpConfigurer::disable)          //csrf 비활성화
 | 
			
		||||
                .authorizeHttpRequests(request ->               //request 허용 설정
 | 
			
		||||
                        request
 | 
			
		||||
                        	.anyRequest().permitAll()  // 모든 요청 허용
 | 
			
		||||
//                    		.requestMatchers("/ws/**").permitAll()
 | 
			
		||||
//                            .requestMatchers("/admin/**", "/join").hasAnyAuthority(MemberConstants.ROLE_ADMIN)
 | 
			
		||||
//                            .requestMatchers("/member/**").hasAnyAuthority(MemberConstants.ROLE_MEMBER)
 | 
			
		||||
//                            .anyRequest().authenticated()
 | 
			
		||||
                            .requestMatchers(permitAllPaths).permitAll()  // 설정 파일에서 허용할 경로
 | 
			
		||||
                            .anyRequest().authenticated()  // 나머지 요청은 인증 필요
 | 
			
		||||
                )
 | 
			
		||||
                .authenticationManager(authenticationManager)
 | 
			
		||||
                .sessionManagement(session -> 
 | 
			
		||||
                    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)  // 세션 사용 안함
 | 
			
		||||
                )
 | 
			
		||||
                .logout(AbstractHttpConfigurer::disable);
 | 
			
		||||
 | 
			
		||||
        // 예외 처리 핸들링
 | 
			
		||||
        http.exceptionHandling((exceptionConfig) ->
 | 
			
		||||
                exceptionConfig
 | 
			
		||||
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
 | 
			
		||||
                        .accessDeniedHandler(jwtAccessDeniedHandler)
 | 
			
		||||
        );
 | 
			
		||||
 | 
			
		||||
//        http
 | 
			
		||||
//        		.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
 | 
			
		||||
//                .addFilterBefore(new HttpLoggingFilter(accessLogService, httpUtils), UsernamePasswordAuthenticationFilter.class)
 | 
			
		||||
//                .addFilterBefore(getJwtAuthenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
 | 
			
		||||
//                .addFilterBefore(getJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
//                .sessionManagement(httpSecuritySessionManagementConfigurer ->       //Session 사용 X
 | 
			
		||||
//                        httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
 | 
			
		||||
 | 
			
		||||
        http
 | 
			
		||||
            // 1단계: JWT 토큰 발급 필터 (로그인 요청 처리 및 토큰 발급)
 | 
			
		||||
            .addFilterBefore(getJwtTokenIssuanceFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
 | 
			
		||||
            // 2단계: JWT 토큰 검증 필터 (자동 토큰 갱신 포함)
 | 
			
		||||
            .addFilterBefore(getJwtTokenValidationFilter(), UsernamePasswordAuthenticationFilter.class);
 | 
			
		||||
 | 
			
		||||
        return http.build();
 | 
			
		||||
    }
 | 
			
		||||
 
 | 
			
		||||
@@ -1,74 +0,0 @@
 | 
			
		||||
package com.bio.bio_backend.global.utils;
 | 
			
		||||
 | 
			
		||||
import lombok.AllArgsConstructor;
 | 
			
		||||
import lombok.Getter;
 | 
			
		||||
import org.springframework.http.HttpStatus;
 | 
			
		||||
 | 
			
		||||
/*
 | 
			
		||||
 * API 관련 RESPONSE ENUM
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
@Getter
 | 
			
		||||
@AllArgsConstructor
 | 
			
		||||
public enum ApiResponseCode {
 | 
			
		||||
 | 
			
		||||
    /*login & logout*/
 | 
			
		||||
 | 
			
		||||
    // 200 OK
 | 
			
		||||
    LOGIN_SUCCESSFUL(HttpStatus.OK.value(), "Login successful"),
 | 
			
		||||
 | 
			
		||||
    LOGOUT_SUCCESSFUL(HttpStatus.OK.value(), "Logout successful"),
 | 
			
		||||
 | 
			
		||||
    USER_INFO_CHANGE(HttpStatus.OK.value(), "User info update successful"),
 | 
			
		||||
 | 
			
		||||
    USER_DELETE_SUCCESSFUL(HttpStatus.OK.value(),  "User delete is successful"),
 | 
			
		||||
 | 
			
		||||
    // 401 Unauthorized
 | 
			
		||||
    USER_NOT_FOUND(HttpStatus.UNAUTHORIZED.value(), "User not found. Authentication failed"),
 | 
			
		||||
 | 
			
		||||
    AUTHENTICATION_FAILED(HttpStatus.UNAUTHORIZED.value(), "Password is invalid"),
 | 
			
		||||
 | 
			
		||||
    // 409 Conflict
 | 
			
		||||
    USER_ID_DUPLICATE(HttpStatus.CONFLICT.value(), "User ID already exists"),
 | 
			
		||||
 | 
			
		||||
    /*auth*/
 | 
			
		||||
    // 401 Unauthorized
 | 
			
		||||
    JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT signature does not match. Authentication failed"),
 | 
			
		||||
 | 
			
		||||
    JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT token is null"),
 | 
			
		||||
 | 
			
		||||
    JWT_TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED.value(), "Token is Expired"),
 | 
			
		||||
 | 
			
		||||
    All_TOKEN_INVALID(HttpStatus.UNAUTHORIZED.value(), "Access and Refresh tokens are expired or invalid"),
 | 
			
		||||
 | 
			
		||||
    /*공통 Code*/
 | 
			
		||||
    // 400 Bad Request
 | 
			
		||||
    COMMON_BAD_REQUEST(HttpStatus.BAD_REQUEST.value(), "Required request body is missing or Error"),
 | 
			
		||||
 | 
			
		||||
    COMMON_FORMAT_WRONG(HttpStatus.BAD_REQUEST.value(), "Request format is incorrect"),
 | 
			
		||||
 | 
			
		||||
    // 401 Unauthorized
 | 
			
		||||
    COMMON_UNAUTHORIZED(HttpStatus.UNAUTHORIZED.value(), "Unauthorized"),
 | 
			
		||||
 | 
			
		||||
    // 403 Forbidden
 | 
			
		||||
    COMMON_FORBIDDEN(HttpStatus.FORBIDDEN.value(), "Access is denied"),
 | 
			
		||||
 | 
			
		||||
    // 404 Not Found
 | 
			
		||||
    COMMON_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "Resource is not found"),
 | 
			
		||||
 | 
			
		||||
    // 405 Method Not Allowed
 | 
			
		||||
    COMMON_METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED.value(), "Method not Allowed"),
 | 
			
		||||
 | 
			
		||||
    // 500 Internal Server Error
 | 
			
		||||
    INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An error occurred on the server"),
 | 
			
		||||
 | 
			
		||||
    ARGUMENT_NOT_VALID(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Argument is not valid"),
 | 
			
		||||
 | 
			
		||||
    INDEX_OUT_OF_BOUND(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Index out of bounds for length"),
 | 
			
		||||
	
 | 
			
		||||
	JSON_PROCESSING_EXCEPTION(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Check if it is a valid JSON format");
 | 
			
		||||
 | 
			
		||||
    private final int statusCode;
 | 
			
		||||
    private final String description;
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
@@ -5,14 +5,12 @@ import java.io.Serializable;
 | 
			
		||||
import org.hibernate.engine.spi.SharedSessionContractImplementor;
 | 
			
		||||
import org.hibernate.id.IdentifierGenerator;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.global.utils.OidUtil;
 | 
			
		||||
 | 
			
		||||
public class CustomIdGenerator implements IdentifierGenerator {
 | 
			
		||||
	
 | 
			
		||||
	private static final long serialVersionUID = 1L;
 | 
			
		||||
	
 | 
			
		||||
    @Override
 | 
			
		||||
    public Serializable generate(SharedSessionContractImplementor session, Object object) {
 | 
			
		||||
        return OidUtil.generateOid(); // 재사용
 | 
			
		||||
        return OidUtils.generateOid(); // 재사용
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										310
									
								
								src/main/java/com/bio/bio_backend/global/utils/FileUtils.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										310
									
								
								src/main/java/com/bio/bio_backend/global/utils/FileUtils.java
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,310 @@
 | 
			
		||||
package com.bio.bio_backend.global.utils;
 | 
			
		||||
 | 
			
		||||
import org.springframework.util.StringUtils;
 | 
			
		||||
import org.springframework.web.multipart.MultipartFile;
 | 
			
		||||
 | 
			
		||||
import java.io.IOException;
 | 
			
		||||
import java.nio.file.Files;
 | 
			
		||||
import java.nio.file.Path;
 | 
			
		||||
import java.nio.file.Paths;
 | 
			
		||||
import java.nio.file.StandardCopyOption;
 | 
			
		||||
import java.time.LocalDate;
 | 
			
		||||
import java.time.format.DateTimeFormatter;
 | 
			
		||||
import java.util.UUID;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * 파일 관련 유틸리티 클래스
 | 
			
		||||
 */
 | 
			
		||||
public class FileUtils {
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일 유효성 검사
 | 
			
		||||
     */
 | 
			
		||||
    public static void validateFile(MultipartFile multipartFile) {
 | 
			
		||||
        if (multipartFile == null || multipartFile.isEmpty()) {
 | 
			
		||||
            throw new IllegalArgumentException("업로드할 파일이 없습니다.");
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일 리스트 유효성 검사
 | 
			
		||||
     */
 | 
			
		||||
    public static void validateFileList(java.util.List<MultipartFile> files) {
 | 
			
		||||
        if (files == null || files.isEmpty()) {
 | 
			
		||||
            throw new IllegalArgumentException("업로드할 파일이 없습니다.");
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 업로드 디렉토리 생성
 | 
			
		||||
     */
 | 
			
		||||
    public static Path createUploadDirectory(String uploadPath) throws IOException {
 | 
			
		||||
        Path uploadDir = Paths.get(uploadPath);
 | 
			
		||||
        if (!Files.exists(uploadDir)) {
 | 
			
		||||
            Files.createDirectories(uploadDir);
 | 
			
		||||
        }
 | 
			
		||||
        return uploadDir;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 년월일 기반 업로드 디렉토리 생성
 | 
			
		||||
     * 예: uploads/2024/01/15/
 | 
			
		||||
     */
 | 
			
		||||
    public static Path createDateBasedUploadDirectory(String baseUploadPath) throws IOException {
 | 
			
		||||
        LocalDate today = LocalDate.now();
 | 
			
		||||
        String yearMonthDay = today.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
 | 
			
		||||
        
 | 
			
		||||
        Path dateBasedPath = Paths.get(baseUploadPath, yearMonthDay);
 | 
			
		||||
        if (!Files.exists(dateBasedPath)) {
 | 
			
		||||
            Files.createDirectories(dateBasedPath);
 | 
			
		||||
        }
 | 
			
		||||
        return dateBasedPath;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 년월 기반 업로드 디렉토리 생성
 | 
			
		||||
     * 예: uploads/2024/01/
 | 
			
		||||
     */
 | 
			
		||||
    public static Path createYearMonthUploadDirectory(String baseUploadPath) throws IOException {
 | 
			
		||||
        LocalDate today = LocalDate.now();
 | 
			
		||||
        String yearMonth = today.format(DateTimeFormatter.ofPattern("yyyy/MM"));
 | 
			
		||||
        
 | 
			
		||||
        Path yearMonthPath = Paths.get(baseUploadPath, yearMonth);
 | 
			
		||||
        if (!Files.exists(yearMonthPath)) {
 | 
			
		||||
            Files.createDirectories(yearMonthPath);
 | 
			
		||||
        }
 | 
			
		||||
        return yearMonthPath;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 년 기반 업로드 디렉토리 생성
 | 
			
		||||
     * 예: uploads/2024/
 | 
			
		||||
     */
 | 
			
		||||
    public static Path createYearUploadDirectory(String baseUploadPath) throws IOException {
 | 
			
		||||
        LocalDate today = LocalDate.now();
 | 
			
		||||
        String year = today.format(DateTimeFormatter.ofPattern("yyyy"));
 | 
			
		||||
        
 | 
			
		||||
        Path yearPath = Paths.get(baseUploadPath, year);
 | 
			
		||||
        if (!Files.exists(yearPath)) {
 | 
			
		||||
            Files.createDirectories(yearPath);
 | 
			
		||||
        }
 | 
			
		||||
        return yearPath;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 지정된 날짜로 업로드 디렉토리 생성
 | 
			
		||||
     * 예: uploads/2024/01/15/
 | 
			
		||||
     */
 | 
			
		||||
    public static Path createDateBasedUploadDirectory(String baseUploadPath, LocalDate date) throws IOException {
 | 
			
		||||
        String yearMonthDay = date.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
 | 
			
		||||
        
 | 
			
		||||
        Path dateBasedPath = Paths.get(baseUploadPath, yearMonthDay);
 | 
			
		||||
        if (!Files.exists(dateBasedPath)) {
 | 
			
		||||
            Files.createDirectories(dateBasedPath);
 | 
			
		||||
        }
 | 
			
		||||
        return dateBasedPath;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일 확장자 추출
 | 
			
		||||
     */
 | 
			
		||||
    public static String extractFileExtension(String originalFileName) {
 | 
			
		||||
        if (originalFileName == null || !originalFileName.contains(".")) {
 | 
			
		||||
            return "";
 | 
			
		||||
        }
 | 
			
		||||
        return originalFileName.substring(originalFileName.lastIndexOf("."));
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 고유한 파일명 생성
 | 
			
		||||
     */
 | 
			
		||||
    public static String generateUniqueFileName(String fileExtension) {
 | 
			
		||||
        return UUID.randomUUID().toString() + fileExtension;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일을 디스크에 저장
 | 
			
		||||
     */
 | 
			
		||||
    public static Path saveFileToDisk(MultipartFile multipartFile, Path uploadDir, String storedFileName) throws IOException {
 | 
			
		||||
        Path targetLocation = uploadDir.resolve(storedFileName);
 | 
			
		||||
        Files.copy(multipartFile.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
 | 
			
		||||
        return targetLocation;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 원본 파일명 정리 (경로 정보 제거)
 | 
			
		||||
     */
 | 
			
		||||
    public static String cleanFileName(String originalFileName) {
 | 
			
		||||
        return StringUtils.cleanPath(originalFileName);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일 크기를 사람이 읽기 쉬운 형태로 변환
 | 
			
		||||
     */
 | 
			
		||||
    public static String formatFileSize(long bytes) {
 | 
			
		||||
        if (bytes < 1024) return bytes + " B";
 | 
			
		||||
        if (bytes < 1024 * 1024) return String.format("%.1f KB", bytes / 1024.0);
 | 
			
		||||
        if (bytes < 1024 * 1024 * 1024) return String.format("%.1f MB", bytes / (1024.0 * 1024.0));
 | 
			
		||||
        return String.format("%.1f GB", bytes / (1024.0 * 1024.0 * 1024.0));
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일 확장자로부터 MIME 타입 추정
 | 
			
		||||
     */
 | 
			
		||||
    public static String getMimeTypeFromExtension(String fileName) {
 | 
			
		||||
        if (fileName == null) return "application/octet-stream";
 | 
			
		||||
        
 | 
			
		||||
        String extension = extractFileExtension(fileName).toLowerCase();
 | 
			
		||||
        switch (extension) {
 | 
			
		||||
            case ".txt": return "text/plain";
 | 
			
		||||
            case ".html": case ".htm": return "text/html";
 | 
			
		||||
            case ".css": return "text/css";
 | 
			
		||||
            case ".js": return "application/javascript";
 | 
			
		||||
            case ".json": return "application/json";
 | 
			
		||||
            case ".xml": return "application/xml";
 | 
			
		||||
            case ".pdf": return "application/pdf";
 | 
			
		||||
            case ".zip": return "application/zip";
 | 
			
		||||
            case ".jpg": case ".jpeg": return "image/jpeg";
 | 
			
		||||
            case ".png": return "image/png";
 | 
			
		||||
            case ".gif": return "image/gif";
 | 
			
		||||
            case ".bmp": return "image/bmp";
 | 
			
		||||
            case ".svg": return "image/svg+xml";
 | 
			
		||||
            case ".mp4": return "video/mp4";
 | 
			
		||||
            case ".avi": return "video/x-msvideo";
 | 
			
		||||
            case ".mp3": return "audio/mpeg";
 | 
			
		||||
            case ".wav": return "audio/wav";
 | 
			
		||||
            default: return "application/octet-stream";
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 안전한 파일명 생성 (특수문자 제거)
 | 
			
		||||
     */
 | 
			
		||||
    public static String createSafeFileName(String originalFileName) {
 | 
			
		||||
        if (originalFileName == null) return "";
 | 
			
		||||
        
 | 
			
		||||
        // 특수문자 제거 및 공백을 언더스코어로 변경
 | 
			
		||||
        String safeName = originalFileName
 | 
			
		||||
                .replaceAll("[^a-zA-Z0-9가-힣._-]", "_")
 | 
			
		||||
                .replaceAll("_+", "_")
 | 
			
		||||
                .trim();
 | 
			
		||||
        
 | 
			
		||||
        // 파일명이 너무 길면 자르기
 | 
			
		||||
        if (safeName.length() > 100) {
 | 
			
		||||
            String extension = extractFileExtension(safeName);
 | 
			
		||||
            safeName = safeName.substring(0, 100 - extension.length()) + extension;
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        return safeName;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일이 이미지인지 확인
 | 
			
		||||
     */
 | 
			
		||||
    public static boolean isImageFile(String fileName) {
 | 
			
		||||
        if (fileName == null) return false;
 | 
			
		||||
        
 | 
			
		||||
        String extension = extractFileExtension(fileName).toLowerCase();
 | 
			
		||||
        return extension.matches("\\.(jpg|jpeg|png|gif|bmp|svg|webp)$");
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일이 문서인지 확인
 | 
			
		||||
     */
 | 
			
		||||
    public static boolean isDocumentFile(String fileName) {
 | 
			
		||||
        if (fileName == null) return false;
 | 
			
		||||
        
 | 
			
		||||
        String extension = extractFileExtension(fileName).toLowerCase();
 | 
			
		||||
        return extension.matches("\\.(pdf|doc|docx|xls|xlsx|ppt|pptx|txt|rtf)$");
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일이 압축파일인지 확인
 | 
			
		||||
     */
 | 
			
		||||
    public static boolean isArchiveFile(String fileName) {
 | 
			
		||||
        if (fileName == null) return false;
 | 
			
		||||
        
 | 
			
		||||
        String extension = extractFileExtension(fileName).toLowerCase();
 | 
			
		||||
        return extension.matches("\\.(zip|rar|7z|tar|gz|bz2)$");
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 현재 날짜의 년월일 문자열 반환
 | 
			
		||||
     * 예: "2024/01/15"
 | 
			
		||||
     */
 | 
			
		||||
    public static String getCurrentDatePath() {
 | 
			
		||||
        LocalDate today = LocalDate.now();
 | 
			
		||||
        return today.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 지정된 날짜의 년월일 문자열 반환
 | 
			
		||||
     * 예: "2024/01/15"
 | 
			
		||||
     */
 | 
			
		||||
    public static String getDatePath(LocalDate date) {
 | 
			
		||||
        return date.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 파일 경로에서 년월일 정보 추출
 | 
			
		||||
     * 예: "uploads/2024/01/15/file.txt" -> "2024/01/15"
 | 
			
		||||
     */
 | 
			
		||||
    public static String extractDateFromPath(String filePath) {
 | 
			
		||||
        if (filePath == null || filePath.isEmpty()) {
 | 
			
		||||
            return "";
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        // 정규식으로 년/월/일 패턴 찾기
 | 
			
		||||
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("(\\d{4}/\\d{2}/\\d{2})");
 | 
			
		||||
        java.util.regex.Matcher matcher = pattern.matcher(filePath);
 | 
			
		||||
        
 | 
			
		||||
        if (matcher.find()) {
 | 
			
		||||
            return matcher.group(1);
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        return "";
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 년월일 폴더 구조가 유효한지 확인
 | 
			
		||||
     * 예: "2024/01/15" -> true, "2024/13/45" -> false
 | 
			
		||||
     */
 | 
			
		||||
    public static boolean isValidDatePath(String datePath) {
 | 
			
		||||
        if (datePath == null || datePath.isEmpty()) {
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        try {
 | 
			
		||||
            String[] parts = datePath.split("/");
 | 
			
		||||
            if (parts.length != 3) {
 | 
			
		||||
                return false;
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            int year = Integer.parseInt(parts[0]);
 | 
			
		||||
            int month = Integer.parseInt(parts[1]);
 | 
			
		||||
            int day = Integer.parseInt(parts[2]);
 | 
			
		||||
            
 | 
			
		||||
            // 년도 범위 체크 (1900 ~ 2100)
 | 
			
		||||
            if (year < 1900 || year > 2100) {
 | 
			
		||||
                return false;
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            // 월 범위 체크 (1 ~ 12)
 | 
			
		||||
            if (month < 1 || month > 12) {
 | 
			
		||||
                return false;
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            // 일 범위 체크 (1 ~ 31)
 | 
			
		||||
            if (day < 1 || day > 31) {
 | 
			
		||||
                return false;
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            // 실제 존재하는 날짜인지 확인
 | 
			
		||||
            LocalDate.of(year, month, day);
 | 
			
		||||
            return true;
 | 
			
		||||
            
 | 
			
		||||
        } catch (Exception e) {
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -6,15 +6,18 @@ import io.jsonwebtoken.io.Decoders;
 | 
			
		||||
import io.jsonwebtoken.security.Keys;
 | 
			
		||||
import jakarta.servlet.http.Cookie;
 | 
			
		||||
import jakarta.servlet.http.HttpServletRequest;
 | 
			
		||||
import com.bio.bio_backend.domain.user.member.service.MemberService;
 | 
			
		||||
import jakarta.servlet.http.HttpServletResponse;
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.service.MemberService;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.springframework.beans.factory.annotation.Value;
 | 
			
		||||
import org.springframework.core.env.Environment;
 | 
			
		||||
import org.springframework.stereotype.Component;
 | 
			
		||||
import org.springframework.util.StringUtils;
 | 
			
		||||
 | 
			
		||||
import javax.crypto.SecretKey;
 | 
			
		||||
import java.util.Date;
 | 
			
		||||
import java.util.Objects;
 | 
			
		||||
 | 
			
		||||
@Component
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@@ -22,6 +25,7 @@ import java.util.Date;
 | 
			
		||||
public class JwtUtils {
 | 
			
		||||
 | 
			
		||||
    private final MemberService memberService;
 | 
			
		||||
    private final Environment env;
 | 
			
		||||
 | 
			
		||||
    @Value("${token.secret_key}")
 | 
			
		||||
    private String SECRET_KEY;
 | 
			
		||||
@@ -45,12 +49,82 @@ public class JwtUtils {
 | 
			
		||||
 | 
			
		||||
    // Token 검증
 | 
			
		||||
    public Boolean validateAccessToken(String token) {
 | 
			
		||||
        return isTokenExpired(token);
 | 
			
		||||
        try {
 | 
			
		||||
            return isTokenExpired(token);
 | 
			
		||||
        } catch (io.jsonwebtoken.ExpiredJwtException e) {
 | 
			
		||||
            log.debug("Access Token 만료: {}", e.getMessage());
 | 
			
		||||
            return false;
 | 
			
		||||
        } catch (Exception e) {
 | 
			
		||||
            log.debug("Access Token 검증 실패: {}", e.getMessage());
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public Boolean validateRefreshToken(String token) {
 | 
			
		||||
        String saveToken = memberService.getRefreshToken(extractUsername(token));
 | 
			
		||||
        return (saveToken.equals(token) && isTokenExpired(token));
 | 
			
		||||
    // Refresh Token 생성 시 IP 정보 포함
 | 
			
		||||
    public String createRefreshToken(String username, String role, String clientIp) {
 | 
			
		||||
        return generateToken(username, role, clientIp,
 | 
			
		||||
                Long.parseLong(Objects.requireNonNull(env.getProperty("token.expiration_time_refresh"))));
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // IP 정보를 포함한 토큰 생성
 | 
			
		||||
    public String generateToken(String username, String role, String clientIp, long expirationTime) {
 | 
			
		||||
        return Jwts.builder()
 | 
			
		||||
                .subject(username)
 | 
			
		||||
                .claim("role", role)
 | 
			
		||||
                .claim("ip", clientIp)  // IP 정보 추가
 | 
			
		||||
                .issuedAt(new Date(System.currentTimeMillis()))
 | 
			
		||||
                .expiration(new Date(System.currentTimeMillis() + expirationTime))
 | 
			
		||||
                .signWith(getSigningKey())
 | 
			
		||||
                .compact();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // IP 정보 추출
 | 
			
		||||
    public String extractClientIp(String token) {
 | 
			
		||||
        Claims claims = extractAllClaims(token);
 | 
			
		||||
        return claims.get("ip", String.class);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Refresh Token 검증 시 IP도 함께 검증
 | 
			
		||||
    public Boolean validateRefreshToken(String token, String clientIp) {
 | 
			
		||||
        // 1. 토큰 유효성 검증
 | 
			
		||||
        if (!isValidRefreshToken(token)) {
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        // 2. IP 주소 검증
 | 
			
		||||
        if (!isValidClientIp(token, clientIp)) {
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        return true;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    // Refresh Token 유효성 검증 (토큰 일치, 만료 여부)
 | 
			
		||||
    public Boolean isValidRefreshToken(String token) {
 | 
			
		||||
        try {
 | 
			
		||||
            String savedToken = memberService.getRefreshToken(extractUsername(token));
 | 
			
		||||
            return savedToken.equals(token) && !isTokenExpired(token);
 | 
			
		||||
        } catch (Exception e) {
 | 
			
		||||
            log.debug("Refresh Token 검증 실패: {}", e.getMessage());
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    // 클라이언트 IP 주소 검증
 | 
			
		||||
    public Boolean isValidClientIp(String token, String clientIp) {
 | 
			
		||||
        try {
 | 
			
		||||
            String tokenIp = extractClientIp(token);
 | 
			
		||||
            boolean isValid = Objects.equals(tokenIp, clientIp);
 | 
			
		||||
            
 | 
			
		||||
            if (!isValid) {
 | 
			
		||||
                log.debug("IP 주소 불일치 - 토큰 IP: {}, 클라이언트 IP: {}", tokenIp, clientIp);
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            return isValid;
 | 
			
		||||
        } catch (Exception e) {
 | 
			
		||||
            log.debug("IP 주소 검증 실패: {}", e.getMessage());
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private boolean isTokenExpired(String token) {
 | 
			
		||||
@@ -60,6 +134,12 @@ public class JwtUtils {
 | 
			
		||||
    public String extractUsername(String token) {
 | 
			
		||||
        return extractAllClaims(token).getSubject();
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    // Role 정보 추출
 | 
			
		||||
    public String extractRole(String token) {
 | 
			
		||||
        Claims claims = extractAllClaims(token);
 | 
			
		||||
        return claims.get("role", String.class);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public Claims extractAllClaims(String token) {
 | 
			
		||||
 | 
			
		||||
@@ -87,4 +167,36 @@ public class JwtUtils {
 | 
			
		||||
        }
 | 
			
		||||
        return null;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Access Token 생성
 | 
			
		||||
    public String createAccessToken(String username, String role) {
 | 
			
		||||
        return generateToken(username, role,
 | 
			
		||||
                Long.parseLong(Objects.requireNonNull(env.getProperty("token.expiration_time_access"))));
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    // Refresh Token 생성
 | 
			
		||||
    public String createRefreshToken(String username, String role) {
 | 
			
		||||
        return generateToken(username, role,
 | 
			
		||||
                Long.parseLong(Objects.requireNonNull(env.getProperty("token.expiration_time_refresh"))));
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    // Refresh Token 갱신 (Access Token 갱신 시 함께)
 | 
			
		||||
    public String refreshTokens(String username, String role) {
 | 
			
		||||
        // 새로운 Refresh Token 생성 및 DB 저장
 | 
			
		||||
        String newRefreshToken = createRefreshToken(username, role);
 | 
			
		||||
        
 | 
			
		||||
        log.info("Refresh Token 갱신 완료: {}", username);
 | 
			
		||||
        return newRefreshToken;
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    // Refresh Token 쿠키 설정
 | 
			
		||||
    public void setRefreshTokenCookie(HttpServletResponse response, String refreshToken) {
 | 
			
		||||
        Cookie refreshTokenCookie = new Cookie("RefreshToken", refreshToken);
 | 
			
		||||
        refreshTokenCookie.setHttpOnly(true);
 | 
			
		||||
        refreshTokenCookie.setSecure(false);
 | 
			
		||||
        refreshTokenCookie.setPath("/");
 | 
			
		||||
        refreshTokenCookie.setMaxAge(Integer.parseInt(env.getProperty("token.expiration_time_refresh")));
 | 
			
		||||
        
 | 
			
		||||
        response.addCookie(refreshTokenCookie);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -2,7 +2,7 @@ package com.bio.bio_backend.global.utils;
 | 
			
		||||
 | 
			
		||||
import java.util.concurrent.atomic.AtomicInteger;
 | 
			
		||||
 | 
			
		||||
public class OidUtil {
 | 
			
		||||
public class OidUtils {
 | 
			
		||||
    private static final int MAX_SEQUENCE = 999;
 | 
			
		||||
    private static volatile Long lastTimestamp = null;
 | 
			
		||||
    private static AtomicInteger sequence = new AtomicInteger(0);
 | 
			
		||||
@@ -0,0 +1,68 @@
 | 
			
		||||
package com.bio.bio_backend.global.utils;
 | 
			
		||||
 | 
			
		||||
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.springframework.security.core.Authentication;
 | 
			
		||||
import org.springframework.security.core.context.SecurityContextHolder;
 | 
			
		||||
import org.springframework.stereotype.Component;
 | 
			
		||||
 | 
			
		||||
@Slf4j
 | 
			
		||||
@Component
 | 
			
		||||
public class SecurityUtils {
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 현재 인증된 사용자의 Authentication 객체를 반환합니다.
 | 
			
		||||
     * @return Authentication 객체
 | 
			
		||||
     */
 | 
			
		||||
    public static Authentication getCurrentAuthentication() {
 | 
			
		||||
        return SecurityContextHolder.getContext().getAuthentication();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 현재 인증된 사용자의 MemberDto를 반환합니다.
 | 
			
		||||
     * @return MemberDto 객체
 | 
			
		||||
     */
 | 
			
		||||
    public static MemberDto getCurrentMember() {
 | 
			
		||||
        Authentication authentication = getCurrentAuthentication();
 | 
			
		||||
        if (authentication != null && authentication.getPrincipal() instanceof MemberDto) {
 | 
			
		||||
            return (MemberDto) authentication.getPrincipal();
 | 
			
		||||
        }
 | 
			
		||||
        return null;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 현재 인증된 사용자의 userId를 반환합니다.
 | 
			
		||||
     * @return userId 문자열
 | 
			
		||||
     */
 | 
			
		||||
    public static String getCurrentUserId() {
 | 
			
		||||
        MemberDto member = getCurrentMember();
 | 
			
		||||
        return member != null ? member.getUserId() : null;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 현재 인증된 사용자의 oid를 반환합니다.
 | 
			
		||||
     * @return oid Long 값
 | 
			
		||||
     */
 | 
			
		||||
    public static Long getCurrentUserOid() {
 | 
			
		||||
        MemberDto member = getCurrentMember();
 | 
			
		||||
        return member != null ? member.getOid() : null;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 현재 인증된 사용자가 로그인되어 있는지 확인합니다.
 | 
			
		||||
     * @return 로그인 여부
 | 
			
		||||
     */
 | 
			
		||||
    public static boolean isAuthenticated() {
 | 
			
		||||
        Authentication authentication = getCurrentAuthentication();
 | 
			
		||||
        return authentication != null && authentication.isAuthenticated();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /**
 | 
			
		||||
     * 현재 인증된 사용자의 역할을 반환합니다.
 | 
			
		||||
     * @return 역할 문자열
 | 
			
		||||
     */
 | 
			
		||||
    public static String getCurrentUserRole() {
 | 
			
		||||
        MemberDto member = getCurrentMember();
 | 
			
		||||
        return member != null ? member.getRole().name() : null;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -1,56 +1,127 @@
 | 
			
		||||
# ========================================
 | 
			
		||||
# 기본 애플리케이션 설정
 | 
			
		||||
# ========================================
 | 
			
		||||
server.port=8080
 | 
			
		||||
server.servlet.context-path=/service
 | 
			
		||||
spring.application.name=bio_backend
 | 
			
		||||
spring.output.ansi.enabled=always
 | 
			
		||||
 | 
			
		||||
# ========================================
 | 
			
		||||
# 개발 도구 설정
 | 
			
		||||
# ========================================
 | 
			
		||||
spring.devtools.livereload.enabled=true
 | 
			
		||||
#spring.devtools.restart.poll-interval=2000
 | 
			
		||||
# 추가로 감시할 경로 (자바 소스 폴더)
 | 
			
		||||
spring.devtools.restart.additional-paths=src/main/java
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
# 데이터베이스 연결 정보
 | 
			
		||||
# URL 형식: jdbc:postgresql://[호스트명]:[포트번호]/[데이터베이스명]
 | 
			
		||||
# ========================================
 | 
			
		||||
# 데이터베이스 설정
 | 
			
		||||
# ========================================
 | 
			
		||||
spring.datasource.url=jdbc:postgresql://stam.kr:15432/imas
 | 
			
		||||
spring.datasource.username=imas_user
 | 
			
		||||
spring.datasource.password=stam1201
 | 
			
		||||
spring.datasource.driver-class-name=org.postgresql.Driver
 | 
			
		||||
# 운영 환경 변수 설정 필요
 | 
			
		||||
# spring.datasource.url=${DB_URL:}
 | 
			
		||||
# spring.datasource.username=${DB_USERNAME:}
 | 
			
		||||
# spring.datasource.password=${DB_PASSWORD:}
 | 
			
		||||
 | 
			
		||||
# ========================================
 | 
			
		||||
# JPA/Hibernate 설정
 | 
			
		||||
# ddl-auto: 엔티티(Entity)에 맞춰 데이터베이스 스키마를 자동 생성/업데이트합니다.
 | 
			
		||||
# - create: 애플리케이션 시작 시 기존 스키마를 삭제하고 새로 생성 (개발용)
 | 
			
		||||
# - create-drop: 시작 시 생성, 종료 시 삭제 (테스트용)
 | 
			
		||||
# - update: 엔티티 변경 시 스키마 업데이트 (개발용)
 | 
			
		||||
# - validate: 엔티티와 스키마 일치 여부만 검증 (운영용)
 | 
			
		||||
# - none: 아무 작업도 하지 않음
 | 
			
		||||
# ========================================
 | 
			
		||||
# 개발 환경 설정
 | 
			
		||||
spring.jpa.hibernate.ddl-auto=none
 | 
			
		||||
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.hibernate.hbm2ddl.schema-generation.script.append=false
 | 
			
		||||
 | 
			
		||||
# Hibernate log
 | 
			
		||||
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.use_sql_comments=false
 | 
			
		||||
 | 
			
		||||
# 배치 처리 설정
 | 
			
		||||
spring.jpa.properties.hibernate.default_batch_fetch_size=100
 | 
			
		||||
spring.jpa.properties.hibernate.jdbc.batch_size=100
 | 
			
		||||
spring.jpa.properties.hibernate.order_inserts=true
 | 
			
		||||
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.hibernate.hbm2ddl.schema-generation.script.append=false
 | 
			
		||||
 | 
			
		||||
# ========================================
 | 
			
		||||
# 로그 레벨 설정
 | 
			
		||||
# ========================================
 | 
			
		||||
# 전체 애플리케이션 기본 로그 레벨
 | 
			
		||||
logging.level.root=INFO
 | 
			
		||||
 | 
			
		||||
# 프로젝트 패키지 로그 레벨
 | 
			
		||||
logging.level.com.bio.bio_backend=DEBUG
 | 
			
		||||
 | 
			
		||||
# 세부 패키지별 로그 레벨 
 | 
			
		||||
logging.level.com.bio.bio_backend..*.controller=INFO
 | 
			
		||||
logging.level.com.bio.bio_backend..*.service=DEBUG
 | 
			
		||||
logging.level.com.bio.bio_backend..*.repository=DEBUG
 | 
			
		||||
logging.level.com.bio.bio_backend.global.aop=DEBUG
 | 
			
		||||
logging.level.com.bio.bio_backend.global.filter=INFO
 | 
			
		||||
 | 
			
		||||
# JPA/Hibernate 로깅
 | 
			
		||||
logging.level.org.hibernate.SQL=DEBUG
 | 
			
		||||
logging.level.org.hibernate.orm.jdbc.bind=TRACE
 | 
			
		||||
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
 | 
			
		||||
logging.level.org.springframework.data.jpa=DEBUG
 | 
			
		||||
logging.level.org.springframework.orm.jpa=INFO
 | 
			
		||||
logging.level.org.springframework.transaction=DEBUG
 | 
			
		||||
 | 
			
		||||
# Open Session in View 설정 (권장: false)
 | 
			
		||||
spring.jpa.open-in-view=false
 | 
			
		||||
# Spring Framework 로깅
 | 
			
		||||
logging.level.org.springframework.web=WARN
 | 
			
		||||
logging.level.org.springframework.web.servlet.DispatcherServlet=WARN
 | 
			
		||||
logging.level.org.springframework.security=INFO
 | 
			
		||||
 | 
			
		||||
# P6Spy
 | 
			
		||||
 | 
			
		||||
# ========================================
 | 
			
		||||
# 로그 패턴 설정
 | 
			
		||||
# ========================================
 | 
			
		||||
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
 | 
			
		||||
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
 | 
			
		||||
 | 
			
		||||
# ========================================
 | 
			
		||||
# P6Spy 설정 (SQL 로깅)
 | 
			
		||||
# ========================================
 | 
			
		||||
decorator.datasource.p6spy.enable-logging=true
 | 
			
		||||
decorator.datasource.p6spy.log-format=%(sqlSingleLine)
 | 
			
		||||
 | 
			
		||||
# CONSOLE
 | 
			
		||||
spring.output.ansi.enabled=always
 | 
			
		||||
# ========================================
 | 
			
		||||
# JWT 설정
 | 
			
		||||
# ========================================
 | 
			
		||||
token.expiration_time_access=900000
 | 
			
		||||
token.expiration_time_refresh=86400000
 | 
			
		||||
token.secret_key=c3RhbV9qd3Rfc2VjcmV0X3Rva2Vuc3RhbV9qd3Rfc2VjcmV0X3RhbV9qd3Rfc2VjcmV0X3RhbV9qd3Rfc2VjcmV0X3Rva2Vu
 | 
			
		||||
# 운영 환경 변수 설정 필요
 | 
			
		||||
# token.secret_key=${JWT_SECRET_KEY:}
 | 
			
		||||
 | 
			
		||||
# HikariCP 연결 풀 크기 설정 (선택사항)
 | 
			
		||||
# spring.datasource.hikari.maximum-pool-size=10
 | 
			
		||||
 | 
			
		||||
##JWT 설정
 | 
			
		||||
## access : 30분 / refresh : 7일
 | 
			
		||||
token.expiration_time_access=180000
 | 
			
		||||
token.expiration_time_refresh=604800000
 | 
			
		||||
token.secret_key= c3RhbV9qd3Rfc2VjcmV0X3Rva2Vuc3RhbV9qd3Rfc2VjcmV0X3Rva2Vu
 | 
			
		||||
 | 
			
		||||
# ========================================
 | 
			
		||||
# Swagger 설정
 | 
			
		||||
# ========================================
 | 
			
		||||
springdoc.api-docs.path=/api-docs
 | 
			
		||||
springdoc.swagger-ui.path=/swagger-ui.html
 | 
			
		||||
springdoc.swagger-ui.operationsSorter=method
 | 
			
		||||
springdoc.swagger-ui.tagsSorter=alpha
 | 
			
		||||
springdoc.swagger-ui.doc-expansion=none
 | 
			
		||||
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,/members/register,/swagger-ui/**,/swagger-ui.html,/swagger-ui/index.html,/api-docs,/api-docs/**,/v3/api-docs,/v3/api-docs/**,/ws/**
 | 
			
		||||
 | 
			
		||||
# 파일 업로드 설정
 | 
			
		||||
# ========================================
 | 
			
		||||
spring.servlet.multipart.enabled=true
 | 
			
		||||
spring.servlet.multipart.max-file-size=10MB
 | 
			
		||||
spring.servlet.multipart.max-request-size=10MB
 | 
			
		||||
spring.servlet.multipart.file-size-threshold=2KB
 | 
			
		||||
 | 
			
		||||
# 파일 저장 경로 설정
 | 
			
		||||
app.file.upload.path=./uploads/
 | 
			
		||||
							
								
								
									
										92
									
								
								src/main/resources/logback-spring.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										92
									
								
								src/main/resources/logback-spring.xml
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,92 @@
 | 
			
		||||
<?xml version="1.0" encoding="UTF-8"?>
 | 
			
		||||
<configuration>
 | 
			
		||||
    <!-- 콘솔 출력 -->
 | 
			
		||||
    <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>
 | 
			
		||||
        </encoder>
 | 
			
		||||
    </appender>
 | 
			
		||||
 | 
			
		||||
    <!-- 파일 출력 -->
 | 
			
		||||
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
 | 
			
		||||
        <file>logs/bio-backend.log</file>
 | 
			
		||||
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
 | 
			
		||||
            <!-- 일별 로그 파일 생성 -->
 | 
			
		||||
            <fileNamePattern>logs/bio-backend-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
 | 
			
		||||
            <!-- 30일간 보관 -->
 | 
			
		||||
            <maxHistory>30</maxHistory>
 | 
			
		||||
            <!-- 파일 크기 제한 -->
 | 
			
		||||
            <maxFileSize>10MB</maxFileSize>
 | 
			
		||||
            <!-- 총 용량 제한 -->
 | 
			
		||||
            <totalSizeCap>1GB</totalSizeCap>
 | 
			
		||||
        </rollingPolicy>
 | 
			
		||||
        <encoder>
 | 
			
		||||
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
 | 
			
		||||
        </encoder>
 | 
			
		||||
    </appender>
 | 
			
		||||
 | 
			
		||||
    <!-- 에러 로그만 별도 파일로 분리 -->
 | 
			
		||||
    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
 | 
			
		||||
        <file>logs/bio-backend-error.log</file>
 | 
			
		||||
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
 | 
			
		||||
            <level>ERROR</level>
 | 
			
		||||
            <onMatch>ACCEPT</onMatch>
 | 
			
		||||
            <onMismatch>DENY</onMismatch>
 | 
			
		||||
        </filter>
 | 
			
		||||
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
 | 
			
		||||
            <fileNamePattern>logs/bio-backend-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
 | 
			
		||||
            <maxHistory>30</maxHistory>
 | 
			
		||||
            <maxFileSize>10MB</maxFileSize>
 | 
			
		||||
            <totalSizeCap>500MB</totalSizeCap>
 | 
			
		||||
        </rollingPolicy>
 | 
			
		||||
        <encoder>
 | 
			
		||||
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
 | 
			
		||||
        </encoder>
 | 
			
		||||
    </appender>
 | 
			
		||||
 | 
			
		||||
    <!-- 루트 로거 설정 -->
 | 
			
		||||
    <root level="INFO">
 | 
			
		||||
        <appender-ref ref="CONSOLE" />
 | 
			
		||||
        <appender-ref ref="FILE" />
 | 
			
		||||
        <appender-ref ref="ERROR_FILE" />
 | 
			
		||||
    </root>
 | 
			
		||||
 | 
			
		||||
    <!-- 프로젝트 패키지 로그 레벨 설정 -->
 | 
			
		||||
    <logger name="com.bio.bio_backend" level="INFO" additivity="false">
 | 
			
		||||
        <appender-ref ref="CONSOLE" />
 | 
			
		||||
        <appender-ref ref="FILE" />
 | 
			
		||||
    </logger>
 | 
			
		||||
 | 
			
		||||
    <!-- Spring Security 로그 레벨 -->
 | 
			
		||||
    <logger name="org.springframework.security" level="INFO" additivity="false">
 | 
			
		||||
        <appender-ref ref="CONSOLE" />
 | 
			
		||||
        <appender-ref ref="FILE" />
 | 
			
		||||
    </logger>
 | 
			
		||||
 | 
			
		||||
    <!-- Spring Web 로그 레벨 -->
 | 
			
		||||
    <logger name="org.springframework.web" level="WARN" additivity="false">
 | 
			
		||||
        <appender-ref ref="CONSOLE" />
 | 
			
		||||
        <appender-ref ref="FILE" />
 | 
			
		||||
    </logger>
 | 
			
		||||
 | 
			
		||||
    <!-- JPA/Hibernate 로그 레벨 -->
 | 
			
		||||
    <logger name="org.hibernate.SQL" level="DEBUG" additivity="false">
 | 
			
		||||
        <appender-ref ref="CONSOLE" />
 | 
			
		||||
        <appender-ref ref="FILE" />
 | 
			
		||||
    </logger>
 | 
			
		||||
 | 
			
		||||
    <logger name="org.hibernate.orm.jdbc.bind" level="INFO" additivity="false">
 | 
			
		||||
        <appender-ref ref="CONSOLE" />
 | 
			
		||||
        <appender-ref ref="FILE" />
 | 
			
		||||
    </logger>
 | 
			
		||||
 | 
			
		||||
    <logger name="org.springframework.data.jpa" level="INFO" additivity="false">
 | 
			
		||||
        <appender-ref ref="CONSOLE" />
 | 
			
		||||
        <appender-ref ref="FILE" />
 | 
			
		||||
    </logger>
 | 
			
		||||
 | 
			
		||||
    <logger name="org.springframework.orm.jpa" level="INFO" additivity="false">
 | 
			
		||||
        <appender-ref ref="CONSOLE" />
 | 
			
		||||
        <appender-ref ref="FILE" />
 | 
			
		||||
    </logger>
 | 
			
		||||
</configuration>
 | 
			
		||||
		Reference in New Issue
	
	Block a user