[파일 업로드 기능 추가] 파일 업로드 및 다운로드 API 구현
This commit is contained in:
		@@ -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,208 @@
 | 
			
		||||
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;
 | 
			
		||||
 | 
			
		||||
@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());
 | 
			
		||||
        
 | 
			
		||||
        // 응답 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;
 | 
			
		||||
        
 | 
			
		||||
        for (MultipartFile multipartFile : files) {
 | 
			
		||||
            try {
 | 
			
		||||
                // 개별 파일 유효성 검사
 | 
			
		||||
                if (multipartFile.isEmpty()) {
 | 
			
		||||
                    String errorMsg = "파일 '" + multipartFile.getOriginalFilename() + "'이 비어있습니다.";
 | 
			
		||||
                    errorMessages.add(errorMsg);
 | 
			
		||||
                    failureCount++;
 | 
			
		||||
                    continue;
 | 
			
		||||
                }
 | 
			
		||||
                
 | 
			
		||||
                // 단일 파일 업로드 처리
 | 
			
		||||
                File savedFile = processFileUpload(multipartFile, requestDto.getDescription());
 | 
			
		||||
                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) {
 | 
			
		||||
        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);
 | 
			
		||||
            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) {
 | 
			
		||||
        return File.builder()
 | 
			
		||||
                .originalFileName(originalFileName)
 | 
			
		||||
                .storedFileName(storedFileName)
 | 
			
		||||
                .filePath(targetLocation.toString())
 | 
			
		||||
                .fileSize(multipartFile.getSize())
 | 
			
		||||
                .contentType(multipartFile.getContentType())
 | 
			
		||||
                .description(description)
 | 
			
		||||
                .groupOid(OidUtils.generateOid())
 | 
			
		||||
                .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());
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -41,8 +41,7 @@ public class MemberController {
 | 
			
		||||
    })
 | 
			
		||||
    @PostMapping("/register")
 | 
			
		||||
    public ResponseEntity<ApiResponseDto<CreateMemberResponseDto>> createMember(@RequestBody @Valid CreateMemberRequestDto requestDto) {
 | 
			
		||||
        MemberDto member = memberMapper.toMemberDto(requestDto);
 | 
			
		||||
        MemberDto createdMember = memberService.createMember(member);
 | 
			
		||||
        MemberDto createdMember = memberService.createMember(memberMapper.toMemberDto(requestDto));
 | 
			
		||||
        CreateMemberResponseDto responseDto = memberMapper.toCreateMemberResponseDto(createdMember);
 | 
			
		||||
        ApiResponseDto<CreateMemberResponseDto> apiResponse = ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS_CREATED, responseDto);
 | 
			
		||||
        
 | 
			
		||||
 
 | 
			
		||||
@@ -4,6 +4,7 @@ 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;
 | 
			
		||||
