Skip to content

Commit

Permalink
[FEAT] CloudFront PreSignedUrl에서 upload 로직 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
sung-silver committed Jan 18, 2024
1 parent e984c68 commit e5ca7db
Showing 1 changed file with 26 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@

import com.nonsoolmate.nonsoolmateServer.external.aws.error.AWSBusinessException;
import com.nonsoolmate.nonsoolmateServer.external.aws.error.AWSExceptionType;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;

import com.nonsoolmate.nonsoolmateServer.external.aws.service.vo.PreSignedUrlVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
Expand All @@ -32,9 +36,22 @@ public class CloudFrontService {

private static final Long PRE_SIGNED_URL_EXPIRE_SECONDS = 30L;

public PreSignedUrlVO createPreSignedPutUrl(String path) {
String fileName = generateZipFileName();
return PreSignedUrlVO.of(fileName, createPreSignedUrl(path + fileName));
}

private String generateZipFileName() {
return UUID.randomUUID() + ".zip";
}

public String createPreSignedGetUrl(String path, String fileName) {
String resourcePath = getEncodedResourcePath(path, fileName);
return createPreSignedUrl(resourcePath);
}

private String createPreSignedUrl(String resourcePath) {
try {
String resourcePath = getEncodedResourcePath(path, fileName);
String cloudFrontUrl = "https://" + distributionDomain + "/" + resourcePath;
Instant expirationTime = Instant.now().plus(PRE_SIGNED_URL_EXPIRE_SECONDS, ChronoUnit.SECONDS);
Path keyPath = Paths.get(privateKeyFilePath);
Expand All @@ -48,15 +65,19 @@ public String createPreSignedGetUrl(String path, String fileName) {
.build();
SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(cannedSignerRequest);
return signedUrl.url();
} catch(AWSBusinessException e){
} catch (AWSBusinessException e) {
throw new AWSBusinessException(AWSExceptionType.GET_PRESIGNED_URL_AWS_CLOUDFRONT_FAIL);
} catch (Exception e) {
throw new AWSBusinessException(AWSExceptionType.NOT_FOUND_AWS_PRIVATE_KEY);
}
}

private String getEncodedResourcePath(String path, String fileName) throws UnsupportedEncodingException {
String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
return path + encodedFileName;
private String getEncodedResourcePath(String path, String fileName) {
try {
String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
return path + encodedFileName;
} catch (UnsupportedEncodingException e) {
throw new AWSBusinessException(AWSExceptionType.FAIL_ENCODING_FILE_NAME);
}
}
}

0 comments on commit e5ca7db

Please sign in to comment.