Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] 파일 확장자 검증 로직 추가 #316

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static org.springframework.util.MimeTypeUtils.*;

@Slf4j
@Service
@RequiredArgsConstructor
Expand All @@ -44,6 +47,7 @@ public class ReviewService {
private static final double MAX_STAR_RATING = 5.0;
private static final String REVIEW_DOMAIN = FileReferType.REVIEW.getDomain();
private static final String REVIEW_CODE = FileReferType.REVIEW.getCode();
private static final List<String> ALLOWED_FILE_TYPE = Arrays.asList(IMAGE_JPEG_VALUE, IMAGE_PNG_VALUE, IMAGE_GIF_VALUE);

@Transactional(readOnly = true)
public Page<ReviewResponseDto> getReviewsByProduct(Long productNo, String sortBy, Pageable pageable) {
Expand Down Expand Up @@ -77,6 +81,7 @@ public ReviewResponseDto getReview(Long reviewNo) {
public Review createReview(ReviewRequestDto reviewRequestDto, List<MultipartFile> files, String id) {
isValidMemberInfo(id, reviewRequestDto.memberNo());
isValidStarRating(reviewRequestDto.starRating());
fileUtils.isValidFileExtension(files, ALLOWED_FILE_TYPE);

Review review;

Expand Down Expand Up @@ -120,6 +125,7 @@ public void updateReview(ReviewRequestDto reviewRequestDto, List<MultipartFile>
Review review = isVisibleReview(reviewRequestDto.reviewNo());
isValidMemberInfo(id, review.getMember().getMemberNo());
isValidStarRating(reviewRequestDto.starRating());
fileUtils.isValidFileExtension(files, ALLOWED_FILE_TYPE);

long productNo = review.getProduct().getProductNo();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static org.springframework.util.MimeTypeUtils.*;

@Slf4j
@Service
@RequiredArgsConstructor
Expand All @@ -43,6 +46,7 @@ public class WashzoneReviewService {
private static final double MAX_STAR_RATING = 5.0;
private static final String WASHZONE_REVIEW_DOMAIN = FileReferType.WASHZONE_REVIEW.getDomain();
private static final String WASHZONE_REVIEW_CODE = FileReferType.WASHZONE_REVIEW.getCode();
private static final List<String> ALLOWED_FILE_TYPE = Arrays.asList(IMAGE_JPEG_VALUE, IMAGE_PNG_VALUE, IMAGE_GIF_VALUE);

@Transactional(readOnly = true)
public Page<WashzoneReviewResponseDto> getWashzoneReviewsByWashzone(Long washzoneNo, String sortBy, Pageable pageable) {
Expand Down Expand Up @@ -76,6 +80,7 @@ public WashzoneReviewResponseDto getWashzoneReview(Long washzoneReviewNo) {
public WashzoneReview createWashzoneReview(WashzoneReviewRequestDto requestDto, List<MultipartFile> files, String id) {
isValidMemberInfo(id, requestDto.memberNo());
isValidStarRating(requestDto.starRating());
fileUtils.isValidFileExtension(files, ALLOWED_FILE_TYPE);

WashzoneReview washzoneReview;

Expand Down Expand Up @@ -119,6 +124,7 @@ public void updateWashzoneReview(WashzoneReviewRequestDto requestDto, List<Multi
WashzoneReview washzoneReview = isVisibleStatus(requestDto.washzoneReviewNo());
isValidMemberInfo(id, washzoneReview.getMember().getMemberNo());
isValidStarRating(requestDto.starRating());
fileUtils.isValidFileExtension(files, ALLOWED_FILE_TYPE);

long washzoneNo = washzoneReview.getWashzone().getWashZoneNo();

Expand Down
3 changes: 3 additions & 0 deletions module-common/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ dependencies {
// aws s3
implementation 'com.amazonaws:aws-java-sdk-s3:1.12.625'

// apache tika
implementation 'org.apache.tika:tika-core:2.9.1'

// commons-lang3
implementation 'org.apache.commons:commons-lang3:3.12.0'
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ public enum CommonErrorCode implements ErrorCode {
INVALID_ARGUMENT(HttpStatus.BAD_REQUEST.value(), "E006", "요청 파라미터가 없거나 비어있거나, 요청 파라미터의 이름이 메서드 인수의 이름과 일치하지 않습니다"),
INVALID_HTTP_REQUEST_METHOD(HttpStatus.BAD_REQUEST.value(), "E007", "요청 URL 에서 지원하지 않는 HTTP Method 입니다."),
INVALID_REQUEST_PARAMETER(HttpStatus.BAD_REQUEST.value(), "E008", "요청한 파라미터가 존재하지 않음"),
ARGUMENT_VALIDATION_FAILED(HttpStatus.BAD_REQUEST.value(), "E009", "유효하지 않은 데이터가 존재함");
ARGUMENT_VALIDATION_FAILED(HttpStatus.BAD_REQUEST.value(), "E009", "유효하지 않은 데이터가 존재함"),
FAIL_FILE_EXTENSION_VALIDATE(HttpStatus.INTERNAL_SERVER_ERROR.value(), "E010", "파일 확장자 검증 실패");

private final int status;
private final String code;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,30 @@
import com.kernel360.code.common.CommonErrorCode;
import com.kernel360.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.tika.Tika;
import org.apache.tika.mime.MimeTypeException;
import org.apache.tika.mime.MimeTypes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class FileUtils {

private final AmazonS3 amazonS3;
private final Tika tika = new Tika();
private final MimeTypes mimeTypes = MimeTypes.getDefaultMimeTypes();

@Value("${aws.s3.bucket.name}")
private String bucketName;
Expand Down Expand Up @@ -74,10 +84,49 @@ private String makeFileName() {
}

private String getFileExtension(String originalFilename) {
// TODO: 확장자에 대한 검사 로직 추가할 수 있을지 체크
try {
return originalFilename.substring(originalFilename.lastIndexOf("."));
} catch (StringIndexOutOfBoundsException e) {

return originalFilename.substring(originalFilename.lastIndexOf("."));
}

public void isValidFileExtension(List<MultipartFile> files) {
boolean isNotValid = files.stream()
.anyMatch(file -> {
try {
List<String> extensions = mimeTypes.forName(tika.detect(file.getInputStream())).getExtensions();
return !extensions.contains("." + FilenameUtils.getExtension(file.getOriginalFilename()));
} catch (MimeTypeException | IOException e) {
log.error("isValidFileExtension(List)", e.getMessage());
throw new BusinessException(CommonErrorCode.FAIL_FILE_EXTENSION_VALIDATE);
}
});

if (isNotValid) {
throw new BusinessException(CommonErrorCode.INVALID_FILE_EXTENSION);
}
}
Comment on lines +91 to +106
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

파일 확장자와 파일 형식이 맞는지 체크하는 부분이 이 부분인가요?


public void isValidFileExtension(List<MultipartFile> files, List<String> allowedFileType) {
isValidFileExtension(files);

if (allowedFileType == null || allowedFileType.isEmpty()) {
return;
}

List<String> allowExt = new ArrayList<>();
allowedFileType.stream()
.forEach(type -> {
try {
allowExt.addAll(mimeTypes.forName(type).getExtensions());
} catch (MimeTypeException e) {
log.error("isValidFileExtension(List, List)", e.getMessage());
throw new BusinessException(CommonErrorCode.FAIL_FILE_EXTENSION_VALIDATE);
}
});

boolean isNotValid = files.stream()
.anyMatch(file -> !allowExt.contains(getFileExtension(file.getOriginalFilename())));

if (isNotValid) {
throw new BusinessException(CommonErrorCode.INVALID_FILE_EXTENSION);
}
}
Expand Down