Skip to content

Commit

Permalink
Refactor: S3 & Kakao & Jwt Properties 환경변수 중앙 집중 관리[박한솔]
Browse files Browse the repository at this point in the history
  • Loading branch information
pjhcsols committed Sep 16, 2024
1 parent c0d783c commit 6b50098
Show file tree
Hide file tree
Showing 17 changed files with 114 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,13 @@ spring.mvc.cors.allowed-origin-patterns=http://localhost:8080
spring.mvc.cors.allow-credentials=true

# AWS S3 Service bucket
cloud.aws.s3.bucket=
cloud.aws.region.static=ap-northeast-2
cloud.aws.credentials.accessKey=
cloud.aws.credentials.secretKey=
cloud.aws.stack.auto=false

cloud.aws.s3-bucket-name=
# AWS S3 Bucket URL
cloud.aws.s3.bucket.url=
cloud.aws.s3-bucket-url=
cloud.aws.region-static=ap-northeast-2
cloud.aws.credentials-accessKey=
cloud.aws.credentials-secretKey=
cloud.aws.stack.auto=false



Expand Down
Binary file not shown.
2 changes: 1 addition & 1 deletion web3-credential-server/src/main/java/web3/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan("web3.properties.kakao")
@ConfigurationPropertiesScan("web3.properties")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,20 @@
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import web3.properties.JwtProperties;
import web3.properties.KakaoProperties;

import java.util.Date;


