This commit is contained in:
leejisun9
2025-08-26 13:21:23 +09:00
33 changed files with 1066 additions and 297 deletions

3
.gitignore vendored
View File

@@ -44,3 +44,6 @@ bin/
.DS_Store .DS_Store
Thumbs.db Thumbs.db
/nginx-1.28.0/logs/nginx.pid /nginx-1.28.0/logs/nginx.pid
# Upload files
uploads/

View File

@@ -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 ( create table st_member (
use_flag boolean not null, use_flag boolean not null,
created_at timestamp(6) not null, created_at timestamp(6) not null,
@@ -8,11 +27,14 @@
updated_at timestamp(6) not null, updated_at timestamp(6) not null,
updated_oid bigint, updated_oid bigint,
role varchar(40) not null check (role in ('MEMBER','ADMIN','SYSTEM_ADMIN')), role varchar(40) not null check (role in ('MEMBER','ADMIN','SYSTEM_ADMIN')),
login_ip varchar(45),
name varchar(100) not null, name varchar(100) not null,
password varchar(100) not null, password varchar(100) not null,
user_id varchar(100) not null, user_id varchar(100) not null,
refresh_token varchar(1024), refresh_token varchar(1024),
created_id varchar(255),
email varchar(255) not null, email varchar(255) not null,
updated_id varchar(255),
primary key (oid) primary key (oid)
); );

View File

@@ -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));
}
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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();
}

View File

@@ -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로 변경)
}

View File

@@ -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());
}
}

View File

@@ -21,6 +21,8 @@ import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import com.bio.bio_backend.global.constants.ApiResponseCode; import com.bio.bio_backend.global.constants.ApiResponseCode;
import com.bio.bio_backend.global.annotation.LogExecution; import com.bio.bio_backend.global.annotation.LogExecution;
import com.bio.bio_backend.global.utils.SecurityUtils;
@Tag(name = "Member", description = "회원 관련 API") @Tag(name = "Member", description = "회원 관련 API")
@RestController @RestController
@@ -41,8 +43,7 @@ public class MemberController {
}) })
@PostMapping("/register") @PostMapping("/register")
public ResponseEntity<ApiResponseDto<CreateMemberResponseDto>> createMember(@RequestBody @Valid CreateMemberRequestDto requestDto) { public ResponseEntity<ApiResponseDto<CreateMemberResponseDto>> createMember(@RequestBody @Valid CreateMemberRequestDto requestDto) {
MemberDto member = memberMapper.toMemberDto(requestDto); MemberDto createdMember = memberService.createMember(memberMapper.toMemberDto(requestDto));
MemberDto createdMember = memberService.createMember(member);
CreateMemberResponseDto responseDto = memberMapper.toCreateMemberResponseDto(createdMember); CreateMemberResponseDto responseDto = memberMapper.toCreateMemberResponseDto(createdMember);
ApiResponseDto<CreateMemberResponseDto> apiResponse = ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS_CREATED, responseDto); ApiResponseDto<CreateMemberResponseDto> apiResponse = ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS_CREATED, responseDto);
@@ -56,12 +57,11 @@ public class MemberController {
@ApiResponse(responseCode = "401", description = "인증 실패", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))) @ApiResponse(responseCode = "401", description = "인증 실패", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))
}) })
@PostMapping("/logout") @PostMapping("/logout")
public ResponseEntity<ApiResponseDto<Void>> logout(@RequestHeader("Authorization") String authorization) { public ResponseEntity<ApiResponseDto<Void>> logout() {
try { try {
// Authorization 헤더에서 토큰 추출 String userId = SecurityUtils.getCurrentUserId();
String token = authorization.replace("Bearer ", ""); memberService.deleteRefreshToken(userId);
// Refresh Token 삭제 (실제로는 JWT 블랙리스트나 DB에서 삭제) log.info("사용자 로그아웃 완료: {}", userId);
// memberService.deleteRefreshToken(userId);
return ResponseEntity.ok(ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS)); return ResponseEntity.ok(ApiResponseDto.success(ApiResponseCode.COMMON_SUCCESS));
} catch (Exception e) { } catch (Exception e) {
@@ -70,73 +70,4 @@ public class MemberController {
.body(ApiResponseDto.fail(ApiResponseCode.COMMON_INTERNAL_SERVER_ERROR)); .body(ApiResponseDto.fail(ApiResponseCode.COMMON_INTERNAL_SERVER_ERROR));
} }
} }
// @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 ApiResponseDto<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 ApiResponseDto.success(ApiResponseCode.USER_INFO_CHANGE, null);
// }
// @DeleteMapping("/member")
// public ApiResponseDto<Void> deleteMember(@RequestBody @Valid CreateMemberRequestDTO requestMember){
// MemberDTO member = mapper.map(requestMember, MemberDTO.class);
// memberService.deleteMember(member);
// return ApiResponseDto.success(ApiResponseCode.USER_DELETE_SUCCESSFUL, null);
// }
// @PostMapping("/logout")
// public ApiResponseDto<Void> logout(@AuthenticationPrincipal MemberDTO member) {
// String id = member.getId();
// try {
// memberService.deleteRefreshToken(id);
// } catch (Exception e) {
// return ApiResponseDto.fail(ApiResponseCode.INTERNAL_SERVER_ERROR, null);
// }
// return ApiResponseDto.success(ApiResponseCode.LOGOUT_SUCCESSFUL, null);
// }
} }

