Skip to content

Commit

Permalink
Fix: Member GCP Credential 정보 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
gytjd committed Nov 20, 2024
1 parent 4dbac46 commit dfe29a9
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 45 deletions.
2 changes: 2 additions & 0 deletions src/main/java/AIWA/MCPBackend_Member/Entity/AiwaKey.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public class AiwaKey {
private String secretKey;
private String gcpKeyPath;

private String awsTfvarsUrl;

@ManyToOne
@JoinColumn(name = "member_id")
private Member member;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package AIWA.MCPBackend_Member.Service.member;


import AIWA.MCPBackend_Member.Dto.MemberDeleteRequestDto;
import AIWA.MCPBackend_Member.Dto.MemberRequestDto;
import AIWA.MCPBackend_Member.Entity.AiwaKey;
Expand All @@ -23,9 +22,12 @@ public Member registerMember(MemberRequestDto memberRequestDto) {
if (memberRepository.findByEmail(memberRequestDto.getEmail()) != null) {
throw new RuntimeException("Email already exists");
}
s3Service.createUserDirectory(memberRequestDto.getEmail());
Member regiMember=new Member(memberRequestDto.getName(), memberRequestDto.getPassword(), memberRequestDto.getEmail());
// 사용자 디렉터리 생성 (AWS 및 GCP 디렉토리 포함)
s3Service.createUserAWSDirectory(memberRequestDto.getEmail());
s3Service.createUserGCPDirectory(memberRequestDto.getEmail()); // GCP 디렉토리 추가

// 회원 생성
Member regiMember = new Member(memberRequestDto.getName(), memberRequestDto.getPassword(), memberRequestDto.getEmail());
return memberRepository.save(regiMember);
}

Expand All @@ -45,7 +47,6 @@ public void deleteMember(MemberDeleteRequestDto deleteMemberRequestDto) {
memberRepository.delete(member);
}


// 특정 회원 조회
public Member getMemberByEmail(String email) {
return memberRepository.findByEmail(email);
Expand All @@ -56,37 +57,25 @@ public List<Member> getAllMembers() {
}


// AWS 및 GCP 키 추가/수정
public String addOrUpdateAwsAndGcpKey(String email, String companyName, String accessKey, String secretKey, String gcpKeyContent) {
// 회원 조회
Member member = getMemberByEmail(email);
if (member == null) {
throw new RuntimeException("Member not found with Email: " + email);
}

// AWS 키 처리: "AWS" 또는 다른 회사 키를 처리 가능하도록 수정
Optional<AiwaKey> existingKey = member.getAiwaKeys().stream()
.filter(key -> companyName.equalsIgnoreCase(key.getCompanyName()))
.findFirst();

if (existingKey.isPresent()) {
// 기존 키 업데이트
AiwaKey key = existingKey.get();
key.setAccessKey(accessKey);
key.setSecretKey(secretKey);

// GCP 키 내용이 제공된 경우에만 GCP 키 경로 업데이트
if (gcpKeyContent != null && !gcpKeyContent.isEmpty()) {
String gcpKeyPath = s3Service.uploadGcpKeyFile(email, gcpKeyContent);
key.setGcpKeyPath(gcpKeyPath);
}
} else {
// 새로운 키 추가
String gcpKeyPath = gcpKeyContent != null && !gcpKeyContent.isEmpty()
? s3Service.uploadGcpKeyFile(email, gcpKeyContent)
: null;

AiwaKey newKey = new AiwaKey(companyName, accessKey, secretKey, gcpKeyPath, member);
member.getAiwaKeys().add(newKey);
// AWS 및 GCP 키 업데이트 또는 추가
AiwaKey aiwaKey = findOrCreateAiwaKey(member, companyName);

// AWS tfvars 파일 생성 및 URL 반환
String awsTfvarsUrl = s3Service.createAwsTfvarsFile(email, accessKey, secretKey);
aiwaKey.setAwsTfvarsUrl(awsTfvarsUrl);

// GCP 키 처리 (GCP 키가 제공된 경우에만 업데이트)
if (gcpKeyContent != null && !gcpKeyContent.isEmpty()) {
String gcpKeyPath = s3Service.uploadGcpKeyFile(email, gcpKeyContent);
aiwaKey.setGcpKeyPath(gcpKeyPath);
}

// 회원 정보 저장
Expand All @@ -95,9 +84,21 @@ public String addOrUpdateAwsAndGcpKey(String email, String companyName, String a
return String.format("%s keys have been successfully added or updated.", companyName);
}

// AiwaKey를 찾아서 없으면 새로 생성
private AiwaKey findOrCreateAiwaKey(Member member, String companyName) {
// 기존 키가 있으면 업데이트, 없으면 새로 생성
return member.getAiwaKeys().stream()
.filter(key -> companyName.equalsIgnoreCase(key.getCompanyName()))
.findFirst()
.orElseGet(() -> {
AiwaKey newKey = new AiwaKey(companyName, null, null, null, member);
member.getAiwaKeys().add(newKey);
return newKey;
});
}



// AWS 키 삭제
public Member removeAwsKey(Long memberId) {
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new RuntimeException("Member not found"));
Expand All @@ -107,7 +108,7 @@ public Member removeAwsKey(Long memberId) {
return memberRepository.save(member);
}


// GCP 키 삭제
public Member removeGcpKey(Long memberId) {
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new RuntimeException("Member not found"));
Expand All @@ -118,6 +119,4 @@ public Member removeGcpKey(Long memberId) {

return memberRepository.save(member);
}


}
}
54 changes: 42 additions & 12 deletions src/main/java/AIWA/MCPBackend_Member/Service/s3/S3Service.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
@RequiredArgsConstructor
Expand All @@ -15,13 +16,19 @@ public class S3Service {
private final AmazonS3 s3Client;
private final String bucketName = "aiwa-terraform";

// 사용자 디렉토리 생성
public void createUserDirectory(String userId) {
String userPrefix = "users/" + userId + "/";
uploadInitialFiles(userPrefix);
// 사용자 디렉토리 생성 (AWS와 GCP 디렉토리를 분리)
public void createUserAWSDirectory(String userId) {
String userPrefix = "users/" + userId + "/AWS/";
uploadAwsInitialFiles(userPrefix);
}

public void createUserGCPDirectory(String userId) {
String userPrefix = "users/" + userId + "/GCP/";
uploadGcpInitialFiles(userPrefix);
}

private void uploadInitialFiles(String userPrefix) {
// AWS 초기 파일 업로드
private void uploadAwsInitialFiles(String userPrefix) {
String mainTfContent = """
variable "aws_access_key" {
description = "AWS Access Key"
Expand All @@ -43,9 +50,33 @@ private void uploadInitialFiles(String userPrefix) {
s3Client.putObject(bucketName, userPrefix + "main.tf", mainTfContent);
}

// GCP 초기 파일 업로드
private void uploadGcpInitialFiles(String userPrefix) {
String mainTfContent = """
variable "gcp_project_id" {
description = "GCP Project ID"
type = string
}
variable "gcp_credentials" {
description = "GCP Credentials JSON file content"
type = string
sensitive = true
}
provider "google" {
project = var.gcp_project_id
region = "asia-northeast3"
credentials = var.gcp_credentials
}
""";

s3Client.putObject(bucketName, userPrefix + "main.tf", mainTfContent);
}

// AWS tfvars 파일 생성
public String createAwsTfvarsFile(String userId, String accessKey, String secretKey) {
String userPrefix = "users/" + userId + "/";
String userPrefix = "users/" + userId + "/AWS/";
String tfvarsContent = String.format("""
aws_access_key = "%s"
aws_secret_key = "%s"
Expand All @@ -58,7 +89,7 @@ public String createAwsTfvarsFile(String userId, String accessKey, String secret

// GCP 자격 증명 파일 업로드
public String uploadGcpKeyFile(String userId, String gcpKeyContent) {
String userPrefix = "users/" + userId + "/";
String userPrefix = "users/" + userId + "/GCP/";
String gcpKeyFileKey = userPrefix + "gcp_credentials.json";
byte[] gcpKeyBytes = gcpKeyContent.getBytes(StandardCharsets.UTF_8);

Expand All @@ -68,23 +99,23 @@ public String uploadGcpKeyFile(String userId, String gcpKeyContent) {

return s3Client.getUrl(bucketName, gcpKeyFileKey).toString(); // S3 URL 반환
}

// GCP 키 파일 삭제
public void deleteGcpKeyFile(String userId) {
String gcpKeyFileKey = "users/" + userId + "/gcp_credentials.json";
String gcpKeyFileKey = "users/" + userId + "/GCP/gcp_credentials.json";
if (s3Client.doesObjectExist(bucketName, gcpKeyFileKey)) {
s3Client.deleteObject(bucketName, gcpKeyFileKey);
}
}

// AWS tfvars 파일 삭제
public void deleteAwsTfvarsFile(String userId) {
String awsTfvarsKey = "users/" + userId + "/aws_terraform.tfvars";
String awsTfvarsKey = "users/" + userId + "/AWS/aws_terraform.tfvars";
if (s3Client.doesObjectExist(bucketName, awsTfvarsKey)) {
s3Client.deleteObject(bucketName, awsTfvarsKey);
}
}


// 사용자 디렉토리 삭제
public void deleteUserDirectory(String userId) {
String userPrefix = "users/" + userId + "/";
Expand All @@ -99,5 +130,4 @@ public void deleteUserDirectory(String userId) {
request.setContinuationToken(result.getNextContinuationToken());
} while (result.isTruncated());
}

}
}

0 comments on commit dfe29a9

Please sign in to comment.