@@ -51,10 +52,6 @@ public interface MemberMapper {
 | 
			
		||||
    /**
 | 
			
		||||
     * MemberDto의 값으로 기존 Member 엔티티 업데이트 (null이 아닌 필드만)
 | 
			
		||||
     */
 | 
			
		||||
    @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)
 | 
			
		||||
    @IgnoreBaseEntityMapping
 | 
			
		||||
    void updateMemberFromDto(MemberDto memberDto, @org.mapstruct.MappingTarget Member member);
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -25,4 +25,10 @@ public interface MemberService extends UserDetailsService {
 | 
			
		||||
    int updateMember(MemberDto member);
 | 
			
		||||
 | 
			
		||||
    int deleteMember(MemberDto member);
 | 
			
		||||
    
 | 
			
		||||
    /**
 | 
			
		||||
     * 현재 로그인한 사용자의 정보를 조회합니다.
 | 
			
		||||
     * @return 현재 사용자의 MemberDto
 | 
			
		||||
     */
 | 
			
		||||
    MemberDto getCurrentMember();
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -7,6 +7,8 @@ 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 com.bio.bio_backend.global.utils.SecurityUtils;
 | 
			
		||||
import lombok.RequiredArgsConstructor;
 | 
			
		||||
import lombok.extern.slf4j.Slf4j;
 | 
			
		||||
import org.springframework.security.core.userdetails.UserDetails;
 | 
			
		||||
@@ -18,7 +20,7 @@ import org.springframework.transaction.annotation.Transactional;
 | 
			
		||||
import java.util.List;
 | 
			
		||||
import java.util.Map;
 | 
			
		||||
 | 
			
		||||
import static com.bio.bio_backend.global.utils.OidUtil.generateOid;
 | 
			
		||||
import static com.bio.bio_backend.global.utils.OidUtils.generateOid;
 | 
			
		||||
 | 
			
		||||
@Service
 | 
			
		||||
@RequiredArgsConstructor
 | 
			
		||||
@@ -59,7 +61,7 @@ public class MemberServiceImpl implements MemberService {
 | 
			
		||||
 | 
			
		||||
        Long oid = generateOid();
 | 
			
		||||
        member.setOid(oid);
 | 
			
		||||
        member.setCreatedOid(oid);
 | 
			
		||||
        member.setCreator(AppConstants.ADMIN_OID, AppConstants.ADMIN_USER_ID);
 | 
			
		||||
        
 | 
			
		||||
        Member savedMember = memberRepository.save(member);
 | 
			
		||||
        
 | 
			
		||||
@@ -115,6 +117,11 @@ public class MemberServiceImpl implements MemberService {
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    public MemberDto getCurrentMember() {
 | 
			
		||||
        return SecurityUtils.getCurrentMember();
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    @Override
 | 
			
		||||
    @Transactional
 | 
			
		||||
    public int deleteMember(MemberDto memberDto) {
 | 
			
		||||
 
 | 
			
		||||
@@ -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 {
 | 
			
		||||
}
 | 
			
		||||
@@ -63,7 +63,26 @@ public enum ApiResponseCode {
 | 
			
		||||
    JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT 서명이 일치하지 않습니다. 인증에 실패했습니다"),
 | 
			
		||||
    JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT 토큰이 null입니다"),
 | 
			
		||||
    JWT_TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED.value(), "토큰이 만료되었습니다"),
 | 
			
		||||
    ALL_TOKEN_INVALID(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;
 | 
			
		||||
 
 | 
			
		||||
@@ -2,4 +2,9 @@ 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 = "시스템관리자";
 | 
			
		||||
}
 | 
			
		||||
@@ -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;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -69,9 +69,25 @@ public class JwtTokenValidationFilter extends OncePerRequestFilter {
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        // Access Token이 없거나 만료된 경우, Refresh Token으로 갱신 시도
 | 
			
		||||
        if (refreshToken != null && jwtUtils.validateRefreshToken(refreshToken, request.getRemoteAddr())) {
 | 
			
		||||
        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 = (String) jwtUtils.extractAllClaims(refreshToken).get("role");
 | 
			
		||||
            String role = jwtUtils.extractRole(refreshToken);
 | 
			
		||||
            
 | 
			
		||||
            // 새로운 Access Token 생성
 | 
			
		||||
            String newAccessToken = jwtUtils.generateToken(username, role,
 | 
			
		||||
 
 | 
			
		||||
@@ -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;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -49,7 +49,15 @@ 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;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    // Refresh Token 생성 시 IP 정보 포함
 | 
			
		||||
@@ -78,13 +86,45 @@ public class JwtUtils {
 | 
			
		||||
 | 
			
		||||
    // Refresh Token 검증 시 IP도 함께 검증
 | 
			
		||||
    public Boolean validateRefreshToken(String token, String clientIp) {
 | 
			
		||||
        String savedToken = memberService.getRefreshToken(extractUsername(token));
 | 
			
		||||
        String tokenIp = extractClientIp(token);
 | 
			
		||||
        // 1. 토큰 유효성 검증
 | 
			
		||||
        if (!isValidRefreshToken(token)) {
 | 
			
		||||
            return false;
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        // 토큰 일치, 만료되지 않음, IP 일치 확인
 | 
			
		||||
        return (savedToken.equals(token) && 
 | 
			
		||||
                isTokenExpired(token) && 
 | 
			
		||||
                Objects.equals(tokenIp, clientIp));
 | 
			
		||||
        // 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) {
 | 
			
		||||
@@ -94,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) {
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
@@ -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;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@@ -114,4 +114,14 @@ 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/**
 | 
			
		||||
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/
 | 
			
		||||
		Reference in New Issue
	
	Block a user