View File

@@ -27,6 +27,7 @@ public class MemberDto implements UserDetails {
private MemberRole role; private MemberRole role;
private Boolean useFlag; private Boolean useFlag;
private String refreshToken; private String refreshToken;
private String loginIp;
private LocalDateTime lastLoginAt; private LocalDateTime lastLoginAt;
private LocalDateTime createdAt; private LocalDateTime createdAt;
private LocalDateTime updatedAt; private LocalDateTime updatedAt;

View File

@@ -1,6 +1,7 @@
package com.bio.bio_backend.domain.base.member.entity; package com.bio.bio_backend.domain.base.member.entity;
import com.bio.bio_backend.domain.base.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 com.bio.bio_backend.global.entity.BaseEntity;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -17,7 +18,7 @@ import java.time.LocalDateTime;
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Table( @Table(
name = "st_member", name = AppConstants.TABLE_PREFIX + "member",
indexes = { indexes = {
@Index(name = "idx_member_user_id", columnList = "user_id") @Index(name = "idx_member_user_id", columnList = "user_id")
} }
@@ -47,6 +48,9 @@ public class Member extends BaseEntity {
@Column(name = "refresh_token", length = 1024) @Column(name = "refresh_token", length = 1024)
private String refreshToken; private String refreshToken;
@Column(name = "login_ip", length = 45) // IPv6 지원을 위해 45자
private String loginIp;
@Column(name = "last_login_at") @Column(name = "last_login_at")
private LocalDateTime lastLoginAt; private LocalDateTime lastLoginAt;

View File

@@ -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.CreateMemberResponseDto;
import com.bio.bio_backend.domain.base.member.dto.MemberDto; 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.entity.Member;
import com.bio.bio_backend.global.annotation.IgnoreBaseEntityMapping;
import org.mapstruct.Mapper; import org.mapstruct.Mapper;
import org.mapstruct.Mapping; import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers; import org.mapstruct.factory.Mappers;
@@ -22,6 +23,7 @@ public interface MemberMapper {
@Mapping(target = "role", expression = "java(com.bio.bio_backend.domain.base.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 = "useFlag", constant = "true")
@Mapping(target = "refreshToken", ignore = true) @Mapping(target = "refreshToken", ignore = true)
@Mapping(target = "loginIp", ignore = true)
@Mapping(target = "lastLoginAt", ignore = true) @Mapping(target = "lastLoginAt", ignore = true)
@Mapping(target = "createdAt", ignore = true) @Mapping(target = "createdAt", ignore = true)
@Mapping(target = "updatedAt", ignore = true) @Mapping(target = "updatedAt", ignore = true)
@@ -50,10 +52,6 @@ public interface MemberMapper {
/** /**
* MemberDto의 값으로 기존 Member 엔티티 업데이트 (null이 아닌 필드만) * MemberDto의 값으로 기존 Member 엔티티 업데이트 (null이 아닌 필드만)
*/ */
@Mapping(target = "oid", ignore = true) @IgnoreBaseEntityMapping
@Mapping(target = "createdAt", ignore = true)
@Mapping(target = "updatedAt", ignore = true)
@Mapping(target = "createdOid", ignore = true)
@Mapping(target = "updatedOid", ignore = true)
void updateMemberFromDto(MemberDto memberDto, @org.mapstruct.MappingTarget Member member); void updateMemberFromDto(MemberDto memberDto, @org.mapstruct.MappingTarget Member member);
} }

View File

@@ -4,27 +4,11 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.bio.bio_backend.domain.base.member.entity.Member; import com.bio.bio_backend.domain.base.member.entity.Member;
import java.util.Optional;
import java.util.List; import java.util.List;
@Repository @Repository
public interface MemberRepository extends JpaRepository<Member, Long>, MemberRepositoryCustom { public interface MemberRepository extends JpaRepository<Member, Long>, MemberRepositoryCustom {
// 사용자 ID로 회원 조회 (Optional 반환)
Optional<Member> findByUserId(String userId);
// 사용자 ID로 첫 번째 회원 조회 (userId가 unique하지 않을 경우 대비)
Optional<Member> findFirstByUserId(String userId);
// 사용자 ID로 활성화된 회원 조회
Optional<Member> findByUserIdAndUseFlagTrue(String userId);
// 사용자 ID로 활성화된 회원 첫 번째 조회
Optional<Member> findFirstByUserIdAndUseFlagTrue(String userId);
// 사용자 ID 존재 여부 확인 (활성화된 회원만)
boolean existsByUserIdAndUseFlagTrue(String userId);
// 사용자 ID 존재 여부 확인 // 사용자 ID 존재 여부 확인
boolean existsByUserId(String userId); boolean existsByUserId(String userId);

View File

@@ -1,10 +1,6 @@
package com.bio.bio_backend.domain.base.member.repository; 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.Member;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Optional; import java.util.Optional;
/** /**
@@ -20,48 +16,4 @@ public interface MemberRepositoryCustom {
* @return Optional<Member> 회원 정보 (없으면 empty) * @return Optional<Member> 회원 정보 (없으면 empty)
*/ */
Optional<Member> findActiveMemberByUserId(String userId); Optional<Member> findActiveMemberByUserId(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);
} }

View File

@@ -2,17 +2,10 @@ 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.Member;
import com.bio.bio_backend.domain.base.member.entity.QMember; import com.bio.bio_backend.domain.base.member.entity.QMember;
import com.bio.bio_backend.domain.base.member.enums.MemberRole;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory; import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional; import java.util.Optional;
/** /**
@@ -42,89 +35,4 @@ public class MemberRepositoryImpl implements MemberRepositoryCustom {
return Optional.ofNullable(foundMember); 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();
}
} }

View File

@@ -1,6 +1,5 @@
package com.bio.bio_backend.domain.base.member.service; package com.bio.bio_backend.domain.base.member.service;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -21,9 +20,5 @@ public interface MemberService extends UserDetailsService {
List<MemberDto> selectMemberList(Map<String, String> params); List<MemberDto> selectMemberList(Map<String, String> params);
MemberDto selectMember(long seq);
int updateMember(MemberDto member); int updateMember(MemberDto member);
int deleteMember(MemberDto member);
} }

View File

@@ -7,6 +7,7 @@ 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.domain.base.member.repository.MemberRepository;
import com.bio.bio_backend.global.exception.ApiException; import com.bio.bio_backend.global.exception.ApiException;
import com.bio.bio_backend.global.constants.ApiResponseCode; import com.bio.bio_backend.global.constants.ApiResponseCode;
import com.bio.bio_backend.global.constants.AppConstants;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
@@ -18,7 +19,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.Map; 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 @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -34,11 +35,7 @@ public class MemberServiceImpl implements MemberService {
public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
Member member = memberRepository.findActiveMemberByUserId(id) Member member = memberRepository.findActiveMemberByUserId(id)
.orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다: " + id)); .orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다: " + id));
return memberMapper.toMemberDto(member);
// MapStruct를 사용하여 Member 엔티티를 MemberDto로 변환
MemberDto memberDto = memberMapper.toMemberDto(member);
return memberDto;
} }
@Override @Override
@@ -59,7 +56,7 @@ public class MemberServiceImpl implements MemberService {
Long oid = generateOid(); Long oid = generateOid();
member.setOid(oid); member.setOid(oid);
member.setCreatedOid(oid); member.setCreator(AppConstants.ADMIN_OID, AppConstants.ADMIN_USER_ID);
Member savedMember = memberRepository.save(member); Member savedMember = memberRepository.save(member);
@@ -69,7 +66,7 @@ public class MemberServiceImpl implements MemberService {
@Override @Override
@Transactional @Transactional
public int updateMember(MemberDto memberDto) { public int updateMember(MemberDto memberDto) {
Member member = memberRepository.findFirstByUserIdAndUseFlagTrue(memberDto.getUserId()) Member member = memberRepository.findActiveMemberByUserId(memberDto.getUserId())
.orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND)); .orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND));
memberMapper.updateMemberFromDto(memberDto, member); memberMapper.updateMemberFromDto(memberDto, member);
@@ -79,7 +76,7 @@ public class MemberServiceImpl implements MemberService {
@Override @Override
public String getRefreshToken(String id) { public String getRefreshToken(String id) {
Member member = memberRepository.findFirstByUserIdAndUseFlagTrue(id) Member member = memberRepository.findActiveMemberByUserId(id)
.orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND)); .orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND));
return member.getRefreshToken(); return member.getRefreshToken();
@@ -88,12 +85,12 @@ public class MemberServiceImpl implements MemberService {
@Override @Override
@Transactional @Transactional
public int deleteRefreshToken(String id) { public int deleteRefreshToken(String id) {
Member member = memberRepository.findFirstByUserIdAndUseFlagTrue(id) Member member = memberRepository.findActiveMemberByUserId(id)
.orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND)); .orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND));
member.setRefreshToken(null); member.setRefreshToken(null);
memberRepository.save(member); memberRepository.save(member);
return 1; // 성공 시 1 반환 return 1;
} }
@Override @Override
@@ -102,30 +99,4 @@ public class MemberServiceImpl implements MemberService {
return memberMapper.toMemberDtoList(members); 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 deleteMember(MemberDto memberDto) {
Member member = memberRepository.findFirstByUserId(memberDto.getUserId())
.orElseThrow(() -> new ApiException(ApiResponseCode.USER_NOT_FOUND));
member.setUseFlag(false);
log.info("회원 삭제 처리: {}", member.toString());
memberRepository.save(member);
return 1; // 성공 시 1 반환
}
} }

View File

@@ -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 {
}

View File

@@ -63,7 +63,26 @@ public enum ApiResponseCode {
JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT 서명이 일치하지 않습니다. 인증에 실패했습니다"), JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT 서명이 일치하지 않습니다. 인증에 실패했습니다"),
JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT 토큰이 null입니다"), JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT 토큰이 null입니다"),
JWT_TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED.value(), "토큰이 만료되었습니다"), 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 int statusCode;
private final String description; private final String description;

View File

@@ -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 = "시스템관리자";
}

View File

@@ -9,7 +9,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import static com.bio.bio_backend.global.utils.OidUtil.generateOid; import static com.bio.bio_backend.global.utils.OidUtils.generateOid;
/** /**
* 모든 엔티티가 상속받는 기본 엔티티 클래스 * 모든 엔티티가 상속받는 기본 엔티티 클래스
@@ -39,9 +39,37 @@ public abstract class BaseEntity {
@Column(name = "updated_oid") @Column(name = "updated_oid")
private Long updatedOid; private Long updatedOid;
@Column(name = "created_id", updatable = false)
private String createdId;
@Column(name = "updated_id")
private String updatedId;
@PrePersist @PrePersist
protected void onCreate() { protected void onCreate() {
if(this.oid == null) this.oid = generateOid(); if(this.oid == null) this.oid = generateOid();
if(this.createdOid != null && this.updatedOid == null) this.updatedOid = this.createdOid; 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;
}
} }

View File

@@ -12,6 +12,7 @@ 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.domain.base.member.service.MemberService;
import com.bio.bio_backend.global.constants.ApiResponseCode; import com.bio.bio_backend.global.constants.ApiResponseCode;
import com.bio.bio_backend.global.utils.JwtUtils; import com.bio.bio_backend.global.utils.JwtUtils;
import com.bio.bio_backend.global.utils.HttpUtils;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@@ -38,6 +39,7 @@ public class JwtTokenIssuanceFilter extends UsernamePasswordAuthenticationFilter
private final JwtUtils jwtUtils; private final JwtUtils jwtUtils;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final MemberService memberService; private final MemberService memberService;
private final HttpUtils httpUtils;
// 사용자 login 인증 처리 // 사용자 login 인증 처리
@Override @Override
@@ -66,6 +68,7 @@ public class JwtTokenIssuanceFilter extends UsernamePasswordAuthenticationFilter
String refreshToken = jwtUtils.createRefreshToken(member.getUserId(), member.getRole().getValue()); String refreshToken = jwtUtils.createRefreshToken(member.getUserId(), member.getRole().getValue());
member.setRefreshToken(refreshToken); member.setRefreshToken(refreshToken);
member.setLoginIp(httpUtils.getClientIp());
member.setLastLoginAt(LocalDateTime.now()); member.setLastLoginAt(LocalDateTime.now());
memberService.updateMember(member); memberService.updateMember(member);

View File

@@ -69,9 +69,25 @@ public class JwtTokenValidationFilter extends OncePerRequestFilter {
} }
// Access Token이 없거나 만료된 경우, Refresh Token으로 갱신 시도 // Access Token이 없거나 만료된 경우, Refresh Token으로 갱신 시도
if (refreshToken != null && jwtUtils.validateRefreshToken(refreshToken)) { 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 username = jwtUtils.extractUsername(refreshToken);
String role = (String) jwtUtils.extractAllClaims(refreshToken).get("role"); String role = jwtUtils.extractRole(refreshToken);
// 새로운 Access Token 생성 // 새로운 Access Token 생성
String newAccessToken = jwtUtils.generateToken(username, role, String newAccessToken = jwtUtils.generateToken(username, role,

View File

@@ -21,6 +21,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.bio.bio_backend.domain.base.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.CustomAuthenticationFailureHandler;
import com.bio.bio_backend.global.utils.JwtUtils; 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 com.bio.bio_backend.global.config.SecurityPathConfig;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -35,9 +36,10 @@ public class WebSecurity {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final Environment env; private final Environment env;
private final SecurityPathConfig securityPathConfig; private final SecurityPathConfig securityPathConfig;
private final HttpUtils httpUtils;
private JwtTokenIssuanceFilter getJwtTokenIssuanceFilter(AuthenticationManager authenticationManager) throws Exception { private JwtTokenIssuanceFilter getJwtTokenIssuanceFilter(AuthenticationManager authenticationManager) throws Exception {
JwtTokenIssuanceFilter filter = new JwtTokenIssuanceFilter(authenticationManager, jwtUtils, objectMapper, memberService); JwtTokenIssuanceFilter filter = new JwtTokenIssuanceFilter(authenticationManager, jwtUtils, objectMapper, memberService, httpUtils);
filter.setFilterProcessesUrl("/login"); filter.setFilterProcessesUrl("/login");
filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler(objectMapper)); filter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler(objectMapper));
return filter; return filter;

View File

@@ -5,14 +5,12 @@ import java.io.Serializable;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.IdentifierGenerator;
import com.bio.bio_backend.global.utils.OidUtil;
public class CustomIdGenerator implements IdentifierGenerator { public class CustomIdGenerator implements IdentifierGenerator {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Override @Override
public Serializable generate(SharedSessionContractImplementor session, Object object) { public Serializable generate(SharedSessionContractImplementor session, Object object) {
return OidUtil.generateOid(); // 재사용 return OidUtils.generateOid(); // 재사용
} }
} }

View 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;
}
}
}

View File

@@ -8,7 +8,6 @@ import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import com.bio.bio_backend.domain.base.member.service.MemberService; import com.bio.bio_backend.domain.base.member.service.MemberService;
import com.bio.bio_backend.domain.base.member.dto.MemberDto;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@@ -50,12 +49,82 @@ public class JwtUtils {
// Token 검증 // Token 검증
public Boolean validateAccessToken(String 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) { // Refresh Token 생성 시 IP 정보 포함
String saveToken = memberService.getRefreshToken(extractUsername(token)); public String createRefreshToken(String username, String role, String clientIp) {
return (saveToken.equals(token) && isTokenExpired(token)); 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) { private boolean isTokenExpired(String token) {
@@ -66,6 +135,12 @@ public class JwtUtils {
return extractAllClaims(token).getSubject(); 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) { public Claims extractAllClaims(String token) {
return Jwts.parser() return Jwts.parser()

View File

@@ -2,7 +2,7 @@ package com.bio.bio_backend.global.utils;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class OidUtil { public class OidUtils {
private static final int MAX_SEQUENCE = 999; private static final int MAX_SEQUENCE = 999;
private static volatile Long lastTimestamp = null; private static volatile Long lastTimestamp = null;
private static AtomicInteger sequence = new AtomicInteger(0); private static AtomicInteger sequence = new AtomicInteger(0);

View File

@@ -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;
}
}

View File

@@ -92,7 +92,7 @@ decorator.datasource.p6spy.log-format=%(sqlSingleLine)
# JWT 설정 # JWT 설정
# ======================================== # ========================================
token.expiration_time_access=900000 token.expiration_time_access=900000
token.expiration_time_refresh=604800000 token.expiration_time_refresh=86400000
token.secret_key=c3RhbV9qd3Rfc2VjcmV0X3Rva2Vuc3RhbV9qd3Rfc2VjcmV0X3RhbV9qd3Rfc2VjcmV0X3RhbV9qd3Rfc2VjcmV0X3Rva2Vu token.secret_key=c3RhbV9qd3Rfc2VjcmV0X3Rva2Vuc3RhbV9qd3Rfc2VjcmV0X3RhbV9qd3Rfc2VjcmV0X3RhbV9qd3Rfc2VjcmV0X3Rva2Vu
# 운영 환경 변수 설정 필요 # 운영 환경 변수 설정 필요
# token.secret_key=${JWT_SECRET_KEY:} # token.secret_key=${JWT_SECRET_KEY:}
@@ -115,3 +115,13 @@ 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/