@Component
@RequiredArgsConstructor
public class JwtTokenUtil {

@Value("${jwt.key}")
private String secretKey;
private final JwtProperties jwtProperties;

@Value("${jwt.access-token-validity}")
private long accessTokenValidityMilliseconds;
Expand All @@ -39,7 +42,7 @@ public boolean validateToken(String token) {
try {

Jwts.parserBuilder()
.setSigningKey(secretKey.getBytes())
.setSigningKey(jwtProperties.key().getBytes())
.build()
.parseClaimsJws(token);

Expand All @@ -56,7 +59,7 @@ public boolean validateToken(String token) {

public Claims getClaimsFromToken(String token) {
return Jwts.parserBuilder()
.setSigningKey(secretKey.getBytes())
.setSigningKey(jwtProperties.key().getBytes())
.build()
.parseClaimsJws(token)
.getBody();
Expand All @@ -70,7 +73,7 @@ private String generateToken(String email, long validityMilliseconds) {
.setSubject(email)
.setIssuedAt(now)
.setExpiration(validity)
.signWith(Keys.hmacShaKeyFor(secretKey.getBytes()), SignatureAlgorithm.HS256)
.signWith(Keys.hmacShaKeyFor(jwtProperties.key().getBytes()), SignatureAlgorithm.HS256)
.compact();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import web3.properties.kakao.KakaoProperties;
import web3.properties.KakaoProperties;

@Controller
@RequestMapping("/admin/kakao")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import web3.properties.kakao.KakaoProperties;
import web3.properties.KakaoProperties;
import web3.domain.user.User;
import web3.common.dto.user.UserInfoDto;
import web3.service.dto.user.UserInfoDto;
import web3.service.kakao.KakaoService;
import web3.validation.LoginMember;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package web3.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "jwt")
public record JwtProperties (
String key
){
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package web3.properties.kakao;
package web3.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package web3.properties;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import jakarta.annotation.PostConstruct;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;

@Configuration
@ConfigurationProperties(prefix = "cloud.aws")
@Getter
@Setter
@Slf4j
public class S3Properties {

private String s3BucketName;
private String credentialsAccessKey;
private String credentialsSecretKey;
private String s3BucketUrl;
private String regionStatic;
private S3Client s3Client;

@PostConstruct
public void init() {
if (regionStatic == null || regionStatic.trim().isEmpty()) {
throw new IllegalStateException("Region must not be null or empty");
}
this.s3Client = S3Client.builder()
.region(Region.of(regionStatic))
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(credentialsAccessKey, credentialsSecretKey)))
.build();
}

}
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
package web3.s3Storage.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import org.springframework.beans.factory.annotation.Value;

import web3.properties.S3Properties;
/*
@Configuration
@RequiredArgsConstructor
public class S3Config {

@Value("${cloud.aws.region.static}")
private String region;

private final S3Properties s3Properties;
@Bean
public S3Client s3Client() {
return S3Client.builder()
.region(Region.of(region))
.region(Region.of(s3Properties.getRegionStatic()))
.build();
}
}
}
*/
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,4 @@ public ResponseEntity<String> getPdfKey(@RequestParam String pdfUrl,
return ResponseEntity.ok().body(metadata);
}



/*//스케줄러 용
@GetMapping("/all/photourl")
public ResponseEntity<List<String>> getAllImageUrls() {
List<String> imageUrls = s3StorageService.getAllImageUrls();
return ResponseEntity.ok(imageUrls);
}*/

}
Original file line number Diff line number Diff line change
@@ -1,50 +1,36 @@
package web3.s3Storage.service;

import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import web3.domain.wallet.Wallet;
import web3.properties.S3Properties;
import web3.repository.wallet.WalletRepository;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class S3StorageService {

private final S3Properties s3Properties;
private final S3Client s3Client;
private final String bucketName;
private final String bucketUrl;

private final WalletRepository walletRepository;

@Autowired
public S3StorageService(@Value("${cloud.aws.credentials.accessKey}") String accessKey,
@Value("${cloud.aws.credentials.secretKey}") String secretKey,
@Value("${cloud.aws.s3.bucket}") String bucketName,
@Value("${cloud.aws.s3.bucket.url}") String bucketUrl,
WalletRepository walletRepository) {
this.s3Client = S3Client.builder()
.region(Region.AP_NORTHEAST_2) // 원하는 리전을 지정해야 합니다.
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(accessKey, secretKey)))
.build();
this.bucketName = bucketName;
this.bucketUrl = bucketUrl;
public S3StorageService(S3Properties s3Properties, WalletRepository walletRepository) {
this.s3Properties = s3Properties;
this.s3Client = s3Properties.getS3Client();
this.walletRepository = walletRepository;
}

Expand All @@ -56,10 +42,12 @@ public String uploadPdf(MultipartFile file, Wallet wallet,String pdfInfo,String

//첫 등록일때 => 생성해줘야함
if (wallet.getPdfUrl() == null){
System.out.println("file = " + file);
log.info("file = {}", file);

fileName = (file.getSize() > 0) ? getFileName(file, wallet): getEmptyFilename(wallet);
System.out.println("fileName = " + fileName);

log.info("fileName = {}", fileName);

// PDF 파일 확장자 검증
//validatePdfFile(fileName);
result = (file.getSize() > 0) ? file.getBytes():createEmptyPdf();
Expand All @@ -69,15 +57,15 @@ public String uploadPdf(MultipartFile file, Wallet wallet,String pdfInfo,String
//이미 있을시 -> pdf 병합
String destination = wallet.getPdfUrl();
fileName = extractKeyFromUrl(destination);
System.out.println("destination = " + destination);
System.out.println("fileName = " + fileName);
log.info("destination = {}", destination);
log.info("fileName = {}", fileName);

byte[] first = getPdf(destination).readAllBytes();//원래 파일
byte[] second = (file.getSize() > 0) ? file.getBytes() : createEmptyPdf(); //뒤에 들어온 파일

nowPage = getPdfPageCount(first)+1;
result = mergePdfs(first, second);
System.out.println("merge Success");
log.info("merge Success");


metadata= getPdfMetadata(fileName);
Expand All @@ -86,26 +74,26 @@ public String uploadPdf(MultipartFile file, Wallet wallet,String pdfInfo,String
String page = "page-" + nowPage; // 키 설정
String value = pdfInfo + ":" + pdfKey;
metadata.put(page,value); // 키-값 쌍으로 추가
System.out.println("metadata = " + metadata);

log.info("metadata = {}", metadata);

try {
// S3에 PDF 파일 업로드
PutObjectRequest putRequest = PutObjectRequest.builder()
.bucket(bucketName)
.bucket(s3Properties.getS3BucketName())
.key(fileName)
.contentType(file.getContentType())
.metadata(metadata)
.build();

// PutObject 요청 수행
s3Client.putObject(putRequest, RequestBody.fromBytes(result));

} catch (S3Exception e) {
throw new IOException("Failed to upload pdf to S3: " + e.getMessage());
}

wallet.updatePdfUrl(getpdfUrl(fileName));
walletRepository.saveAndFlush(wallet);

return getpdfUrl(fileName);
}

Expand Down Expand Up @@ -174,7 +162,7 @@ public String replacePdfPage(Wallet wallet, int pageNumberToRemove, MultipartFil
// 최종 PDF를 S3에 업로드
try {
PutObjectRequest putRequest = PutObjectRequest.builder()
.bucket(bucketName)
.bucket(s3Properties.getS3BucketName())
.key(fileName)
.contentType(newPdfFile.getContentType())
.metadata(metadata)
Expand Down Expand Up @@ -277,7 +265,7 @@ public HashMap<String, String> getPdfMetadata( String pdfUrl) {
try {
HeadObjectResponse response = s3Client.headObject(
HeadObjectRequest.builder()
.bucket(bucketName)
.bucket(s3Properties.getS3BucketName())
.key(fileName)
.build());

Expand All @@ -300,7 +288,7 @@ public String getMetadataForPage(String pdfUrl, int pageNumber) {
String fileName = extractKeyFromUrl(pdfUrl);

GetObjectRequest getRequest = GetObjectRequest.builder()
.bucket(bucketName)
.bucket(s3Properties.getS3BucketName())
.key(fileName)
.build();

Expand All @@ -324,7 +312,7 @@ public String getPdfKeyForPage(String pdfUrl, int pageNumber) {
String fileName = extractKeyFromUrl(pdfUrl);

GetObjectRequest getRequest = GetObjectRequest.builder()
.bucket(bucketName)
.bucket(s3Properties.getS3BucketName())
.key(fileName)
.build();

Expand Down Expand Up @@ -365,7 +353,7 @@ public void deletePdf(String urlToDelete) {
System.out.println("key = " + key);
try {
s3Client.deleteObject(DeleteObjectRequest.builder()
.bucket(bucketName)
.bucket(s3Properties.getS3BucketName())
.key(key)
.build());
} catch (S3Exception e) {
Expand All @@ -376,7 +364,7 @@ public void deletePdf(String urlToDelete) {
public ResponseInputStream<GetObjectResponse> getPdf(String pdfUrl) {
String key = extractKeyFromUrl(pdfUrl);
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(bucketName)
.bucket(s3Properties.getS3BucketName())
.key(key)
.build();
return s3Client.getObject(getObjectRequest);
Expand All @@ -399,7 +387,7 @@ private String extractKeyFromUrl(String url) {
}

private String getpdfUrl(String fileName) {
return bucketUrl + "/" + fileName;
return s3Properties.getS3BucketUrl() + "/" + fileName;
}

@PreDestroy
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package web3.common.dto.jwt;
package web3.service.dto.jwt;

public class JwtResponse {
private String accessToken;
Expand Down
Loading

0 comments on commit 6b50098

Please sign in to comment.