Skip to content

Commit

Permalink
#Fix : Gcp 파일 자체로 등록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
gytjd committed Nov 20, 2024
1 parent 78f1e0d commit 4c32054
Show file tree
Hide file tree
Showing 4 changed files with 135 additions and 75 deletions.
151 changes: 86 additions & 65 deletions src/main/java/AIWA/MCPBackend_Member/Controller/MemberController.java
Original file line number Diff line number Diff line change
@@ -1,98 +1,119 @@
package AIWA.MCPBackend_Member.Controller;

import AIWA.MCPBackend_Member.Dto.AddAwsAndGcpKeyRequestDto;
import AIWA.MCPBackend_Member.Dto.MemberDeleteRequestDto;
import AIWA.MCPBackend_Member.Dto.MemberRequestDto;
import AIWA.MCPBackend_Member.Dto.*;
import AIWA.MCPBackend_Member.Entity.AiwaKey;
import AIWA.MCPBackend_Member.Entity.Member;
import AIWA.MCPBackend_Member.Service.member.MemberService;
import AIWA.MCPBackend_Member.Service.response.ResponseService;
import AIWA.MCPBackend_Member.response.CommonResult;
import AIWA.MCPBackend_Member.response.ListResult;
import AIWA.MCPBackend_Member.response.SingleResult;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/member/api/members")
@RequiredArgsConstructor
@RequestMapping("/member/api/members")
public class MemberController {

private final MemberService memberService;
private final ResponseService responseService;

// 회원 등록
@PostMapping("/register")
public ResponseEntity<String> registerMember(@RequestBody MemberRequestDto memberRequestDto) {
try {
memberService.registerMember(memberRequestDto);
return ResponseEntity.ok("Member registered successfully");
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
public SingleResult<MemberResponseDto> registerMember(@RequestBody MemberRequestDto memberRequestDto) {
// 회원 등록
Member savedMember = memberService.registerMember(memberRequestDto);
MemberResponseDto memberResponseDto = MemberResponseDto.toDto(savedMember);
return responseService.getSingleResult(memberResponseDto);
}

// 회원 삭제
@DeleteMapping("/delete")
public ResponseEntity<String> deleteMember(@RequestBody MemberDeleteRequestDto deleteMemberRequestDto) {
try {
memberService.deleteMember(deleteMemberRequestDto);
return ResponseEntity.ok("Member deleted successfully");
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
public CommonResult deleteMember(@RequestBody MemberDeleteRequestDto deleteMemberRequestDto) {
// 회원 삭제
memberService.deleteMember(deleteMemberRequestDto);
return responseService.getSuccessResult();
}

// AWS 및 GCP 키 추가/수정
@PostMapping("/add-keys")
public ResponseEntity<String> addOrUpdateAwsAndGcpKey(@RequestBody AddAwsAndGcpKeyRequestDto addAwsAndGcpKeyRequestDto) {
try {
String result = memberService.addOrUpdateAwsAndGcpKey(
addAwsAndGcpKeyRequestDto.getEmail(),
addAwsAndGcpKeyRequestDto.getCompanyName(),
addAwsAndGcpKeyRequestDto.getAccessKey(),
addAwsAndGcpKeyRequestDto.getSecretKey(),
addAwsAndGcpKeyRequestDto.getGcpKeyContent()
);
return ResponseEntity.ok(result);
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
// 모든 회원 조회
@GetMapping("/all")
public ListResult<MemberResponseDto> getAllMembers() {
// 모든 회원 조회
List<Member> members = memberService.getAllMembers();
List<MemberResponseDto> memberResponseDtoList = members.stream()
.map(MemberResponseDto::toDto)
.collect(Collectors.toList());
return responseService.getListResult(memberResponseDtoList);
}

// 회원 정보 조회
@GetMapping("/{email}")
public ResponseEntity<Object> getMemberByEmail(@PathVariable String email) {
try {
return ResponseEntity.ok(memberService.getMemberByEmail(email));
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(e.getMessage());
// 특정 회원 조회
@GetMapping("/{email}/{companyName}")
public SingleResult<MemberCredentialDto> getMemberKey(
@PathVariable String email,
@PathVariable String companyName) {

Member findMember = memberService.getMemberByEmail(email);
if (findMember == null) {
return (SingleResult<MemberCredentialDto>) responseService.getFailResult("Member not found");
}
}

// 모든 회원 조회
@GetMapping("/all")
public ResponseEntity<Object> getAllMembers() {
try {
return ResponseEntity.ok(memberService.getAllMembers());
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(e.getMessage());
Optional<AiwaKey> matchingKey = findMember.getAiwaKeys().stream()
.filter(key -> companyName.equalsIgnoreCase(key.getCompanyName()))
.findFirst();

if (matchingKey.isPresent()) {
AiwaKey aiwaKey = matchingKey.get();
MemberCredentialDto memberCredentialDto = new MemberCredentialDto(
findMember.getEmail(),
aiwaKey.getAccessKey(),
aiwaKey.getSecretKey()
);
return responseService.getSingleResult(memberCredentialDto);
} else {
return (SingleResult<MemberCredentialDto>) responseService.getFailResult("No key found for company: " + companyName);
}
}

// AWS 및 GCP 키 추가/업데이트
@PostMapping("/add-aws-gcp-key")
public SingleResult<String> addAwsAndGcpKey(
@RequestParam String email,
@RequestParam String companyName,
@RequestParam String accessKey,
@RequestParam String secretKey,
@RequestParam String projectId,
@RequestParam(required = false) MultipartFile gcpKeyFile) throws IOException {

// GCP 자격 증명 파일을 포함하여 AWS 및 GCP 키 처리
String result = memberService.addOrUpdateAwsAndGcpKey(
email,
companyName,
accessKey,
secretKey,
projectId,
gcpKeyFile
);
return responseService.getSingleResult(result);
}

// AWS 키 삭제
@DeleteMapping("/remove/aws/{memberId}")
public ResponseEntity<String> removeAwsKey(@PathVariable Long memberId) {
try {
memberService.removeAwsKey(memberId);
return ResponseEntity.ok("AWS key removed successfully");
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
@DeleteMapping("/delete-aws-key")
public CommonResult deleteAwsKey(@RequestBody DeleteKeyRequestDto deleteKeyRequestDto) {
memberService.removeAwsKey(deleteKeyRequestDto.getMemberId());
return responseService.getSuccessResult();
}

// GCP 키 삭제
@DeleteMapping("/remove/gcp/{memberId}")
public ResponseEntity<String> removeGcpKey(@PathVariable Long memberId) {
try {
memberService.removeGcpKey(memberId);
return ResponseEntity.ok("GCP key removed successfully");
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
@DeleteMapping("/delete-gcp-key")
public CommonResult deleteGcpKey(@RequestBody DeleteKeyRequestDto deleteKeyRequestDto) {
memberService.removeGcpKey(deleteKeyRequestDto.getMemberId());
return responseService.getSuccessResult();
}
}
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 @@ -25,6 +25,8 @@ public class AiwaKey {

private String awsTfvarsUrl;

private String gcpTfvarsUrl;

@ManyToOne
@JoinColumn(name = "member_id")
private Member member;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import AIWA.MCPBackend_Member.Service.s3.S3Service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -59,7 +61,7 @@ public List<Member> getAllMembers() {
}

// AWS 및 GCP 키 추가/수정
public String addOrUpdateAwsAndGcpKey(String email, String companyName, String accessKey, String secretKey, String gcpKeyContent) {
public String addOrUpdateAwsAndGcpKey(String email, String companyName, String accessKey, String secretKey, String projectId, MultipartFile gcpKeyFile) throws IOException {
// 회원 조회
Member member = getMemberByEmail(email);
if (member == null) {
Expand All @@ -74,9 +76,14 @@ public String addOrUpdateAwsAndGcpKey(String email, String companyName, String a
aiwaKey.setAwsTfvarsUrl(awsTfvarsUrl);

// GCP 키 처리 (GCP 키가 제공된 경우에만 업데이트)
if (gcpKeyContent != null && !gcpKeyContent.isEmpty()) {
String gcpKeyPath = s3Service.uploadGcpKeyFile(email, gcpKeyContent);
if (gcpKeyFile != null && !gcpKeyFile.isEmpty()) {
// GCP 자격 증명 파일 업로드
String gcpKeyPath = s3Service.uploadGcpKeyFile(email, gcpKeyFile);
aiwaKey.setGcpKeyPath(gcpKeyPath);

// GCP tfvars 파일 생성 및 URL 반환
String gcpTfvarsUrl = s3Service.createGcpTfvarsFile(email,projectId); // GCP tfvars 생성
aiwaKey.setGcpTfvarsUrl(gcpTfvarsUrl);
}

// 회원 정보 저장
Expand Down Expand Up @@ -117,6 +124,9 @@ public Member removeGcpKey(Long memberId) {
member.getAiwaKeys().removeIf(key -> "GCP".equalsIgnoreCase(key.getCompanyName()));
s3Service.deleteGcpKeyFile(member.getEmail());

// GCP tfvars 파일 삭제
s3Service.deleteGcpTfvarsFile(member.getEmail());

return memberRepository.save(member);
}
}
41 changes: 34 additions & 7 deletions src/main/java/AIWA/MCPBackend_Member/Service/s3/S3Service.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
import com.amazonaws.services.s3.model.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -87,15 +87,34 @@ public String createAwsTfvarsFile(String userId, String accessKey, String secret
return s3Client.getUrl(bucketName, tfvarsKey).toString(); // S3 URL 반환
}

// GCP tfvars 파일 생성
public String createGcpTfvarsFile(String userId, String gcpProjectId) {
String userPrefix = "users/" + userId + "/GCP/";
String tfvarsContent = String.format("""
gcp_project_id = "%s"
gcp_credentials = "users/%s/GCP/gcp_credentials.json"
""", gcpProjectId, userId);

String tfvarsKey = userPrefix + "gcp_terraform.tfvars";
s3Client.putObject(bucketName, tfvarsKey, tfvarsContent);
return s3Client.getUrl(bucketName, tfvarsKey).toString(); // S3 URL 반환
}

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

// MultipartFile에서 InputStream을 추출
InputStream inputStream = file.getInputStream();

// 파일 메타데이터 설정
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(gcpKeyBytes.length);
s3Client.putObject(bucketName, gcpKeyFileKey, new ByteArrayInputStream(gcpKeyBytes), metadata);
metadata.setContentLength(file.getSize());
metadata.setContentType(file.getContentType());

// S3에 파일 업로드
s3Client.putObject(bucketName, gcpKeyFileKey, inputStream, metadata);

return s3Client.getUrl(bucketName, gcpKeyFileKey).toString(); // S3 URL 반환
}
Expand All @@ -116,6 +135,14 @@ public void deleteAwsTfvarsFile(String userId) {
}
}

// GCP tfvars 파일 삭제
public void deleteGcpTfvarsFile(String userId) {
String gcpTfvarsKey = "users/" + userId + "/GCP/gcp_terraform.tfvars";
if (s3Client.doesObjectExist(bucketName, gcpTfvarsKey)) {
s3Client.deleteObject(bucketName, gcpTfvarsKey);
}
}

// 사용자 디렉토리 삭제
public void deleteUserDirectory(String userId) {
String userPrefix = "users/" + userId + "/";
Expand Down

0 comments on commit 4c32054

Please sign in to comment.