From 3014a89771ed9cf3a9758d7b386ec5f372fb533c Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 17 Jul 2023 14:13:44 +0900 Subject: [PATCH 01/63] Revert "Merge remote-tracking branch 'origin/feature/#17-blueprint' into feature/#17-blueprint" This reverts commit 9f42d0be8d1aa6cec1d60c02fb5cf28dcefc995f. --- .../cloud/blueprint/BlueprintController.java | 57 ++---- .../cloud/blueprint/domain/ComponentDot.java | 39 +++-- .../domain/aws/AwsComponentType.java | 2 +- .../blueprint/dto/aws/AwsBluePrintDto.java | 38 ++-- .../dto/aws/AwsBluePrintListDto.java | 14 -- .../aws/AwsBluePrintRepository.java | 7 - .../service/AwsBlueprintService.java | 7 +- .../service/AwsBlueprintServiceImpl.java | 114 ++++++------ .../middleware/AuthorizationFromToken.java | 4 + .../auth/AuthorizationFromTokenAspect.java | 77 +++++---- .../infra/service/aws_cdk/Ec2ServiceImpl.java | 43 +++++ .../infra/service/aws_cdk/stack/Ec2Stack.java | 16 ++ .../cloud/jwt/provider/JwtTokenProvider.java | 1 - .../cloud/member/MemberRepository.java | 4 +- .../cloud/member/domain/Member.java | 28 +-- .../cloud/oauth/service/OAuthService.java | 162 ++++++++---------- 16 files changed, 309 insertions(+), 304 deletions(-) delete mode 100644 src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java create mode 100644 src/main/java/com/kumofactory/cloud/global/middleware/AuthorizationFromToken.java create mode 100644 src/main/java/com/kumofactory/cloud/infra/service/aws_cdk/Ec2ServiceImpl.java create mode 100644 src/main/java/com/kumofactory/cloud/infra/service/aws_cdk/stack/Ec2Stack.java diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index e00534c..9dafc31 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -2,56 +2,37 @@ import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; -import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; -import com.kumofactory.cloud.global.middleware.auth.AuthorizationFromToken; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; -import java.util.List; - @RestController @RequiredArgsConstructor @RequestMapping("/blueprint") @Slf4j public class BlueprintController { - private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); - private final AwsBlueprintService awsBlueprintService; - - @GetMapping("/aws/{id}") - @AuthorizationFromToken - public AwsBluePrintDto getAwsBlueprint(@PathVariable("id") Long id, String userId) { - try { - logger.info("aws blue print id: {}", id); - AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); - return awsBlueprint; - } catch (RuntimeException e) { - return null; - } - } - - @GetMapping("/aws/list") - @AuthorizationFromToken - public List getAwsBlueprintList(String userId) { - logger.info("userId: {}", userId); - return awsBlueprintService.getMyAwsBlueprints(userId); - } + private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); + private final AwsBlueprintService awsBlueprintService; - @PostMapping("/aws") - @AuthorizationFromToken - public String createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) { - logger.info(userId); - awsBlueprintService.store(awsBluePrintDto, userId); - return "hello-world"; - } + // TODO : 토큰에서 유저 정보 가져오는 로직 추가 + // TODO : blueprint list 주는 api 추가 + // TODO : blueprint id 값으로 blueprint 가져오는 api 추가 + @GetMapping("/aws") + public AwsBluePrintDto getAwsBlueprint() { + try { + AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(); + return awsBlueprint; + } catch (RuntimeException e) { + return null; + } + } - @GetMapping("/test") - @AuthorizationFromToken - public String testMiddleware(String userId) { - System.out.printf("userId: %s\n", userId); - return userId; - } + @PostMapping("/aws") + public String createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto) { + awsBlueprintService.store(awsBluePrintDto); + return "hello-world"; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/ComponentDot.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/ComponentDot.java index 5f8fd92..1e7f557 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/ComponentDot.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/ComponentDot.java @@ -8,7 +8,10 @@ import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; -import javax.persistence.*; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; import java.util.Date; @Entity @@ -17,24 +20,24 @@ @NoArgsConstructor @AllArgsConstructor public class ComponentDot { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - @CreationTimestamp - private Date created_at; - @UpdateTimestamp - private Date updated_at; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @CreationTimestamp + private Date created_at; + @UpdateTimestamp + private Date updated_at; - private Integer x; // 점의 x 좌표 - private Integer y; // 점의 y 좌표 - private String componentId; // 점이 속한 컴포넌트의 id + private Integer x; // 점의 x 좌표 + private Integer y; // 점의 y 좌표 + private String componentId; // 점이 속한 컴포넌트의 id - public static ComponentDot createComponentDot(ComponentDotDto componentDotDto) { - ComponentDot componentDot = new ComponentDot(); - componentDot.setComponentId(componentDotDto.getComponentId()); - componentDot.setX(componentDotDto.getX()); - componentDot.setY(componentDotDto.getY()); - return componentDot; - } + public static ComponentDot createComponentDot(ComponentDotDto componentDotDto) { + ComponentDot componentDot = new ComponentDot(); + componentDot.setComponentId(componentDotDto.getComponentId()); + componentDot.setX(componentDotDto.getX()); + componentDot.setY(componentDotDto.getY()); + return componentDot; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java index 51499cc..e5221ad 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java @@ -1,5 +1,5 @@ package com.kumofactory.cloud.blueprint.domain.aws; public enum AwsComponentType { - VPC, SUBNET, ELB, EC2, EFS, WAF, ROUTE53, NAT_GATEWAY, RDS, S3, ElastiCache, CloudFront, AutoScaling + VPC, SUBNET, ELB, EC2, EFS, WAF, ROUTE53, NAT_GATEWAY, RDS, } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index eb73f6d..91d662e 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -13,23 +13,23 @@ @Data public class AwsBluePrintDto { - private String name; - private List components; - private List links; - - public static List awsComponentDtosMapper(List awsComponentDtos) { - List awsComponentDtoList = new ArrayList<>(); - for (AwsComponent awsComponent : awsComponentDtos) { - awsComponentDtoList.add(AwsComponentDto.mapper(awsComponent)); - } - return awsComponentDtoList; - } - - public static List componentLinkDtoListMapper(List componentLinks) { - List componentLinkDtoList = new ArrayList<>(); - for (ComponentLine pointLink : componentLinks) { - componentLinkDtoList.add(ComponentLineDto.mapper(pointLink)); - } - return componentLinkDtoList; - } + private String name; + private List components; + private List links; + + public static List awsComponentDtosMapper(List awsComponentDtos) { + List awsComponentDtoList = new ArrayList<>(); + for (AwsComponent awsComponent : awsComponentDtos) { + awsComponentDtoList.add(AwsComponentDto.mapper(awsComponent)); + } + return awsComponentDtoList; + } + + public static List componentLinkDtoListMapper(List componentLinks) { + List componentLinkDtoList = new ArrayList<>(); + for (ComponentLine pointLink : componentLinks) { + componentLinkDtoList.add(ComponentLineDto.mapper(pointLink)); + } + return componentLinkDtoList; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java deleted file mode 100644 index 99bec33..0000000 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.kumofactory.cloud.blueprint.dto.aws; - -import lombok.Getter; -import lombok.Setter; - -import java.util.Date; - -@Getter -@Setter -public class AwsBluePrintListDto { - private Long id; - private String name; - private Date createdAt; -} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java b/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java index c8ddacf..8bb149f 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java @@ -1,17 +1,10 @@ package com.kumofactory.cloud.blueprint.repository.aws; import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; -import com.kumofactory.cloud.member.domain.Member; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.util.List; - @Repository public interface AwsBluePrintRepository extends JpaRepository { AwsBluePrint findAwsBluePrintById(long id); - - AwsBluePrint findAwsBluePrintByMemberId(long memberId); - - List findAwsBluePrintsByMember(Member member); } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java index 9e1f8c3..3354151 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java @@ -3,15 +3,14 @@ import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; -import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; import java.util.List; public interface AwsBlueprintService { - AwsBluePrintDto getAwsBlueprint(Long bluePrintId); + AwsBluePrintDto getAwsBlueprint(); - List getMyAwsBlueprints(String userId); + List getMyAwsBlueprints(); - void store(AwsBluePrintDto awsBluePrintDto, String userId); + void store(AwsBluePrintDto awsBluePrintDto); } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 28fef92..e1f712b 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -6,14 +6,12 @@ import com.kumofactory.cloud.blueprint.dto.ComponentLineDto; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; -import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; import com.kumofactory.cloud.blueprint.dto.aws.AwsComponentDto; import com.kumofactory.cloud.blueprint.repository.ComponentDotRepository; import com.kumofactory.cloud.blueprint.repository.ComponentLineRepository; import com.kumofactory.cloud.blueprint.repository.aws.AwsBluePrintRepository; import com.kumofactory.cloud.blueprint.repository.aws.AwsComponentRepository; import com.kumofactory.cloud.member.MemberRepository; -import com.kumofactory.cloud.member.domain.Member; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; @@ -30,75 +28,63 @@ @Repository public class AwsBlueprintServiceImpl implements AwsBlueprintService { - private final MemberRepository memberRepository; - private final AwsBluePrintRepository awsBluePrintRepository; - private final AwsComponentRepository awsComponentRepository; - private final ComponentLineRepository componentLineRepository; - private final ComponentDotRepository componentDotRepository; - private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); + private final MemberRepository memberRepository; + private final AwsBluePrintRepository awsBluePrintRepository; + private final AwsComponentRepository awsComponentRepository; + private final ComponentLineRepository componentLineRepository; + private final ComponentDotRepository componentDotRepository; + private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); - @Override - public AwsBluePrintDto getAwsBlueprint(Long bluePrintId) { - AwsBluePrint awsBluePrintById = awsBluePrintRepository.findAwsBluePrintById(bluePrintId); - if (awsBluePrintById == null) { - throw new RuntimeException("awsBluePrintById is null"); - } + @Override + public AwsBluePrintDto getAwsBlueprint() { + AwsBluePrint awsBluePrintById = awsBluePrintRepository.findAwsBluePrintById(1L); + logger.info("awsBluePrintById: {}", awsBluePrintById); + if (awsBluePrintById == null) { + throw new RuntimeException("awsBluePrintById is null"); + } - List awsComponents = awsComponentRepository.findAllByBluePrint(awsBluePrintById); - List componentLines = componentLineRepository.findAllByBluePrint(awsBluePrintById); - AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); - awsBluePrintDto.setName(awsBluePrintById.getName()); - awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); - awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); - return awsBluePrintDto; - } + List awsComponents = awsComponentRepository.findAllByBluePrint(awsBluePrintById); + List componentLines = componentLineRepository.findAllByBluePrint(awsBluePrintById); + AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); + awsBluePrintDto.setName(awsBluePrintById.getName()); + awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); + awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); + return awsBluePrintDto; + } - @Override - public List getMyAwsBlueprints(String oauthId) { - Member member = memberRepository.findMemberByOauthId(oauthId); - if (member == null) { - throw new RuntimeException("member is null"); - } + @Override + public List getMyAwsBlueprints() { + return null; + } - List awsBluePrints = awsBluePrintRepository.findAwsBluePrintsByMember(member); - List awsBluePrintDtos = new ArrayList<>(); - for (AwsBluePrint awsBluePrint : awsBluePrints) { - AwsBluePrintListDto dto = new AwsBluePrintListDto(); - dto.setName(awsBluePrint.getName()); - dto.setId(awsBluePrint.getId()); - dto.setCreatedAt(awsBluePrint.getCreated_at()); - awsBluePrintDtos.add(dto); - } - return awsBluePrintDtos; - } + @Override + public void store(AwsBluePrintDto awsBluePrintDto) { +// Member member = memberRepository.findMemberById(1L); - @Override - public void store(AwsBluePrintDto awsBluePrintDto, String userId) { - Member member = memberRepository.findMemberByOauthId(userId); - // BluePrint 저장 - AwsBluePrint awsBluePrint = new AwsBluePrint(); - awsBluePrint.setName(awsBluePrintDto.getName()); - awsBluePrint.setMember(member); - AwsBluePrint savedBlueprint = awsBluePrintRepository.save(awsBluePrint); - logger.info("savedBlueprint: {}", savedBlueprint); + // BluePrint 저장 + AwsBluePrint awsBluePrint = new AwsBluePrint(); + awsBluePrint.setName(awsBluePrintDto.getName()); +// awsBluePrint.setMember(member); + AwsBluePrint savedBlueprint = awsBluePrintRepository.save(awsBluePrint); + logger.info("savedBlueprint: {}", savedBlueprint); - List components = new ArrayList<>(); - List links = awsBluePrintDto.getLinks(); + List components = new ArrayList<>(); + List links = awsBluePrintDto.getLinks(); - // Components 저장 - for (AwsComponentDto component : awsBluePrintDto.getComponents()) { - AwsComponent awsComponent = AwsComponent.createAwsComponent(component, savedBlueprint); - components.add(awsComponent); - } - awsComponentRepository.saveAll(components); + // Components 저장 + for (AwsComponentDto component : awsBluePrintDto.getComponents()) { + AwsComponent awsComponent = AwsComponent.createAwsComponent(component, savedBlueprint); + components.add(awsComponent); + } + awsComponentRepository.saveAll(components); - // Lines 저장 - List componentLines = new ArrayList<>(); - for (ComponentLineDto link : links) { - ComponentLine componentLink = ComponentLine.createComponentLink(link, savedBlueprint); - componentLines.add(componentLink); - } - componentLineRepository.saveAll(componentLines); - } + // Lines 저장 + List componentLines = new ArrayList<>(); + for (ComponentLineDto link : links) { + ComponentLine componentLink = ComponentLine.createComponentLink(link, savedBlueprint); + componentLines.add(componentLink); + } + componentLineRepository.saveAll(componentLines); + } } diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/AuthorizationFromToken.java b/src/main/java/com/kumofactory/cloud/global/middleware/AuthorizationFromToken.java new file mode 100644 index 0000000..37edd75 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/middleware/AuthorizationFromToken.java @@ -0,0 +1,4 @@ +package com.kumofactory.cloud.global.middleware; + +public class AuthorizationFromToken { +} diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java index dfc48f3..64f90a9 100644 --- a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java +++ b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java @@ -2,53 +2,62 @@ import com.kumofactory.cloud.jwt.provider.JwtTokenProvider; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; -import java.util.Objects; @Aspect @Component @RequiredArgsConstructor -@Slf4j public class AuthorizationFromTokenAspect { - private final JwtTokenProvider jwtTokenProvider; - private final Logger logger = LoggerFactory.getLogger(AuthorizationFromTokenAspect.class); - - @Around(value = "@annotation(AuthorizationFromToken)") - public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, AuthorizationFromToken AuthorizationFromToken) throws Throwable { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); - String userId = getUserFromAccessToken(request.getHeader("Authorization")); - if (userId == null) { - throw new RuntimeException("유효하지 않은 토큰입니다."); - } - // 추출된 사용자 정보를 매개변수로 전달 - Object[] args = joinPoint.getArgs(); - args[args.length - 1] = userId; - - return joinPoint.proceed(args); - } - - // user oauth id 추출 - private String getUserFromAccessToken(String token) { - String accessToken = token.split(" ")[1]; - boolean isValidate = jwtTokenProvider.validateAccessToken(accessToken); - if (isValidate) { - return jwtTokenProvider.getClaimsFormToken(accessToken).getSubject(); - } - return null; - } + private final JwtTokenProvider jwtTokenProvider; + + @Around(value = "@annotation(AuthorizationFromToken)") + public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, AuthorizationFromToken AuthorizationFromToken) throws Throwable { + HttpServletRequest request = findHttpServletRequest(joinPoint.getArgs()); + HttpServletRequest header = findHttpServletRequest(joinPoint.getArgs()); + String accessToken = extractAccessTokenFromCookies(request.getCookies()); + String userId = getUserFromAccessToken(accessToken); + + // 추출된 사용자 정보를 매개변수로 전달 + Object[] args = joinPoint.getArgs(); + args[0] = userId; + + return joinPoint.proceed(args); + } + + private HttpServletRequest findHttpServletRequest(Object[] args) { + for (Object arg : args) { + if (arg instanceof HttpServletRequest) { + return (HttpServletRequest) arg; + } + } + throw new IllegalArgumentException("HttpServletRequest not found in method parameters"); + } + + private String extractAccessTokenFromCookies(Cookie[] cookies) { + if (cookies != null) { + return Arrays.stream(cookies) + .filter(cookie -> "access_token".equals(cookie.getName())) + .map(Cookie::getValue) + .findFirst() + .orElse(null); + } + return null; + } + + private String getUserFromAccessToken(String accessToken) { + boolean isValidate = jwtTokenProvider.validateAccessToken(accessToken); + if (isValidate) { + return jwtTokenProvider.getClaimsFormToken(accessToken).getSubject(); + } + return null; + } } diff --git a/src/main/java/com/kumofactory/cloud/infra/service/aws_cdk/Ec2ServiceImpl.java b/src/main/java/com/kumofactory/cloud/infra/service/aws_cdk/Ec2ServiceImpl.java new file mode 100644 index 0000000..e736e8c --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/infra/service/aws_cdk/Ec2ServiceImpl.java @@ -0,0 +1,43 @@ +package com.kumofactory.cloud.infra.service.aws_cdk; + +import java.util.ArrayList; +import java.util.List; + +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import software.amazon.awscdk.services.ec2.BastionHostLinux; +import software.amazon.awscdk.services.ec2.BastionHostLinuxProps; +import software.amazon.awscdk.services.ec2.SubnetFilter; +import software.amazon.awscdk.services.ec2.SubnetSelection; +import software.amazon.awscdk.services.ec2.SubnetSelection.Builder; +import software.amazon.awscdk.services.ec2.Instance; + +/** + * AWS CDK를 이용한 EC2 서비스 + */ +@Service +@Slf4j +public class Ec2ServiceImpl implements Ec2Service { + + private final Logger logger = LoggerFactory.getLogger(Ec2ServiceImpl.class); + + @Override + public void createBastionHostLinux() { + logger.info("================ Create BastionHostLinux Instance ================"); + List subnetsId = new ArrayList<>(); + List subnetFilters = new ArrayList<>(); + subnetsId.add("subnet-043aec505f84e38ac"); + SubnetFilter subnetFilter = SubnetFilter.byIds(subnetsId); + subnetFilters.add(subnetFilter); + BastionHostLinuxProps.builder().subnetSelection(SubnetSelection.builder().subnetFilters(subnetFilters).build()); + } + + @Override + public void createEc2Instance() { + logger.info("================ Create EC2 Instance ================"); + + + } +} diff --git a/src/main/java/com/kumofactory/cloud/infra/service/aws_cdk/stack/Ec2Stack.java b/src/main/java/com/kumofactory/cloud/infra/service/aws_cdk/stack/Ec2Stack.java new file mode 100644 index 0000000..1cdb2cd --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/infra/service/aws_cdk/stack/Ec2Stack.java @@ -0,0 +1,16 @@ +package com.kumofactory.cloud.infra.service.aws_cdk.stack; + +import software.amazon.awscdk.Stack; +import software.amazon.awscdk.services.ec2.ISubnet; +import software.amazon.awscdk.services.ec2.Subnet; +import software.amazon.awscdk.services.ec2.Vpc; +import software.amazon.awscdk.services.ec2.VpcLookupOptions; +import software.constructs.Construct; + +public class Ec2Stack extends Stack { + public Ec2Stack(final Construct scope, String id) { + super(scope, id); + Vpc vpc = (Vpc) Vpc.fromLookup(this, "KumofactoryVPC", VpcLookupOptions.builder().vpcId("vpc-0719a1184fa5ccdcd").build()); + ISubnet kumofactorySubnet = Subnet.fromSubnetId(this, "KumofactorySubnet", "subnet-043aec505f84e38ac"); + } +} diff --git a/src/main/java/com/kumofactory/cloud/jwt/provider/JwtTokenProvider.java b/src/main/java/com/kumofactory/cloud/jwt/provider/JwtTokenProvider.java index 085c995..be96706 100644 --- a/src/main/java/com/kumofactory/cloud/jwt/provider/JwtTokenProvider.java +++ b/src/main/java/com/kumofactory/cloud/jwt/provider/JwtTokenProvider.java @@ -73,7 +73,6 @@ public boolean validateRefreshToken(String token) { } } - // TODO : Refresh Token API 구현 public String refreshAccessToken(Claims claims) { String id = claims.getSubject(); diff --git a/src/main/java/com/kumofactory/cloud/member/MemberRepository.java b/src/main/java/com/kumofactory/cloud/member/MemberRepository.java index 9e0024f..594b50e 100644 --- a/src/main/java/com/kumofactory/cloud/member/MemberRepository.java +++ b/src/main/java/com/kumofactory/cloud/member/MemberRepository.java @@ -6,7 +6,5 @@ @Repository public interface MemberRepository extends JpaRepository { - Member findMemberById(Long id); - - Member findMemberByOauthId(String oauth_id); + Member findMemberById(Long id); } diff --git a/src/main/java/com/kumofactory/cloud/member/domain/Member.java b/src/main/java/com/kumofactory/cloud/member/domain/Member.java index 0055d94..ab53028 100644 --- a/src/main/java/com/kumofactory/cloud/member/domain/Member.java +++ b/src/main/java/com/kumofactory/cloud/member/domain/Member.java @@ -20,22 +20,22 @@ @Setter public class Member { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - private String oauthId; + private String oauth_id; - private String provider; + private String provider; - @OneToMany(mappedBy = "member") - private List bluePrints; + @OneToMany(mappedBy = "member") + private List bluePrints; - // =========== 생성함수 =========== // - public static Member createMember(UserInfoDto userInfoDto) { - Member member = new Member(); - member.setOauthId(userInfoDto.id()); - member.setProvider(userInfoDto.provider()); - return member; - } + // =========== 생성함수 =========== // + public static Member createMember(UserInfoDto userInfoDto) { + Member member = new Member(); + member.setOauth_id(userInfoDto.id()); + member.setProvider(userInfoDto.provider()); + return member; + } } diff --git a/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java b/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java index 19dcd74..ac3a01e 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java +++ b/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java @@ -4,12 +4,9 @@ import com.kumofactory.cloud.config.OAuthProvider; import com.kumofactory.cloud.jwt.dto.TokenDto; import com.kumofactory.cloud.jwt.provider.JwtTokenProvider; -import com.kumofactory.cloud.member.MemberRepository; -import com.kumofactory.cloud.member.domain.Member; import com.kumofactory.cloud.oauth.dto.UserInfoDto; import com.kumofactory.cloud.oauth.service.github.GitHubService; import com.kumofactory.cloud.oauth.service.google.GoogleService; - import static com.kumofactory.cloud.oauth.dto.OAuthDto.*; import lombok.extern.slf4j.Slf4j; @@ -28,88 +25,79 @@ @Slf4j @RequiredArgsConstructor public class OAuthService { - private final GoogleService googleService; - private final GitHubService githubService; - - private final JwtTokenProvider jwtTokenProvider; - private final MemberRepository memberRepository; - - private TokenDto token; - - public ResponseEntity request(OAuthProvider provider, String code) - throws JsonProcessingException { - - HttpHeaders responseHeaders = new HttpHeaders(); - - switch (provider) { - case GOOGLE: { - token = getAccessTokenFromGoogle(code); - break; - } - case GITHUB: { - token = getAccessTokenFromGitHub(code); - break; - } - default: { - throw new IllegalArgumentException("Unknown type of social login."); - } - } - - responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); - - ResponseCookie refreshTokenCookie = ResponseCookie - .from("refreshToken", token.getRefreshToken()) - .httpOnly(true) - .path("/") - .maxAge(Duration.ofDays(365)) - .build(); - - responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); - - Map map = new HashMap<>(); - map.put("accessToken", token.getAccessToken()); - - return ResponseEntity.ok() - .headers(responseHeaders) - .body(new ObjectMapper().writeValueAsString(map)); - } - - // TODO : 중복된 코드 간소화 (getAccessTokenFromXXX) - private TokenDto getAccessTokenFromGoogle(String code) - throws JsonProcessingException { - - GoogleToken accessTokenFromGoogle = googleService.requestAccessToken(code); - if (accessTokenFromGoogle != null) { - - UserInfoDto userInfo = googleService.requestUserInfo(accessTokenFromGoogle.accessToken()); - saveMember(userInfo); - - return jwtTokenProvider.create(userInfo.id()); - } - return null; - } - - private TokenDto getAccessTokenFromGitHub(String code) - throws JsonProcessingException { - - GitHubToken accessTokenFromGithub = githubService.requestAccessToken(code); - if (accessTokenFromGithub != null) { - - UserInfoDto userInfo = githubService.requestUserInfo(accessTokenFromGithub.accessToken()); - saveMember(userInfo); - - - return jwtTokenProvider.create(userInfo.id()); - } - return null; - } - - // 처음 가입한 member 일때만 저장 - private void saveMember(UserInfoDto userInfo) { - Member member = memberRepository.findMemberByOauthId(userInfo.id()); - if (member == null) { - member = Member.createMember(userInfo); - memberRepository.save(member); - } - } + private final GoogleService googleService; + private final GitHubService githubService; + + private final JwtTokenProvider jwtTokenProvider; + + private TokenDto token; + + public ResponseEntity request(OAuthProvider provider, String code) + throws JsonProcessingException { + + HttpHeaders responseHeaders = new HttpHeaders(); + + switch (provider) { + case GOOGLE:{ + token = getAccessTokenFromGoogle(code); + break; + } + case GITHUB:{ + token = getAccessTokenFromGitHub(code); + break; + } + default:{ + throw new IllegalArgumentException("Unknown type of social login."); + } + } + + responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); + + ResponseCookie refreshTokenCookie = ResponseCookie + .from("refreshToken", token.getRefreshToken()) + .httpOnly(true) + .path("/") + .maxAge(Duration.ofDays(365)) + .build(); + + responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); + + Map map = new HashMap<>(); + map.put("accessToken", token.getAccessToken()); + + return ResponseEntity.ok() + .headers(responseHeaders) + .body(new ObjectMapper().writeValueAsString(map)); + } + + // TODO : 중복된 코드 간소화 (getAccessTokenFromXXX) + private TokenDto getAccessTokenFromGoogle(String code) + throws JsonProcessingException{ + + GoogleToken accessTokenFromGoogle = googleService.requestAccessToken(code); + if(accessTokenFromGoogle != null) { + + UserInfoDto userInfo = googleService.requestUserInfo(accessTokenFromGoogle.accessToken()); + TokenDto token = jwtTokenProvider.create(userInfo.id()); + + return token; + } + assert accessTokenFromGoogle != null; + return null; + } + + private TokenDto getAccessTokenFromGitHub(String code) + throws JsonProcessingException{ + + GitHubToken accessTokenFromGithub = githubService.requestAccessToken(code); + if(accessTokenFromGithub != null) { + + UserInfoDto userInfo = githubService.requestUserInfo(accessTokenFromGithub.accessToken()); + TokenDto token = jwtTokenProvider.create(userInfo.id()); + + return token; + } + assert accessTokenFromGithub != null; + return null; + } } From 582fda63c940983033679b774beb48f668812c2b Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 17 Jul 2023 21:33:53 +0900 Subject: [PATCH 02/63] feat : add refresh token from cookie --- .../cloud/auth/AuthController.java | 55 +++++++++++++++++++ .../kumofactory/cloud/auth/AuthService.java | 7 +++ .../cloud/auth/AuthServiceImpl.java | 38 +++++++++++++ .../cloud/{ => auth}/jwt/dto/TokenDto.java | 0 .../jwt/provider/JwtTokenProvider.java | 2 +- .../repository/RefreshTokenRepository.java | 0 6 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/kumofactory/cloud/auth/AuthController.java create mode 100644 src/main/java/com/kumofactory/cloud/auth/AuthService.java create mode 100644 src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java rename src/main/java/com/kumofactory/cloud/{ => auth}/jwt/dto/TokenDto.java (100%) rename src/main/java/com/kumofactory/cloud/{ => auth}/jwt/provider/JwtTokenProvider.java (97%) rename src/main/java/com/kumofactory/cloud/{ => auth}/jwt/repository/RefreshTokenRepository.java (100%) diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthController.java b/src/main/java/com/kumofactory/cloud/auth/AuthController.java new file mode 100644 index 0000000..dbb0014 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/auth/AuthController.java @@ -0,0 +1,55 @@ +package com.kumofactory.cloud.auth; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.kumofactory.cloud.auth.jwt.dto.TokenDto; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseCookie; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import java.util.HashMap; +import java.util.Map; + +@Controller +@RequestMapping("/auth") +@Slf4j +@RequiredArgsConstructor +public class AuthController { + private final AuthService authService; + + @GetMapping("/refresh") + public ResponseEntity refresh(HttpServletRequest request) throws JsonProcessingException { + Cookie[] cookies = request.getCookies(); + String refreshToken = null; + for (Cookie cookie : cookies) { + if (cookie.getName().equals("refreshToken")) { + log.info("refreshToken: {}", cookie.getValue()); + refreshToken = cookie.getValue(); + break; + } + } + TokenDto token = authService.refresh(refreshToken); + HttpHeaders responseHeaders = new HttpHeaders(); + ResponseCookie refreshTokenCookie = ResponseCookie.from("refreshToken", token.getRefreshToken()) + .httpOnly(true) + .path("/") + .maxAge(60 * 60 * 24 * 30) + .build(); + responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); + responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); + Map map = new HashMap<>(); + map.put("accessToken", token.getAccessToken()); + + + return ResponseEntity.ok() + .headers(responseHeaders) + .body(new ObjectMapper().writeValueAsString(map)); + } +} diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthService.java b/src/main/java/com/kumofactory/cloud/auth/AuthService.java new file mode 100644 index 0000000..a134a4f --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/auth/AuthService.java @@ -0,0 +1,7 @@ +package com.kumofactory.cloud.auth; + +import com.kumofactory.cloud.auth.jwt.dto.TokenDto; + +public interface AuthService { + TokenDto refresh(String refreshToken); +} diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java b/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java new file mode 100644 index 0000000..9f401b1 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java @@ -0,0 +1,38 @@ +package com.kumofactory.cloud.auth; + +import com.kumofactory.cloud.auth.jwt.dto.TokenDto; +import com.kumofactory.cloud.auth.jwt.provider.JwtTokenProvider; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.JwtException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +@Slf4j +public class AuthServiceImpl implements AuthService { + private final JwtTokenProvider jwtTokenProvider; + + @Override + public TokenDto refresh(String refreshToken) { + if (refreshToken == null) { + throw new RuntimeException("Token is null"); + } + + try { + boolean isValidToken = jwtTokenProvider.validateToken(refreshToken); + if (isValidToken) { + Claims claims = jwtTokenProvider.getClaimsFormToken(refreshToken); + String oauthId = claims.getSubject(); + return jwtTokenProvider.create(oauthId); + } + } catch (JwtException e) { + return null; + } + + + return null; + } +} diff --git a/src/main/java/com/kumofactory/cloud/jwt/dto/TokenDto.java b/src/main/java/com/kumofactory/cloud/auth/jwt/dto/TokenDto.java similarity index 100% rename from src/main/java/com/kumofactory/cloud/jwt/dto/TokenDto.java rename to src/main/java/com/kumofactory/cloud/auth/jwt/dto/TokenDto.java diff --git a/src/main/java/com/kumofactory/cloud/jwt/provider/JwtTokenProvider.java b/src/main/java/com/kumofactory/cloud/auth/jwt/provider/JwtTokenProvider.java similarity index 97% rename from src/main/java/com/kumofactory/cloud/jwt/provider/JwtTokenProvider.java rename to src/main/java/com/kumofactory/cloud/auth/jwt/provider/JwtTokenProvider.java index 085c995..5e358f7 100644 --- a/src/main/java/com/kumofactory/cloud/jwt/provider/JwtTokenProvider.java +++ b/src/main/java/com/kumofactory/cloud/auth/jwt/provider/JwtTokenProvider.java @@ -30,7 +30,7 @@ public TokenDto create(String id) { String accessToken = Jwts.builder() .setSubject(id) .setIssuedAt(now) - .setExpiration(new Date(now.getTime() + VALIDITY)) + .setExpiration(new Date(now.getTime() + 3)) .signWith(Keys.hmacShaKeyFor(secret.getBytes())) .compact(); diff --git a/src/main/java/com/kumofactory/cloud/jwt/repository/RefreshTokenRepository.java b/src/main/java/com/kumofactory/cloud/auth/jwt/repository/RefreshTokenRepository.java similarity index 100% rename from src/main/java/com/kumofactory/cloud/jwt/repository/RefreshTokenRepository.java rename to src/main/java/com/kumofactory/cloud/auth/jwt/repository/RefreshTokenRepository.java From a646072223a8193734558414a585ef88776b7156 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 17 Jul 2023 21:35:35 +0900 Subject: [PATCH 03/63] =?UTF-8?q?fix=20:=20access=20token,=20refresh=20tok?= =?UTF-8?q?en=20=EC=9C=A0=ED=9A=A8=20=EC=8B=9C=EA=B0=84=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/jwt/provider/JwtTokenProvider.java | 31 +--- .../cloud/blueprint/BlueprintController.java | 63 +++---- .../auth/AuthorizationFromTokenAspect.java | 70 ++++--- .../cloud/oauth/service/OAuthService.java | 172 +++++++++--------- 4 files changed, 164 insertions(+), 172 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/auth/jwt/provider/JwtTokenProvider.java b/src/main/java/com/kumofactory/cloud/auth/jwt/provider/JwtTokenProvider.java index 5e358f7..68b0611 100644 --- a/src/main/java/com/kumofactory/cloud/auth/jwt/provider/JwtTokenProvider.java +++ b/src/main/java/com/kumofactory/cloud/auth/jwt/provider/JwtTokenProvider.java @@ -1,6 +1,6 @@ -package com.kumofactory.cloud.jwt.provider; +package com.kumofactory.cloud.auth.jwt.provider; -import com.kumofactory.cloud.jwt.dto.TokenDto; +import com.kumofactory.cloud.auth.jwt.dto.TokenDto; import io.jsonwebtoken.*; import io.jsonwebtoken.security.Keys; import lombok.RequiredArgsConstructor; @@ -20,8 +20,10 @@ public class JwtTokenProvider { @Value("${jwt.secret}") private String secret; - @Value("${jwt.token-validity-in-milliseconds}") + @Value("${jwt.ac-token-validity-in-milliseconds}") private long VALIDITY; + @Value("${jwt.re-token-validity-in-milliseconds}") + private long REFRESH_VALIDITY; public TokenDto create(String id) { @@ -30,14 +32,14 @@ public TokenDto create(String id) { String accessToken = Jwts.builder() .setSubject(id) .setIssuedAt(now) - .setExpiration(new Date(now.getTime() + 3)) + .setExpiration(new Date(now.getTime() + VALIDITY)) .signWith(Keys.hmacShaKeyFor(secret.getBytes())) .compact(); String refreshToken = Jwts.builder() .setSubject(id) .setIssuedAt(now) - .setExpiration(new Date(now.getTime() + (VALIDITY * 365))) + .setExpiration(new Date(now.getTime() + (REFRESH_VALIDITY * 365))) .signWith(Keys.hmacShaKeyFor(secret.getBytes())) .compact(); @@ -48,7 +50,7 @@ public TokenDto create(String id) { .build(); } - public boolean validateAccessToken(String token) { + public boolean validateToken(String token) { try { Claims claims = getClaimsFormToken(token); return true; @@ -64,23 +66,6 @@ public boolean validateAccessToken(String token) { } } - public boolean validateRefreshToken(String token) { - try { - Jws claims = Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(secret.getBytes())).build().parseClaimsJws(token); - return !claims.getBody().getExpiration().before(new Date()); - } catch (Exception e) { - return false; - } - } - - - // TODO : Refresh Token API 구현 - public String refreshAccessToken(Claims claims) { - String id = claims.getSubject(); - TokenDto tokenDto = create(id); - return null; - } - public Claims getClaimsFormToken(String token) { return Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(secret.getBytes())).build().parseClaimsJws(token).getBody(); } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index e00534c..5330dce 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -1,6 +1,5 @@ package com.kumofactory.cloud.blueprint; -import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; @@ -9,6 +8,8 @@ import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @@ -18,40 +19,36 @@ @RequestMapping("/blueprint") @Slf4j public class BlueprintController { - private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); - private final AwsBlueprintService awsBlueprintService; + private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); + private final AwsBlueprintService awsBlueprintService; - @GetMapping("/aws/{id}") - @AuthorizationFromToken - public AwsBluePrintDto getAwsBlueprint(@PathVariable("id") Long id, String userId) { - try { - logger.info("aws blue print id: {}", id); - AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); - return awsBlueprint; - } catch (RuntimeException e) { - return null; - } - } + @GetMapping("/aws/{id}") + @AuthorizationFromToken + public AwsBluePrintDto getAwsBlueprint(@PathVariable("id") Long id, String userId) { + logger.info("aws blue print id: {}", id); + AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); + return awsBlueprint; + } - @GetMapping("/aws/list") - @AuthorizationFromToken - public List getAwsBlueprintList(String userId) { - logger.info("userId: {}", userId); - return awsBlueprintService.getMyAwsBlueprints(userId); - } + @GetMapping("/aws/list") + @AuthorizationFromToken + public List getAwsBlueprintList(String userId) { + logger.info("userId: {}", userId); + return awsBlueprintService.getMyAwsBlueprints(userId); + } - @PostMapping("/aws") - @AuthorizationFromToken - public String createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) { - logger.info(userId); - awsBlueprintService.store(awsBluePrintDto, userId); - return "hello-world"; - } + @PostMapping("/aws") + @AuthorizationFromToken + public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) { + logger.info(userId); + awsBlueprintService.store(awsBluePrintDto, userId); + return "hello-world"; + } - @GetMapping("/test") - @AuthorizationFromToken - public String testMiddleware(String userId) { - System.out.printf("userId: %s\n", userId); - return userId; - } + @GetMapping("/test") + @AuthorizationFromToken + public String testMiddleware(String userId) { + System.out.printf("userId: %s\n", userId); + return userId; + } } diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java index dfc48f3..528bfa5 100644 --- a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java +++ b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java @@ -1,22 +1,22 @@ package com.kumofactory.cloud.global.middleware.auth; -import com.kumofactory.cloud.jwt.provider.JwtTokenProvider; +import com.kumofactory.cloud.auth.jwt.provider.JwtTokenProvider; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.JwtException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; import java.util.Objects; @Aspect @@ -24,31 +24,41 @@ @RequiredArgsConstructor @Slf4j public class AuthorizationFromTokenAspect { - private final JwtTokenProvider jwtTokenProvider; - private final Logger logger = LoggerFactory.getLogger(AuthorizationFromTokenAspect.class); + private final JwtTokenProvider jwtTokenProvider; + private final Logger logger = LoggerFactory.getLogger(AuthorizationFromTokenAspect.class); - @Around(value = "@annotation(AuthorizationFromToken)") - public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, AuthorizationFromToken AuthorizationFromToken) throws Throwable { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); - String userId = getUserFromAccessToken(request.getHeader("Authorization")); - if (userId == null) { - throw new RuntimeException("유효하지 않은 토큰입니다."); - } - // 추출된 사용자 정보를 매개변수로 전달 - Object[] args = joinPoint.getArgs(); - args[args.length - 1] = userId; + @Around(value = "@annotation(AuthorizationFromToken)") + public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, AuthorizationFromToken AuthorizationFromToken) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); + String userId = getUserFromAccessToken(request.getHeader("Authorization")); + if (userId == null) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("토큰이 유효하지 않습니다."); + } else if (userId.equals("expired")) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("토큰이 만료되었습니다."); + } else { + // 추출된 사용자 정보를 매개변수로 전달 + Object[] args = joinPoint.getArgs(); + args[args.length - 1] = userId; + return joinPoint.proceed(args); + } + } - return joinPoint.proceed(args); - } - - // user oauth id 추출 - private String getUserFromAccessToken(String token) { - String accessToken = token.split(" ")[1]; - boolean isValidate = jwtTokenProvider.validateAccessToken(accessToken); - if (isValidate) { - return jwtTokenProvider.getClaimsFormToken(accessToken).getSubject(); - } - return null; - } + // user oauth id 추출 + private String getUserFromAccessToken(String token) { + String accessToken = token.split(" ")[1]; + try { + boolean isValidate = jwtTokenProvider.validateToken(accessToken); + if (isValidate) { + return jwtTokenProvider.getClaimsFormToken(accessToken).getSubject(); + } + } catch (ExpiredJwtException exception) { // Access Token 이 만료됐을 때 + return "expired"; + } catch (JwtException e) { // Access Token 이 유효하지 않을 때 + return null; + } catch (NullPointerException e) { // Access Token 이 null 일 때 + return null; + } + return null; + } } diff --git a/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java b/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java index 19dcd74..b28fa5a 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java +++ b/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java @@ -2,8 +2,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.kumofactory.cloud.config.OAuthProvider; -import com.kumofactory.cloud.jwt.dto.TokenDto; -import com.kumofactory.cloud.jwt.provider.JwtTokenProvider; +import com.kumofactory.cloud.auth.jwt.dto.TokenDto; +import com.kumofactory.cloud.auth.jwt.provider.JwtTokenProvider; import com.kumofactory.cloud.member.MemberRepository; import com.kumofactory.cloud.member.domain.Member; import com.kumofactory.cloud.oauth.dto.UserInfoDto; @@ -28,88 +28,88 @@ @Slf4j @RequiredArgsConstructor public class OAuthService { - private final GoogleService googleService; - private final GitHubService githubService; - - private final JwtTokenProvider jwtTokenProvider; - private final MemberRepository memberRepository; - - private TokenDto token; - - public ResponseEntity request(OAuthProvider provider, String code) - throws JsonProcessingException { - - HttpHeaders responseHeaders = new HttpHeaders(); - - switch (provider) { - case GOOGLE: { - token = getAccessTokenFromGoogle(code); - break; - } - case GITHUB: { - token = getAccessTokenFromGitHub(code); - break; - } - default: { - throw new IllegalArgumentException("Unknown type of social login."); - } - } - - responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); - - ResponseCookie refreshTokenCookie = ResponseCookie - .from("refreshToken", token.getRefreshToken()) - .httpOnly(true) - .path("/") - .maxAge(Duration.ofDays(365)) - .build(); - - responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); - - Map map = new HashMap<>(); - map.put("accessToken", token.getAccessToken()); - - return ResponseEntity.ok() - .headers(responseHeaders) - .body(new ObjectMapper().writeValueAsString(map)); - } - - // TODO : 중복된 코드 간소화 (getAccessTokenFromXXX) - private TokenDto getAccessTokenFromGoogle(String code) - throws JsonProcessingException { - - GoogleToken accessTokenFromGoogle = googleService.requestAccessToken(code); - if (accessTokenFromGoogle != null) { - - UserInfoDto userInfo = googleService.requestUserInfo(accessTokenFromGoogle.accessToken()); - saveMember(userInfo); - - return jwtTokenProvider.create(userInfo.id()); - } - return null; - } - - private TokenDto getAccessTokenFromGitHub(String code) - throws JsonProcessingException { - - GitHubToken accessTokenFromGithub = githubService.requestAccessToken(code); - if (accessTokenFromGithub != null) { - - UserInfoDto userInfo = githubService.requestUserInfo(accessTokenFromGithub.accessToken()); - saveMember(userInfo); - - - return jwtTokenProvider.create(userInfo.id()); - } - return null; - } - - // 처음 가입한 member 일때만 저장 - private void saveMember(UserInfoDto userInfo) { - Member member = memberRepository.findMemberByOauthId(userInfo.id()); - if (member == null) { - member = Member.createMember(userInfo); - memberRepository.save(member); - } - } + private final GoogleService googleService; + private final GitHubService githubService; + + private final JwtTokenProvider jwtTokenProvider; + private final MemberRepository memberRepository; + + private TokenDto token; + + public ResponseEntity request(OAuthProvider provider, String code) + throws JsonProcessingException { + + HttpHeaders responseHeaders = new HttpHeaders(); + + switch (provider) { + case GOOGLE: { + token = getAccessTokenFromGoogle(code); + break; + } + case GITHUB: { + token = getAccessTokenFromGitHub(code); + break; + } + default: { + throw new IllegalArgumentException("Unknown type of social login."); + } + } + + responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); + + ResponseCookie refreshTokenCookie = ResponseCookie + .from("refreshToken", token.getRefreshToken()) + .httpOnly(true) + .path("/") + .maxAge(Duration.ofDays(365)) + .build(); + + responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); + + Map map = new HashMap<>(); + map.put("accessToken", token.getAccessToken()); + + return ResponseEntity.ok() + .headers(responseHeaders) + .body(new ObjectMapper().writeValueAsString(map)); + } + + // TODO : 중복된 코드 간소화 (getAccessTokenFromXXX) + private TokenDto getAccessTokenFromGoogle(String code) + throws JsonProcessingException { + + GoogleToken accessTokenFromGoogle = googleService.requestAccessToken(code); + if (accessTokenFromGoogle != null) { + + UserInfoDto userInfo = googleService.requestUserInfo(accessTokenFromGoogle.accessToken()); + saveMember(userInfo); + + return jwtTokenProvider.create(userInfo.id()); + } + return null; + } + + private TokenDto getAccessTokenFromGitHub(String code) + throws JsonProcessingException { + + GitHubToken accessTokenFromGithub = githubService.requestAccessToken(code); + if (accessTokenFromGithub != null) { + + UserInfoDto userInfo = githubService.requestUserInfo(accessTokenFromGithub.accessToken()); + saveMember(userInfo); + + + return jwtTokenProvider.create(userInfo.id()); + } + return null; + } + + // 처음 가입한 member 일때만 저장 + private void saveMember(UserInfoDto userInfo) { + Member member = memberRepository.findMemberByOauthId(userInfo.id()); + if (member == null) { + member = Member.createMember(userInfo); + memberRepository.save(member); + } + } } From 18b11d675bf034d053d502f0be4c283fe30e5f43 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 17 Jul 2023 21:36:05 +0900 Subject: [PATCH 04/63] refactor : jwt folder from cloud/ to auth/ --- src/main/java/com/kumofactory/cloud/auth/jwt/dto/TokenDto.java | 2 +- .../cloud/auth/jwt/repository/RefreshTokenRepository.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/auth/jwt/dto/TokenDto.java b/src/main/java/com/kumofactory/cloud/auth/jwt/dto/TokenDto.java index c4ff4c2..01453e2 100644 --- a/src/main/java/com/kumofactory/cloud/auth/jwt/dto/TokenDto.java +++ b/src/main/java/com/kumofactory/cloud/auth/jwt/dto/TokenDto.java @@ -1,4 +1,4 @@ -package com.kumofactory.cloud.jwt.dto; +package com.kumofactory.cloud.auth.jwt.dto; import lombok.*; diff --git a/src/main/java/com/kumofactory/cloud/auth/jwt/repository/RefreshTokenRepository.java b/src/main/java/com/kumofactory/cloud/auth/jwt/repository/RefreshTokenRepository.java index db4ec08..48130c2 100644 --- a/src/main/java/com/kumofactory/cloud/auth/jwt/repository/RefreshTokenRepository.java +++ b/src/main/java/com/kumofactory/cloud/auth/jwt/repository/RefreshTokenRepository.java @@ -1,4 +1,4 @@ -package com.kumofactory.cloud.jwt.repository; +package com.kumofactory.cloud.auth.jwt.repository; import lombok.AllArgsConstructor; import lombok.Builder; From 1ec46772b81a209c93aaaffe8f0324fe5e178620 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 17 Jul 2023 21:50:37 +0900 Subject: [PATCH 05/63] =?UTF-8?q?feat=20:=20refresh=20token=20=EB=A7=8C?= =?UTF-8?q?=EB=A3=8C=EC=8B=9C=20cookie=20=EC=A0=9C=EA=B1=B0=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cloud/auth/AuthController.java | 62 ++++++++++++------- .../cloud/auth/AuthServiceImpl.java | 3 +- .../cloud/blueprint/BlueprintController.java | 4 +- .../auth/AuthorizationFromTokenAspect.java | 15 +++-- 4 files changed, 49 insertions(+), 35 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthController.java b/src/main/java/com/kumofactory/cloud/auth/AuthController.java index dbb0014..e155bec 100644 --- a/src/main/java/com/kumofactory/cloud/auth/AuthController.java +++ b/src/main/java/com/kumofactory/cloud/auth/AuthController.java @@ -6,6 +6,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseCookie; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -14,6 +15,7 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @@ -25,31 +27,45 @@ public class AuthController { private final AuthService authService; @GetMapping("/refresh") - public ResponseEntity refresh(HttpServletRequest request) throws JsonProcessingException { - Cookie[] cookies = request.getCookies(); - String refreshToken = null; - for (Cookie cookie : cookies) { - if (cookie.getName().equals("refreshToken")) { - log.info("refreshToken: {}", cookie.getValue()); - refreshToken = cookie.getValue(); - break; + public ResponseEntity refresh(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException { + try { + Cookie[] cookies = request.getCookies(); + String refreshToken = null; + for (Cookie cookie : cookies) { + if (cookie.getName().equals("refreshToken")) { + log.info("refreshToken: {}", cookie.getValue()); + refreshToken = cookie.getValue(); + break; + } } - } - TokenDto token = authService.refresh(refreshToken); - HttpHeaders responseHeaders = new HttpHeaders(); - ResponseCookie refreshTokenCookie = ResponseCookie.from("refreshToken", token.getRefreshToken()) - .httpOnly(true) - .path("/") - .maxAge(60 * 60 * 24 * 30) - .build(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); - responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); - Map map = new HashMap<>(); - map.put("accessToken", token.getAccessToken()); + TokenDto token = authService.refresh(refreshToken); + HttpHeaders responseHeaders = new HttpHeaders(); + ResponseCookie refreshTokenCookie = ResponseCookie.from("refreshToken", token.getRefreshToken()) + .httpOnly(true) + .path("/") + .maxAge(60 * 60 * 24 * 30) + .build(); + responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); + responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); + Map map = new HashMap<>(); + map.put("accessToken", token.getAccessToken()); + log.info("accessToken: {}", token.getAccessToken()); + return ResponseEntity.ok() + .headers(responseHeaders) + .body(new ObjectMapper().writeValueAsString(map)); + } catch (RuntimeException e) { + log.info("Refresh Token is expired"); + for (Cookie cookie : request.getCookies()) { + if (cookie.getName().equals("refreshToken")) { + cookie.setMaxAge(0); + cookie.setPath("/"); + response.addCookie(cookie); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Refresh Token is expired"); + } + } + } - return ResponseEntity.ok() - .headers(responseHeaders) - .body(new ObjectMapper().writeValueAsString(map)); + return null; } } diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java b/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java index 9f401b1..acb4dfe 100644 --- a/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java @@ -29,10 +29,9 @@ public TokenDto refresh(String refreshToken) { return jwtTokenProvider.create(oauthId); } } catch (JwtException e) { - return null; + throw new RuntimeException("Token is not valid"); } - return null; } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index 5330dce..3bdeff0 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -24,7 +24,7 @@ public class BlueprintController { @GetMapping("/aws/{id}") @AuthorizationFromToken - public AwsBluePrintDto getAwsBlueprint(@PathVariable("id") Long id, String userId) { + public Object getAwsBlueprint(@PathVariable("id") Long id, String userId) { logger.info("aws blue print id: {}", id); AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); return awsBlueprint; @@ -32,7 +32,7 @@ public AwsBluePrintDto getAwsBlueprint(@PathVariable("id") Long id, String userI @GetMapping("/aws/list") @AuthorizationFromToken - public List getAwsBlueprintList(String userId) { + public Object getAwsBlueprintList(String userId) { logger.info("userId: {}", userId); return awsBlueprintService.getMyAwsBlueprints(userId); } diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java index 528bfa5..c53c3cc 100644 --- a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java +++ b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java @@ -32,16 +32,15 @@ public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, Authori ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); String userId = getUserFromAccessToken(request.getHeader("Authorization")); + log.info("userId: {}", userId); if (userId == null) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("토큰이 유효하지 않습니다."); - } else if (userId.equals("expired")) { + log.info("토큰이 만료되었습니다."); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("토큰이 만료되었습니다."); - } else { - // 추출된 사용자 정보를 매개변수로 전달 - Object[] args = joinPoint.getArgs(); - args[args.length - 1] = userId; - return joinPoint.proceed(args); } + // 추출된 사용자 정보를 매개변수로 전달 + Object[] args = joinPoint.getArgs(); + args[args.length - 1] = userId; + return joinPoint.proceed(args); } // user oauth id 추출 @@ -53,7 +52,7 @@ private String getUserFromAccessToken(String token) { return jwtTokenProvider.getClaimsFormToken(accessToken).getSubject(); } } catch (ExpiredJwtException exception) { // Access Token 이 만료됐을 때 - return "expired"; + return null; } catch (JwtException e) { // Access Token 이 유효하지 않을 때 return null; } catch (NullPointerException e) { // Access Token 이 null 일 때 From ff82225d65c645303d11595a22f3992b389cba63 Mon Sep 17 00:00:00 2001 From: wook Date: Thu, 20 Jul 2023 14:07:13 +0900 Subject: [PATCH 06/63] feat : add feature logout and withdraw --- .../cloud/auth/AuthController.java | 31 ++++++++++++++++--- .../kumofactory/cloud/auth/AuthService.java | 3 ++ .../cloud/auth/AuthServiceImpl.java | 30 +++++++++++++++++- .../kumofactory/cloud/auth/dto/ResultDto.java | 14 +++++++++ .../auth/AuthorizationFromTokenAspect.java | 2 +- 5 files changed, 74 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/kumofactory/cloud/auth/dto/ResultDto.java diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthController.java b/src/main/java/com/kumofactory/cloud/auth/AuthController.java index e155bec..be120df 100644 --- a/src/main/java/com/kumofactory/cloud/auth/AuthController.java +++ b/src/main/java/com/kumofactory/cloud/auth/AuthController.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kumofactory.cloud.auth.jwt.dto.TokenDto; +import com.kumofactory.cloud.global.middleware.auth.AuthorizationFromToken; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; @@ -10,8 +11,10 @@ import org.springframework.http.ResponseCookie; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; @@ -19,7 +22,7 @@ import java.util.HashMap; import java.util.Map; -@Controller +@RestController @RequestMapping("/auth") @Slf4j @RequiredArgsConstructor @@ -27,13 +30,13 @@ public class AuthController { private final AuthService authService; @GetMapping("/refresh") - public ResponseEntity refresh(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException { + public Object refresh(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException { try { Cookie[] cookies = request.getCookies(); String refreshToken = null; for (Cookie cookie : cookies) { if (cookie.getName().equals("refreshToken")) { - log.info("refreshToken: {}", cookie.getValue()); + log.info("take refreshToken: {}", cookie.getValue()); refreshToken = cookie.getValue(); break; } @@ -49,11 +52,12 @@ public ResponseEntity refresh(HttpServletRequest request, HttpServletRes responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); Map map = new HashMap<>(); map.put("accessToken", token.getAccessToken()); - log.info("accessToken: {}", token.getAccessToken()); + log.info("create accessToken: {}", token.getAccessToken()); return ResponseEntity.ok() .headers(responseHeaders) .body(new ObjectMapper().writeValueAsString(map)); + } catch (RuntimeException e) { log.info("Refresh Token is expired"); for (Cookie cookie : request.getCookies()) { @@ -68,4 +72,23 @@ public ResponseEntity refresh(HttpServletRequest request, HttpServletRes return null; } + + @GetMapping("/logout") + public Object logout(HttpServletRequest request, HttpServletResponse response) { + for (Cookie cookie : request.getCookies()) { + if (cookie.getName().equals("refreshToken")) { + cookie.setMaxAge(0); + cookie.setPath("/"); + response.addCookie(cookie); + return ResponseEntity.ok().body("logout"); + } + } + return ResponseEntity.status(HttpStatus.OK).body("logout"); + } + + @DeleteMapping("/withdrawal") + @AuthorizationFromToken + public Object withdrawal(String userId) { + return authService.withdraw(userId); + } } diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthService.java b/src/main/java/com/kumofactory/cloud/auth/AuthService.java index a134a4f..7528c8d 100644 --- a/src/main/java/com/kumofactory/cloud/auth/AuthService.java +++ b/src/main/java/com/kumofactory/cloud/auth/AuthService.java @@ -1,7 +1,10 @@ package com.kumofactory.cloud.auth; +import com.kumofactory.cloud.auth.dto.ResultDto; import com.kumofactory.cloud.auth.jwt.dto.TokenDto; public interface AuthService { TokenDto refresh(String refreshToken); + + ResultDto withdraw(String accessToken); } diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java b/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java index acb4dfe..2b0df94 100644 --- a/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/auth/AuthServiceImpl.java @@ -1,9 +1,11 @@ package com.kumofactory.cloud.auth; +import com.kumofactory.cloud.auth.dto.ResultDto; import com.kumofactory.cloud.auth.jwt.dto.TokenDto; import com.kumofactory.cloud.auth.jwt.provider.JwtTokenProvider; +import com.kumofactory.cloud.member.MemberRepository; +import com.kumofactory.cloud.member.domain.Member; import io.jsonwebtoken.Claims; -import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.JwtException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -14,6 +16,7 @@ @Slf4j public class AuthServiceImpl implements AuthService { private final JwtTokenProvider jwtTokenProvider; + private final MemberRepository memberRepository; @Override public TokenDto refresh(String refreshToken) { @@ -34,4 +37,29 @@ public TokenDto refresh(String refreshToken) { return null; } + + @Override + public ResultDto withdraw(String accessToken) { + if (accessToken == null) { + throw new RuntimeException("Token is null"); + } + + try { + Claims claims = jwtTokenProvider.getClaimsFormToken(accessToken); + String oauthId = claims.getSubject(); + Member member = memberRepository.findMemberByOauthId(oauthId); + + if (member != null) { + memberRepository.delete(member); + return ResultDto.builder() + .result(true) + .build(); + } + + } catch (JwtException e) { + return ResultDto.builder().result(false).message("Not Found").build(); + } + + return null; + } } diff --git a/src/main/java/com/kumofactory/cloud/auth/dto/ResultDto.java b/src/main/java/com/kumofactory/cloud/auth/dto/ResultDto.java new file mode 100644 index 0000000..fdaa5ec --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/auth/dto/ResultDto.java @@ -0,0 +1,14 @@ +package com.kumofactory.cloud.auth.dto; + + +import lombok.*; + +@Getter +@Setter +@NoArgsConstructor +@Builder +@AllArgsConstructor +public class ResultDto { + private Boolean result; + private String message; +} diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java index c53c3cc..bd0b0ce 100644 --- a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java +++ b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java @@ -32,7 +32,6 @@ public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, Authori ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); String userId = getUserFromAccessToken(request.getHeader("Authorization")); - log.info("userId: {}", userId); if (userId == null) { log.info("토큰이 만료되었습니다."); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("토큰이 만료되었습니다."); @@ -46,6 +45,7 @@ public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, Authori // user oauth id 추출 private String getUserFromAccessToken(String token) { String accessToken = token.split(" ")[1]; + logger.info("get From Client accessToken: {}", accessToken); try { boolean isValidate = jwtTokenProvider.validateToken(accessToken); if (isValidate) { From 4283cebb5afb15d3414648cff072406219e14986 Mon Sep 17 00:00:00 2001 From: wook Date: Thu, 20 Jul 2023 19:37:06 +0900 Subject: [PATCH 07/63] fix : import dependency --- .../com/kumofactory/cloud/blueprint/BlueprintController.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index 40b3f54..5053821 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -2,12 +2,11 @@ import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; +import com.kumofactory.cloud.global.middleware.auth.AuthorizationFromToken; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController From 1bd5c25c043f1bfb348b116627cf44162f94527a Mon Sep 17 00:00:00 2001 From: wook Date: Thu, 20 Jul 2023 19:40:17 +0900 Subject: [PATCH 08/63] =?UTF-8?q?fix=20:=20=EC=9C=BC=EC=95=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../global/middleware/auth/AuthorizationFromTokenAspect.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java index 448e974..11c99fe 100644 --- a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java +++ b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java @@ -12,6 +12,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; +import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Objects; @@ -29,7 +30,6 @@ public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, Authori HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); String userId = getUserFromAccessToken(request.getHeader("Authorization")); if (userId == null) { - log.info("토큰이 만료되었습니다."); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("토큰이 만료되었습니다."); } // 추출된 사용자 정보를 매개변수로 전달 From ebbcef4de2a724e616032e109a3a7393ab46e6b6 Mon Sep 17 00:00:00 2001 From: wook Date: Thu, 20 Jul 2023 19:42:04 +0900 Subject: [PATCH 09/63] fix : import RequestContextHolder in AuthorizationFromTokenAspect --- .../global/middleware/auth/AuthorizationFromTokenAspect.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java index 11c99fe..a73d4d1 100644 --- a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java +++ b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java @@ -12,6 +12,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; From 6d22ab03a2471ba7d1226dba9c808d61b5b8a652 Mon Sep 17 00:00:00 2001 From: wook Date: Thu, 20 Jul 2023 21:27:46 +0900 Subject: [PATCH 10/63] update : -name to -t --- .github/workflows/Build-Deploy-dev.yaml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/Build-Deploy-dev.yaml b/.github/workflows/Build-Deploy-dev.yaml index 531a55b..7db3e05 100644 --- a/.github/workflows/Build-Deploy-dev.yaml +++ b/.github/workflows/Build-Deploy-dev.yaml @@ -23,7 +23,7 @@ jobs: with: java-version: 17 distribution: 'oracle' - + - name: Setup Gradle 7.6 uses: gradle/gradle-build-action@v2 with: @@ -46,14 +46,14 @@ jobs: - name: Build Project run: gradle build - + ############################################ ### Start Pushing container image on ECR ### ############################################ - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: - aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: ${{ env.AWS_REGION }} @@ -76,7 +76,7 @@ jobs: docker push $ECR_REGISTRY/$ECR_REPOSITORY:dev-$DATE docker push $ECR_REGISTRY/$ECR_REPOSITORY:dev-latest - + ######################################################### # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # ######################################################### @@ -92,7 +92,7 @@ jobs: docker push $ECR_REGISTRY/$ECR_REPOSITORY:main-$DATE docker push $ECR_REGISTRY/$ECR_REPOSITORY:main-latest - + deploy: needs: build @@ -115,7 +115,7 @@ jobs: docker login --username AWS --password $password ${{ env.ECR_REGISTRY }} docker pull ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:dev-latest docker stop ${{ env.ECR_REPOSITORY }}-dev - docker run --rm -d -p 8081:8080 --name kumo-server-dev ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:dev-latest + docker run --rm -d -p 8081:8080 --t kumo-server-dev ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:dev-latest ######################################################### # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # From d14b2c542995e878d33da9312fc715f88d300fc9 Mon Sep 17 00:00:00 2001 From: wook Date: Thu, 20 Jul 2023 21:57:36 +0900 Subject: [PATCH 11/63] delete : delete docker stop --- .github/workflows/Build-Deploy-dev.yaml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/Build-Deploy-dev.yaml b/.github/workflows/Build-Deploy-dev.yaml index 7db3e05..0b1206f 100644 --- a/.github/workflows/Build-Deploy-dev.yaml +++ b/.github/workflows/Build-Deploy-dev.yaml @@ -114,8 +114,7 @@ jobs: password=$(aws ecr get-login-password --region ${{ env.AWS_REGION }}) docker login --username AWS --password $password ${{ env.ECR_REGISTRY }} docker pull ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:dev-latest - docker stop ${{ env.ECR_REPOSITORY }}-dev - docker run --rm -d -p 8081:8080 --t kumo-server-dev ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:dev-latest + docker run --rm -d -p 8081:8080 --name kumo-server-dev ${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}:dev-latest ######################################################### # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # MAIN # From f3a774c664df337982073789a6f643841f93da59 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Mon, 31 Jul 2023 18:38:29 +0900 Subject: [PATCH 12/63] feat: api for listing repository and organization #16 --- .../cloud/appDeploy/AppDeployController.java | 41 ++++ .../cloud/appDeploy/dto/GitHubRepoDto.java | 27 +++ .../cloud/appDeploy/dto/UserRepoDto.java | 25 +++ .../appDeploy/service/UserRepoService.java | 203 ++++++++++++++++++ 4 files changed, 296 insertions(+) create mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java create mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/dto/GitHubRepoDto.java create mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/dto/UserRepoDto.java create mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java b/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java new file mode 100644 index 0000000..ef6d046 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java @@ -0,0 +1,41 @@ +package com.kumofactory.cloud.appDeploy; + +import com.kumofactory.cloud.appDeploy.dto.BuildRequestDto; +import com.kumofactory.cloud.appDeploy.dto.GitHubRepoDto; +import com.kumofactory.cloud.appDeploy.service.UserRepoService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/build") +@RequiredArgsConstructor +public class AppDeployController { + + private final UserRepoService userRepoService = new UserRepoService(); +// @GetMapping("/list") +// public UserRepoDto list() { +// return appDeployService.RequestUserRepoInfo(); +// } + + @GetMapping("/list/{org}/repo") + public List listOrgRepo(@PathVariable String org) { + return userRepoService.RequestOrgRepoInfo(org); + } + + @GetMapping("/list/{user}") + public GitHubRepoDto.UserDto listUserRepoAndOrgs(@PathVariable String user) { + return userRepoService.RequestUserRepoInfoAndOrgList(user); + } + + @GetMapping("/list/{user}/{repo}/branch") + public String listRepoBranches(@PathVariable String user, @PathVariable String repo) { + return "listRepoBranches"; + } + + @PostMapping("/deploy") + public BuildRequestDto deployRequest(@RequestBody BuildRequestDto request) { + return request; + } +} \ No newline at end of file diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/dto/GitHubRepoDto.java b/src/main/java/com/kumofactory/cloud/appDeploy/dto/GitHubRepoDto.java new file mode 100644 index 0000000..2a3ac90 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/appDeploy/dto/GitHubRepoDto.java @@ -0,0 +1,27 @@ +package com.kumofactory.cloud.appDeploy.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class GitHubRepoDto { + public record RepoInfoDto( + @JsonProperty("name") String name, + @JsonProperty("full_name") String fullName, + @JsonProperty("private") Boolean isPrivate, + @JsonProperty("fork") Boolean isFork + ) { } + + public record OrganizationDto( + @JsonProperty("organization_name") String organizationName, + @JsonProperty("organization_repo_count") Integer organizationRepoCount, + @JsonProperty("organization_repo") List organizationRepo + ) { } + + public record UserDto( + @JsonProperty("personal_repo_count") Integer personalRepoCount, + @JsonProperty("personal_repo") List personalRepo, + @JsonProperty("organization_count") Integer organizationCount, + @JsonProperty("organization") List organizationList + ) { } +} diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/dto/UserRepoDto.java b/src/main/java/com/kumofactory/cloud/appDeploy/dto/UserRepoDto.java new file mode 100644 index 0000000..f357ca7 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/appDeploy/dto/UserRepoDto.java @@ -0,0 +1,25 @@ +package com.kumofactory.cloud.appDeploy.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + + +public record UserRepoDto( + @JsonProperty("personal_repo_count") Integer personalRepoCount, + @JsonProperty("personal_repo") List personalRepo, + @JsonProperty("organization_count") Integer organizationCount, + @JsonProperty("organization") List organization +) { + public record RepoInfoDto( + @JsonProperty("name") String name, + @JsonProperty("full_name") String fullName, + @JsonProperty("private") Boolean isPrivate, + @JsonProperty("fork") Boolean isFork + ) { } + public record OrganizationDto( + @JsonProperty("organization_name") String organizationName, + @JsonProperty("organization_repo_count") Integer organizationRepoCount, + @JsonProperty("organization_repo") List organizationRepo + ) { } +} \ No newline at end of file diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java new file mode 100644 index 0000000..6925bbd --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java @@ -0,0 +1,203 @@ +package com.kumofactory.cloud.appDeploy.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.kumofactory.cloud.appDeploy.dto.GitHubRepoDto; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; + + +import java.util.ArrayList; +import java.util.List; + +@Service +@Slf4j +public class UserRepoService { + + private final Logger logger = LoggerFactory.getLogger(UserRepoService.class); + private String token; + +// public UserRepoDto RequestUserRepoInfo() { +// List repoInfoList = listRepos(); +// List orgAndRepoList = listOrgAndRepos(); +// +// return new UserRepoDto( +// repoInfoList.size(), repoInfoList, +// orgAndRepoList.size(), orgAndRepoList +// ); +// } + + public List RequestOrgRepoInfo(String org) { + String uri = "https://api.github.com/search/repositories?q=org:" + org; + ResponseEntity response = RequestGitHubAPIs(uri); + + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + + List repoInfoList = new ArrayList<>(); + + for (JsonNode node : responseBody.get("items")) { + String name = node.get("name").asText(); + String fullName = node.get("full_name").asText(); + Boolean isPrivate = node.get("private").asBoolean(); + Boolean isFork = node.get("fork").asBoolean(); + + GitHubRepoDto.RepoInfoDto repoInfo = new GitHubRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); + repoInfoList.add(repoInfo); + } + logger.info("response : {}", responseBody); + return repoInfoList; + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return null; + } + + public GitHubRepoDto.UserDto RequestUserRepoInfoAndOrgList(String user) { + List repoInfoList = listUserRepos(user); + List orgList = new ArrayList<>(); + if( StringUtils.hasText(token) ) { + orgList = listOrganization(); + } + + return new GitHubRepoDto.UserDto(repoInfoList.size(), repoInfoList, orgList.size(), orgList); + } + + public List listUserRepos(String user) { + String uri = "https://api.github.com/search/repositories?q=user:" + user; + ResponseEntity response = RequestGitHubAPIs(uri); + + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + + List repoInfoList = new ArrayList<>(); + + for (JsonNode node : responseBody.get("items")) { + String name = node.get("name").asText(); + String fullName = node.get("full_name").asText(); + Boolean isPrivate = node.get("private").asBoolean(); + Boolean isFork = node.get("fork").asBoolean(); + + GitHubRepoDto.RepoInfoDto repoInfo = new GitHubRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); + repoInfoList.add(repoInfo); + } + logger.info("response : {}", responseBody); + return repoInfoList; + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return null; + } + +// public List listRepos() { +// String uri = "https://api.github.com/search/repositories?q=user:" + "coding-convention"; +// ResponseEntity response = RequestGitHubAPIs(uri); +// +// if (response.getStatusCode() == HttpStatus.OK) { +// JsonNode responseBody = response.getBody(); +// +// List repoInfoList = new ArrayList<>(); +// +// for (JsonNode node : responseBody.get("items")) { +// String name = node.get("name").asText(); +// String fullName = node.get("full_name").asText(); +// Boolean isPrivate = node.get("private").asBoolean(); +// Boolean isFork = node.get("fork").asBoolean(); +// +// UserRepoDto.RepoInfoDto repoInfo = new UserRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); +// repoInfoList.add(repoInfo); +// } +// logger.info("response : {}", responseBody); +// return repoInfoList; +// } +// logger.error("response : {}", response.getBody()); +// logger.error("response : {}", response.getStatusCode()); +// return null; +// } + +// public List listRepos(String org) { +// String uri = "https://api.github.com/search/repositories?q=org:" + org; +// ResponseEntity response = RequestGitHubAPIs(uri); +// +// if (response.getStatusCode() == HttpStatus.OK) { +// JsonNode responseBody = response.getBody(); +// +// List repoInfoList = new ArrayList<>(); +// +// for (JsonNode node : responseBody.get("items")) { +// String name = node.get("name").asText(); +// String fullName = node.get("full_name").asText(); +// Boolean isPrivate = node.get("private").asBoolean(); +// Boolean isFork = node.get("fork").asBoolean(); +// +// UserRepoDto.RepoInfoDto repoInfo = new UserRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); +// repoInfoList.add(repoInfo); +// } +// logger.info("response : {}", responseBody); +// return repoInfoList; +// } +// logger.error("response : {}", response.getBody()); +// logger.error("response : {}", response.getStatusCode()); +// return null; +// } + +// public List listOrgAndRepos() { +// List orgList = listOrganization(); +// List orgRepoList = new ArrayList<>(); +// +// for (String orgName : orgList) { +// List orgRepo = listRepos(orgName); +// Integer repoCount = orgRepo.size(); +// +// UserRepoDto.OrganizationDto orgRepoInfo = new UserRepoDto.OrganizationDto( +// orgName, repoCount, orgRepo +// ); +// +// orgRepoList.add(orgRepoInfo); +// } +// +// return orgRepoList; +// } + + public List listOrganization() { + String uri = "https://api.github.com/user/orgs"; + ResponseEntity response = RequestGitHubAPIs(uri); + + List organizationList = new ArrayList<>(); + + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + logger.info("response : {}", responseBody); + + if (responseBody.isArray()) { + for (JsonNode node : responseBody) { + if (node.has("login")) { + organizationList.add(node.get("login").asText()); + } + } + } + return organizationList; + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return organizationList; + } + + private ResponseEntity RequestGitHubAPIs(String uri) { + HttpHeaders headers = new HttpHeaders(); + + headers.set("Accept", "application/json"); + if( StringUtils.hasText(token) ) { + headers.setBearerAuth(token); + } + + HttpEntity httpEntity = new HttpEntity<>(headers); + + return new RestTemplate().exchange(uri, HttpMethod.GET, httpEntity, JsonNode.class); + } + +} \ No newline at end of file From e0b415cdfe721b1e129dcbaf2af730b6430833d4 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Mon, 31 Jul 2023 23:14:00 +0900 Subject: [PATCH 13/63] refactor: discard some feature #16 --- .../appDeploy/service/UserRepoService.java | 84 ------------------- 1 file changed, 84 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java index 6925bbd..f07ca50 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java @@ -21,16 +21,6 @@ public class UserRepoService { private final Logger logger = LoggerFactory.getLogger(UserRepoService.class); private String token; -// public UserRepoDto RequestUserRepoInfo() { -// List repoInfoList = listRepos(); -// List orgAndRepoList = listOrgAndRepos(); -// -// return new UserRepoDto( -// repoInfoList.size(), repoInfoList, -// orgAndRepoList.size(), orgAndRepoList -// ); -// } - public List RequestOrgRepoInfo(String org) { String uri = "https://api.github.com/search/repositories?q=org:" + org; ResponseEntity response = RequestGitHubAPIs(uri); @@ -93,76 +83,6 @@ public List listUserRepos(String user) { return null; } -// public List listRepos() { -// String uri = "https://api.github.com/search/repositories?q=user:" + "coding-convention"; -// ResponseEntity response = RequestGitHubAPIs(uri); -// -// if (response.getStatusCode() == HttpStatus.OK) { -// JsonNode responseBody = response.getBody(); -// -// List repoInfoList = new ArrayList<>(); -// -// for (JsonNode node : responseBody.get("items")) { -// String name = node.get("name").asText(); -// String fullName = node.get("full_name").asText(); -// Boolean isPrivate = node.get("private").asBoolean(); -// Boolean isFork = node.get("fork").asBoolean(); -// -// UserRepoDto.RepoInfoDto repoInfo = new UserRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); -// repoInfoList.add(repoInfo); -// } -// logger.info("response : {}", responseBody); -// return repoInfoList; -// } -// logger.error("response : {}", response.getBody()); -// logger.error("response : {}", response.getStatusCode()); -// return null; -// } - -// public List listRepos(String org) { -// String uri = "https://api.github.com/search/repositories?q=org:" + org; -// ResponseEntity response = RequestGitHubAPIs(uri); -// -// if (response.getStatusCode() == HttpStatus.OK) { -// JsonNode responseBody = response.getBody(); -// -// List repoInfoList = new ArrayList<>(); -// -// for (JsonNode node : responseBody.get("items")) { -// String name = node.get("name").asText(); -// String fullName = node.get("full_name").asText(); -// Boolean isPrivate = node.get("private").asBoolean(); -// Boolean isFork = node.get("fork").asBoolean(); -// -// UserRepoDto.RepoInfoDto repoInfo = new UserRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); -// repoInfoList.add(repoInfo); -// } -// logger.info("response : {}", responseBody); -// return repoInfoList; -// } -// logger.error("response : {}", response.getBody()); -// logger.error("response : {}", response.getStatusCode()); -// return null; -// } - -// public List listOrgAndRepos() { -// List orgList = listOrganization(); -// List orgRepoList = new ArrayList<>(); -// -// for (String orgName : orgList) { -// List orgRepo = listRepos(orgName); -// Integer repoCount = orgRepo.size(); -// -// UserRepoDto.OrganizationDto orgRepoInfo = new UserRepoDto.OrganizationDto( -// orgName, repoCount, orgRepo -// ); -// -// orgRepoList.add(orgRepoInfo); -// } -// -// return orgRepoList; -// } - public List listOrganization() { String uri = "https://api.github.com/user/orgs"; ResponseEntity response = RequestGitHubAPIs(uri); @@ -189,15 +109,11 @@ public List listOrganization() { private ResponseEntity RequestGitHubAPIs(String uri) { HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); if( StringUtils.hasText(token) ) { headers.setBearerAuth(token); } - HttpEntity httpEntity = new HttpEntity<>(headers); - return new RestTemplate().exchange(uri, HttpMethod.GET, httpEntity, JsonNode.class); } - } \ No newline at end of file From c28f9adc879a6923e573f19e13cb525d530528c1 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Mon, 31 Jul 2023 23:17:19 +0900 Subject: [PATCH 14/63] feat: verify Dockerfile existence #16 --- .../service/BuildRequestService.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java new file mode 100644 index 0000000..e842581 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java @@ -0,0 +1,41 @@ +package com.kumofactory.cloud.appDeploy.service; + +import com.fasterxml.jackson.databind.JsonNode; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; + +@Service +@Slf4j +public class BuildRequestService { + private final Logger logger = LoggerFactory.getLogger(BuildRequestService.class); + private String token; + private String baseUri = "https://api.github.com"; + + private Boolean isDockerfileExist(String userName ,String repoName) { + String url = baseUri + "/repos/" + userName + "/" + repoName + "/contents/Dockerfile"; + try { + ResponseEntity response = RequestGitHubAPIs(url); + return true; + } catch (Exception e) { + return false; + } + } + + private ResponseEntity RequestGitHubAPIs(String uri) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + if( StringUtils.hasText(token) ) { + headers.setBearerAuth(token); + } + HttpEntity httpEntity = new HttpEntity<>(headers); + return new RestTemplate().exchange(uri, HttpMethod.GET, httpEntity, JsonNode.class); + } +} From cfd83c6e10b45afb8349027e1b3a9225be41a91f Mon Sep 17 00:00:00 2001 From: coding-convention Date: Tue, 1 Aug 2023 01:44:46 +0900 Subject: [PATCH 15/63] feat: apis for build pages #16 --- .../cloud/appDeploy/AppDeployController.java | 28 ++++++++++++------ .../cloud/appDeploy/dto/BuildRequestDto.java | 29 +++++++++++++++++++ .../service/BuildRequestService.java | 25 +++++++++++++++- .../appDeploy/service/UserRepoService.java | 24 +++++++++++++++ 4 files changed, 96 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java b/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java index ef6d046..8697568 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java @@ -2,8 +2,11 @@ import com.kumofactory.cloud.appDeploy.dto.BuildRequestDto; import com.kumofactory.cloud.appDeploy.dto.GitHubRepoDto; +import com.kumofactory.cloud.appDeploy.service.BuildRequestService; import com.kumofactory.cloud.appDeploy.service.UserRepoService; import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @@ -12,12 +15,10 @@ @RequestMapping("/build") @RequiredArgsConstructor public class AppDeployController { + Logger logger = org.slf4j.LoggerFactory.getLogger(AppDeployController.class); private final UserRepoService userRepoService = new UserRepoService(); -// @GetMapping("/list") -// public UserRepoDto list() { -// return appDeployService.RequestUserRepoInfo(); -// } + private final BuildRequestService buildRequestService = new BuildRequestService(); @GetMapping("/list/{org}/repo") public List listOrgRepo(@PathVariable String org) { @@ -29,13 +30,22 @@ public GitHubRepoDto.UserDto listUserRepoAndOrgs(@PathVariable String user) { return userRepoService.RequestUserRepoInfoAndOrgList(user); } - @GetMapping("/list/{user}/{repo}/branch") - public String listRepoBranches(@PathVariable String user, @PathVariable String repo) { - return "listRepoBranches"; + @GetMapping("/list/{owner}/{repo}/branch") + public List listRepoBranches(@PathVariable String owner, @PathVariable String repo) { + return userRepoService.RequestRepoBranches(owner, repo); } @PostMapping("/deploy") - public BuildRequestDto deployRequest(@RequestBody BuildRequestDto request) { - return request; + public ResponseEntity deployRequest(@RequestBody BuildRequestDto request) { + logger.info("request : {}", "message"); + buildRequestService.RequestBuild(request); +// logger.info("request : {}", request); + + return ResponseEntity.ok("success"); + } + + @GetMapping("/health") + public ResponseEntity checkHealth() { + return ResponseEntity.ok("success"); } } \ No newline at end of file diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java b/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java new file mode 100644 index 0000000..6f10dbf --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java @@ -0,0 +1,29 @@ +package com.kumofactory.cloud.appDeploy.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public record BuildRequestDto( + @JsonProperty("target-instance") String instanceId, // required + @JsonProperty("github-token") String gitHubToken, + @JsonProperty("user") String user, // required + @JsonProperty("repo") String repo, // required + @JsonProperty("branch") String branch, // required + @JsonProperty("Dockerfile") Boolean dockerfile, + @JsonProperty("Language") String language, // required + @JsonProperty("env") List env) // required + { + public record EnvInfoDTO( + @JsonProperty("key") String key, + @JsonProperty("value") String value + ) { } + + public BuildRequestDto setDockerfile(Boolean dockerfile) { + return new BuildRequestDto(instanceId, gitHubToken, user, repo, branch, dockerfile, language, env); + } + + public BuildRequestDto setgithubToken(String gitHubToken) { + return new BuildRequestDto(instanceId, gitHubToken, user, repo, branch, dockerfile, language, env); + } +} diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java index e842581..3d16d90 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java @@ -1,9 +1,12 @@ package com.kumofactory.cloud.appDeploy.service; import com.fasterxml.jackson.databind.JsonNode; +import com.kumofactory.cloud.appDeploy.dto.BuildRequestDto; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -16,8 +19,28 @@ @Slf4j public class BuildRequestService { private final Logger logger = LoggerFactory.getLogger(BuildRequestService.class); - private String token; + private String token = null; private String baseUri = "https://api.github.com"; + @Value("${build.server}") + private String buildServerUri; + + public void RequestBuild(BuildRequestDto request) { + String url = buildServerUri + "/api/v1/deploy"; + request.setDockerfile(isDockerfileExist(request.user(), request.repo())); + request.setgithubToken(token); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + HttpEntity httpEntity = new HttpEntity<>(request, headers); + ResponseEntity response = new RestTemplate().exchange(url, HttpMethod.POST, httpEntity, String.class); + + if (response.getStatusCode().is2xxSuccessful()) { + logger.info("response : {}", response.getBody()); + } else { + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + } + } private Boolean isDockerfileExist(String userName ,String repoName) { String url = baseUri + "/repos/" + userName + "/" + repoName + "/contents/Dockerfile"; diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java index f07ca50..b8373aa 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java @@ -116,4 +116,28 @@ private ResponseEntity RequestGitHubAPIs(String uri) { HttpEntity httpEntity = new HttpEntity<>(headers); return new RestTemplate().exchange(uri, HttpMethod.GET, httpEntity, JsonNode.class); } + + public List RequestRepoBranches(String owner, String repo) { + String uri = "https://api.github.com/repos/" + owner + "/" + repo + "/branches"; + ResponseEntity response = RequestGitHubAPIs(uri); + + List branchList = new ArrayList<>(); + + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + logger.info("response : {}", responseBody); + + if (responseBody.isArray()) { + for (JsonNode node : responseBody) { + if (node.has("name")) { + branchList.add(node.get("name").asText()); + } + } + } + return branchList; + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return branchList; + } } \ No newline at end of file From 30dcb64fc1050f7dd85d2719a96c728b7d378e35 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Tue, 1 Aug 2023 14:22:06 +0900 Subject: [PATCH 16/63] fix: Json naming convention #16 --- .../cloud/appDeploy/dto/BuildRequestDto.java | 6 ++--- .../cloud/appDeploy/dto/GitHubRepoDto.java | 20 +++++++-------- .../cloud/appDeploy/dto/UserRepoDto.java | 25 ------------------- 3 files changed, 12 insertions(+), 39 deletions(-) delete mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/dto/UserRepoDto.java diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java b/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java index 6f10dbf..3908907 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java @@ -5,13 +5,13 @@ import java.util.List; public record BuildRequestDto( - @JsonProperty("target-instance") String instanceId, // required - @JsonProperty("github-token") String gitHubToken, + @JsonProperty("targetInstance") String instanceId, // required + @JsonProperty("githubToken") String gitHubToken, @JsonProperty("user") String user, // required @JsonProperty("repo") String repo, // required @JsonProperty("branch") String branch, // required @JsonProperty("Dockerfile") Boolean dockerfile, - @JsonProperty("Language") String language, // required + @JsonProperty("language") String language, // required @JsonProperty("env") List env) // required { public record EnvInfoDTO( diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/dto/GitHubRepoDto.java b/src/main/java/com/kumofactory/cloud/appDeploy/dto/GitHubRepoDto.java index 2a3ac90..9b94f75 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/dto/GitHubRepoDto.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/dto/GitHubRepoDto.java @@ -7,21 +7,19 @@ public class GitHubRepoDto { public record RepoInfoDto( @JsonProperty("name") String name, - @JsonProperty("full_name") String fullName, + @JsonProperty("fullName") String fullName, @JsonProperty("private") Boolean isPrivate, @JsonProperty("fork") Boolean isFork ) { } - public record OrganizationDto( - @JsonProperty("organization_name") String organizationName, - @JsonProperty("organization_repo_count") Integer organizationRepoCount, - @JsonProperty("organization_repo") List organizationRepo - ) { } - public record UserDto( - @JsonProperty("personal_repo_count") Integer personalRepoCount, - @JsonProperty("personal_repo") List personalRepo, - @JsonProperty("organization_count") Integer organizationCount, - @JsonProperty("organization") List organizationList +// @JsonProperty("personal_repo_count") Integer personalRepoCount, +// @JsonProperty("personal_repo") List personalRepo, +// @JsonProperty("organization_count") Integer organizationCount, +// @JsonProperty("organization") List organizationList + @JsonProperty("repoCount") Integer personalRepoCount, + @JsonProperty("repoInfo") List personalRepo, + @JsonProperty("orgCount") Integer organizationCount, + @JsonProperty("orgList") List organizationList ) { } } diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/dto/UserRepoDto.java b/src/main/java/com/kumofactory/cloud/appDeploy/dto/UserRepoDto.java deleted file mode 100644 index f357ca7..0000000 --- a/src/main/java/com/kumofactory/cloud/appDeploy/dto/UserRepoDto.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.kumofactory.cloud.appDeploy.dto; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - - -public record UserRepoDto( - @JsonProperty("personal_repo_count") Integer personalRepoCount, - @JsonProperty("personal_repo") List personalRepo, - @JsonProperty("organization_count") Integer organizationCount, - @JsonProperty("organization") List organization -) { - public record RepoInfoDto( - @JsonProperty("name") String name, - @JsonProperty("full_name") String fullName, - @JsonProperty("private") Boolean isPrivate, - @JsonProperty("fork") Boolean isFork - ) { } - public record OrganizationDto( - @JsonProperty("organization_name") String organizationName, - @JsonProperty("organization_repo_count") Integer organizationRepoCount, - @JsonProperty("organization_repo") List organizationRepo - ) { } -} \ No newline at end of file From 1b34f18d9acaf4191a3ad7351f7e233f8c8a419d Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Fri, 4 Aug 2023 23:40:23 +0900 Subject: [PATCH 17/63] feat : add validating Enum type value --- build.gradle | 7 +++ .../cloud/blueprint/dto/aws/AccessScope.java | 2 + .../blueprint/dto/aws/AvailabilityZone.java | 2 + .../kumofactory/cloud/config/OauthConfig.java | 33 ---------- .../auth/AuthorizationFromToken.java | 2 +- .../auth/AuthorizationFromTokenAspect.java | 60 +++++++++++++++++++ .../annotation/validation/EnumValidator.java | 22 +++++++ .../validation/EnumValidatorImpl.java | 26 ++++++++ .../{ => global}/config/OAuthProvider.java | 0 .../cloud/global/config/OauthConfig.java | 34 +++++++++++ .../cloud/global/config/RabbitMQConfig.java | 35 +++++++++++ .../auth/AuthorizationFromTokenAspect.java | 60 ------------------- 12 files changed, 189 insertions(+), 94 deletions(-) create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java delete mode 100644 src/main/java/com/kumofactory/cloud/config/OauthConfig.java rename src/main/java/com/kumofactory/cloud/global/{middleware => annotation}/auth/AuthorizationFromToken.java (83%) create mode 100644 src/main/java/com/kumofactory/cloud/global/annotation/auth/AuthorizationFromTokenAspect.java create mode 100644 src/main/java/com/kumofactory/cloud/global/annotation/validation/EnumValidator.java create mode 100644 src/main/java/com/kumofactory/cloud/global/annotation/validation/EnumValidatorImpl.java rename src/main/java/com/kumofactory/cloud/{ => global}/config/OAuthProvider.java (100%) create mode 100644 src/main/java/com/kumofactory/cloud/global/config/OauthConfig.java create mode 100644 src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java delete mode 100644 src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java diff --git a/build.gradle b/build.gradle index 91a416c..e2457ae 100644 --- a/build.gradle +++ b/build.gradle @@ -23,6 +23,7 @@ dependencies { developmentOnly 'org.springframework.boot:spring-boot-devtools' implementation 'org.springframework.boot:spring-boot-starter-web' testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.amqp:spring-rabbit-test' implementation 'mysql:mysql-connector-java:8.0.33' implementation 'org.springframework.boot:spring-boot-starter-validation' compileOnly 'org.projectlombok:lombok:1.18.24' @@ -33,6 +34,12 @@ dependencies { implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2' implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2' implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2' + + implementation "io.hypersistence:hypersistence-utils-hibernate-55:3.5.0" + + + // dependency of rabbitmq + implementation 'org.springframework.boot:spring-boot-starter-amqp' } tasks.named('test') { diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java new file mode 100644 index 0000000..dfa0008 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java @@ -0,0 +1,2 @@ +package com.kumofactory.cloud.blueprint.dto.aws;public class AccessScope { +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java new file mode 100644 index 0000000..4fabf7f --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java @@ -0,0 +1,2 @@ +package com.kumofactory.cloud.blueprint.dto.aws;public class AvailabilityZone { +} diff --git a/src/main/java/com/kumofactory/cloud/config/OauthConfig.java b/src/main/java/com/kumofactory/cloud/config/OauthConfig.java deleted file mode 100644 index 1f693fa..0000000 --- a/src/main/java/com/kumofactory/cloud/config/OauthConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.kumofactory.cloud.config; - -import lombok.Data; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -@Component -@Data -@ConfigurationProperties(prefix = "oauth") -public class OauthConfig { - @Value("${oauth.github.client_id}") - private String githubClientId; - @Value("${oauth.github.client_secret_id}") - private String githubClientSecretId; - @Value("${oauth.github.get_access_token_url}") - private String getAccessTokenUrlFromGithub; - - @Value("${oauth.github.user_info_endpoint}") - private String getUserInfoUrlFromGitHub; - - @Value("${oauth.google.client_id}") - private String googleClientId; - @Value("${oauth.google.client_secret_id}") - private String googleClientSecretId; - @Value("${oauth.google.redirect_url}") - private String googleOauthRedirectUrl; - @Value("${oauth.google.get_access_token_url}") - private String getAccessTokenUrlFromGoogle; - - @Value("${oauth.google.user_info_endpoint}") - private String getUserInfoUrlFromGoogle; -} diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromToken.java b/src/main/java/com/kumofactory/cloud/global/annotation/auth/AuthorizationFromToken.java similarity index 83% rename from src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromToken.java rename to src/main/java/com/kumofactory/cloud/global/annotation/auth/AuthorizationFromToken.java index 7434ab6..50034f2 100644 --- a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromToken.java +++ b/src/main/java/com/kumofactory/cloud/global/annotation/auth/AuthorizationFromToken.java @@ -1,4 +1,4 @@ -package com.kumofactory.cloud.global.middleware.auth; +package com.kumofactory.cloud.global.annotation.auth; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/com/kumofactory/cloud/global/annotation/auth/AuthorizationFromTokenAspect.java b/src/main/java/com/kumofactory/cloud/global/annotation/auth/AuthorizationFromTokenAspect.java new file mode 100644 index 0000000..0bf9f7f --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/annotation/auth/AuthorizationFromTokenAspect.java @@ -0,0 +1,60 @@ +package com.kumofactory.cloud.global.annotation.auth; + +import com.kumofactory.cloud.auth.jwt.provider.JwtTokenProvider; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.JwtException; +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.util.Objects; + +@Aspect +@Component +@RequiredArgsConstructor +public class AuthorizationFromTokenAspect { + private final JwtTokenProvider jwtTokenProvider; + private final Logger logger = LoggerFactory.getLogger(AuthorizationFromTokenAspect.class); + + @Around(value = "@annotation(AuthorizationFromToken)") + public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, AuthorizationFromToken AuthorizationFromToken) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); + String userId = getUserFromAccessToken(request.getHeader("Authorization")); + if (userId == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("토큰이 만료되었습니다."); + } + // 추출된 사용자 정보를 매개변수로 전달 + Object[] args = joinPoint.getArgs(); + args[args.length - 1] = userId; + return joinPoint.proceed(args); + } + + // user oauth id 추출 + private String getUserFromAccessToken(String token) { + String accessToken = token.split(" ")[1]; + logger.info("get From Client accessToken: {}", accessToken); + try { + boolean isValidate = jwtTokenProvider.validateToken(accessToken); + if (isValidate) { + return jwtTokenProvider.getClaimsFormToken(accessToken).getSubject(); + } + } catch (ExpiredJwtException exception) { // Access Token 이 만료됐을 때 + return null; + } catch (JwtException e) { // Access Token 이 유효하지 않을 때 + return null; + } catch (NullPointerException e) { // Access Token 이 null 일 때 + return null; + } + return null; + } +} diff --git a/src/main/java/com/kumofactory/cloud/global/annotation/validation/EnumValidator.java b/src/main/java/com/kumofactory/cloud/global/annotation/validation/EnumValidator.java new file mode 100644 index 0000000..c1f0f99 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/annotation/validation/EnumValidator.java @@ -0,0 +1,22 @@ +package com.kumofactory.cloud.global.annotation.validation; + +import javax.validation.Constraint; +import java.lang.annotation.*; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE}) +@Retention(RUNTIME) +@Documented +@Constraint(validatedBy = EnumValidatorImpl.class) +public @interface EnumValidator { + Class> enumClass(); + + String message() default "must be any of enum {enumClass}"; + + Class[] groups() default {}; + + Class[] payload() default {}; + +} diff --git a/src/main/java/com/kumofactory/cloud/global/annotation/validation/EnumValidatorImpl.java b/src/main/java/com/kumofactory/cloud/global/annotation/validation/EnumValidatorImpl.java new file mode 100644 index 0000000..91574f8 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/annotation/validation/EnumValidatorImpl.java @@ -0,0 +1,26 @@ +package com.kumofactory.cloud.global.annotation.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class EnumValidatorImpl implements ConstraintValidator { + private List acceptedValues; + + @Override + public void initialize(EnumValidator annotaion) { + acceptedValues = Stream.of(annotaion.enumClass().getEnumConstants()) + .map(Enum::name) + .collect(Collectors.toList()); + } + + @Override + public boolean isValid(CharSequence value, ConstraintValidatorContext context) { + if (value == null) { + return true; + } + return acceptedValues.contains(value.toString()); + } +} diff --git a/src/main/java/com/kumofactory/cloud/config/OAuthProvider.java b/src/main/java/com/kumofactory/cloud/global/config/OAuthProvider.java similarity index 100% rename from src/main/java/com/kumofactory/cloud/config/OAuthProvider.java rename to src/main/java/com/kumofactory/cloud/global/config/OAuthProvider.java diff --git a/src/main/java/com/kumofactory/cloud/global/config/OauthConfig.java b/src/main/java/com/kumofactory/cloud/global/config/OauthConfig.java new file mode 100644 index 0000000..ee49593 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/config/OauthConfig.java @@ -0,0 +1,34 @@ +package com.kumofactory.cloud.config; + +import lombok.Data; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@Data +@ConfigurationProperties(prefix = "oauth") +public class OauthConfig { + @Value("${oauth.github.client_id}") + private String githubClientId; + @Value("${oauth.github.client_secret_id}") + private String githubClientSecretId; + @Value("${oauth.github.get_access_token_url}") + private String getAccessTokenUrlFromGithub; + + @Value("${oauth.github.user_info_endpoint}") + private String getUserInfoUrlFromGitHub; + + @Value("${oauth.google.client_id}") + private String googleClientId; + @Value("${oauth.google.client_secret_id}") + private String googleClientSecretId; + @Value("${oauth.google.redirect_url}") + private String googleOauthRedirectUrl; + @Value("${oauth.google.get_access_token_url}") + private String getAccessTokenUrlFromGoogle; + + @Value("${oauth.google.user_info_endpoint}") + private String getUserInfoUrlFromGoogle; + +} diff --git a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java new file mode 100644 index 0000000..9c3322e --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java @@ -0,0 +1,35 @@ +package com.kumofactory.cloud.config; + +import com.rabbitmq.client.ConnectionFactory; +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RabbitMQConfig { + private final String queueName = "aws.cdk.queue"; + + @Bean + public Queue queue() { + return new Queue(queueName, false); + } + + @Bean + public ConnectionFactory connectionFactory() { + CachingConnectionFactory factory = new CachingConnectionFactory(); + factory.setHost("localhost"); + factory.setUsername("guest"); + factory.setPassword("guest"); + return factory.getRabbitConnectionFactory(); + } + + @Bean + public AmqpTemplate rabbitTemplate() { + RabbitTemplate template = new RabbitTemplate((org.springframework.amqp.rabbit.connection.ConnectionFactory) connectionFactory()); + template.setRoutingKey(queueName); + return template; + } +} diff --git a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java b/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java deleted file mode 100644 index a73d4d1..0000000 --- a/src/main/java/com/kumofactory/cloud/global/middleware/auth/AuthorizationFromTokenAspect.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.kumofactory.cloud.global.middleware.auth; - -import com.kumofactory.cloud.auth.jwt.provider.JwtTokenProvider; -import io.jsonwebtoken.ExpiredJwtException; -import io.jsonwebtoken.JwtException; -import lombok.RequiredArgsConstructor; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; -import java.util.Objects; - -@Aspect -@Component -@RequiredArgsConstructor -public class AuthorizationFromTokenAspect { - private final JwtTokenProvider jwtTokenProvider; - private final Logger logger = LoggerFactory.getLogger(AuthorizationFromTokenAspect.class); - - @Around(value = "@annotation(AuthorizationFromToken)") - public Object applyAuthorizationFromToken(ProceedingJoinPoint joinPoint, AuthorizationFromToken AuthorizationFromToken) throws Throwable { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletRequest request = Objects.requireNonNull(attributes).getRequest(); - String userId = getUserFromAccessToken(request.getHeader("Authorization")); - if (userId == null) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("토큰이 만료되었습니다."); - } - // 추출된 사용자 정보를 매개변수로 전달 - Object[] args = joinPoint.getArgs(); - args[args.length - 1] = userId; - return joinPoint.proceed(args); - } - - // user oauth id 추출 - private String getUserFromAccessToken(String token) { - String accessToken = token.split(" ")[1]; - logger.info("get From Client accessToken: {}", accessToken); - try { - boolean isValidate = jwtTokenProvider.validateToken(accessToken); - if (isValidate) { - return jwtTokenProvider.getClaimsFormToken(accessToken).getSubject(); - } - } catch (ExpiredJwtException exception) { // Access Token 이 만료됐을 때 - return null; - } catch (JwtException e) { // Access Token 이 유효하지 않을 때 - return null; - } catch (NullPointerException e) { // Access Token 이 null 일 때 - return null; - } - return null; - } -} From 9ea3ae535d600943748905bbd94a88f565aba3f2 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Fri, 4 Aug 2023 23:40:56 +0900 Subject: [PATCH 18/63] feat : add column options, az, scope in AwsComponent --- .../cloud/blueprint/BlueprintController.java | 77 +++++++++------ .../blueprint/domain/aws/AwsComponent.java | 94 ++++++++++++------- .../cloud/blueprint/dto/aws/AccessScope.java | 7 +- .../blueprint/dto/aws/AvailabilityZone.java | 5 +- .../blueprint/dto/aws/AwsComponentDto.java | 49 ++++++---- 5 files changed, 151 insertions(+), 81 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index 5053821..4ce311c 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -2,7 +2,8 @@ import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; -import com.kumofactory.cloud.global.middleware.auth.AuthorizationFromToken; +import com.kumofactory.cloud.global.annotation.auth.AuthorizationFromToken; +import com.kumofactory.cloud.global.rabbitmq.MessageProducer; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; @@ -14,36 +15,54 @@ @RequestMapping("/blueprint") @Slf4j public class BlueprintController { - private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); - private final AwsBlueprintService awsBlueprintService; + private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); + private final AwsBlueprintService awsBlueprintService; + private final MessageProducer sender; - @GetMapping("/aws/{id}") - @AuthorizationFromToken - public Object getAwsBlueprint(@PathVariable("id") Long id, String userId) { - logger.info("aws blue print id: {}", id); - AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); - return awsBlueprint; - } + @GetMapping("/aws/{id}") + @AuthorizationFromToken + public Object getAwsBlueprint(@PathVariable("id") Long id, String userId) { + logger.info("aws blue print id: {}", id); + AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); + return awsBlueprint; + } - @GetMapping("/aws/list") - @AuthorizationFromToken - public Object getAwsBlueprintList(String userId) { - logger.info("userId: {}", userId); - return awsBlueprintService.getMyAwsBlueprints(userId); - } + @GetMapping("/aws/list") + @AuthorizationFromToken + public Object getAwsBlueprintList(String userId) { + logger.info("userId: {}", userId); + return awsBlueprintService.getMyAwsBlueprints(userId); + } - @PostMapping("/aws") - @AuthorizationFromToken - public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) { - logger.info(userId); - awsBlueprintService.store(awsBluePrintDto, userId); - return "hello-world"; - } + @PostMapping("/aws") + @AuthorizationFromToken + public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) { + logger.info(userId); + awsBlueprintService.store(awsBluePrintDto, userId); + return "hello-world"; + } - @GetMapping("/test") - @AuthorizationFromToken - public String testMiddleware(String userId) { - System.out.printf("userId: %s\n", userId); - return userId; - } + @GetMapping("/test") + public String testMiddleware() { + String message = "Hello World I'm test Message"; + try { + sender.sendMessage(message); + return "send message success"; + } catch (Exception e) { + System.out.println(e); + return "send message fail"; + } + } + + @GetMapping("/test2") + public String testMiddleware2() { + String message = "Hello World I'm test Message2"; + try { + sender.sendMessage2(message); + return "send message success"; + } catch (Exception e) { + System.out.println(e); + return "send message fail"; + } + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java index f242204..2ca2ff6 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java @@ -1,54 +1,82 @@ package com.kumofactory.cloud.blueprint.domain.aws; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.kumofactory.cloud.blueprint.dto.aws.AccessScope; +import com.kumofactory.cloud.blueprint.dto.aws.AvailabilityZone; import com.kumofactory.cloud.blueprint.dto.aws.AwsComponentDto; import java.util.Date; import java.util.List; +import java.util.Map; import javax.persistence.*; +import io.hypersistence.utils.hibernate.type.json.JsonType; +import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.Type; +import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.UpdateTimestamp; +import static javax.persistence.EnumType.STRING; + @Entity @Getter @Setter @NoArgsConstructor +@AllArgsConstructor +@TypeDef( + name = "json", + typeClass = JsonType.class +) public class AwsComponent { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @CreationTimestamp - private Date created_at; - @UpdateTimestamp - private Date updated_at; - - @Column(unique = true) - private String ui_id; // Client 에서 생성하는 uuid - - @Enumerated(EnumType.STRING) - private AwsComponentType type; // Component 타입 (vm, vpc, subnet, ...) - - // Component 의 좌측 상단 좌표 - private Integer position_x; - private Integer position_y; - - @ManyToOne - private AwsBluePrint bluePrint; - - // ============== 생성함수 ================= // - public static AwsComponent createAwsComponent(AwsComponentDto awsComponentDto, - AwsBluePrint awsBluePrint) { - AwsComponent awsComponent = new AwsComponent(); - awsComponent.setUi_id(awsComponentDto.getId()); - awsComponent.setPosition_x(awsComponentDto.getX()); - awsComponent.setPosition_y(awsComponentDto.getY()); - awsComponent.setType(awsComponentDto.getType()); - awsComponent.setBluePrint(awsBluePrint); - return awsComponent; - } + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @CreationTimestamp + private Date created_at; + @UpdateTimestamp + private Date updated_at; + + @Column(unique = true) + private String ui_id; // Client 에서 생성하는 uuid + + @Enumerated(STRING) + private AwsComponentType type; // Component 타입 (vm, vpc, subnet, ...) + + @Enumerated(STRING) + private AccessScope scope; + + @Enumerated(STRING) + private AvailabilityZone az; + + @Type(type = "json") + @Column(columnDefinition = "json") + private Map options; + + // Component 의 좌측 상단 좌표 + private Integer position_x; + private Integer position_y; + + @ManyToOne + private AwsBluePrint bluePrint; + + // ============== 생성함수 ================= // + public static AwsComponent createAwsComponent(AwsComponentDto awsComponentDto, + AwsBluePrint awsBluePrint) { + AwsComponent awsComponent = new AwsComponent(); + awsComponent.setUi_id(awsComponentDto.getId()); + awsComponent.setPosition_x(awsComponentDto.getX()); + awsComponent.setPosition_y(awsComponentDto.getY()); + awsComponent.setType(awsComponentDto.getType()); + awsComponent.setAz(awsComponentDto.getAz()); + awsComponent.setScope(awsComponentDto.getScope()); + awsComponent.setOptions(awsComponentDto.getOptions()); + awsComponent.setBluePrint(awsBluePrint); + return awsComponent; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java index dfa0008..f7ce2d9 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java @@ -1,2 +1,5 @@ -package com.kumofactory.cloud.blueprint.dto.aws;public class AccessScope { -} +package com.kumofactory.cloud.blueprint.dto.aws; + +public enum AccessScope { + PUBLIC, PRIVATE, DATABASE +} \ No newline at end of file diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java index 4fabf7f..fda32f3 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java @@ -1,2 +1,5 @@ -package com.kumofactory.cloud.blueprint.dto.aws;public class AvailabilityZone { +package com.kumofactory.cloud.blueprint.dto.aws; + +public enum AvailabilityZone { + AP_NORTHEAST_2A, AP_NORTHEAST_2C } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java index 8905048..be2b17d 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java @@ -3,33 +3,50 @@ import com.kumofactory.cloud.blueprint.domain.aws.AwsComponent; import com.kumofactory.cloud.blueprint.domain.aws.AwsComponentType; +import javax.persistence.Enumerated; import javax.validation.constraints.NotNull; +import com.kumofactory.cloud.global.annotation.validation.EnumValidator; import lombok.Getter; import lombok.Setter; +import org.springframework.validation.annotation.Validated; +import java.util.Map; + +// todo : Area Component Dto 추가 @Getter @Setter public class AwsComponentDto { - @NotNull - private String id; + @NotNull + private String id; + + @NotNull + private Integer x; + + @NotNull + private Integer y; + + @NotNull + private AwsComponentType type; - @NotNull - private Integer x; + @EnumValidator(enumClass = AwsComponentType.class) + private AccessScope scope; - @NotNull - private Integer y; + @EnumValidator(enumClass = AvailabilityZone.class) + private AvailabilityZone az; - @NotNull - private AwsComponentType type; + private Map options; - public static AwsComponentDto mapper(AwsComponent awsComponent) { - AwsComponentDto awsComponentDto = new AwsComponentDto(); - awsComponentDto.setId(awsComponent.getUi_id()); - awsComponentDto.setX(awsComponent.getPosition_x()); - awsComponentDto.setY(awsComponent.getPosition_y()); - awsComponentDto.setType(awsComponent.getType()); - return awsComponentDto; - } + public static AwsComponentDto mapper(AwsComponent awsComponent) { + AwsComponentDto awsComponentDto = new AwsComponentDto(); + awsComponentDto.setId(awsComponent.getUi_id()); + awsComponentDto.setX(awsComponent.getPosition_x()); + awsComponentDto.setY(awsComponent.getPosition_y()); + awsComponentDto.setType(awsComponent.getType()); + awsComponentDto.setAz(awsComponent.getAz()); + awsComponentDto.setScope(awsComponent.getScope()); + awsComponentDto.setOptions(awsComponent.getOptions()); + return awsComponentDto; + } } From e7c69389c6bc56a256d52e56e1a6e622279e6881 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 16:49:16 +0900 Subject: [PATCH 19/63] feat: add staging.yml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 개발 서버에 사용할 yml 파일 - registry 에 push 하는 일까지만 함 --- .github/workflows/Staging.yml | 59 +++++++++++++++++++ .../cloud/blueprint/dto/aws/AwsCdkDto.java | 2 + 2 files changed, 61 insertions(+) create mode 100644 .github/workflows/Staging.yml create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java diff --git a/.github/workflows/Staging.yml b/.github/workflows/Staging.yml new file mode 100644 index 0000000..647f14a --- /dev/null +++ b/.github/workflows/Staging.yml @@ -0,0 +1,59 @@ +name: Build and Push to ECR +on: + push: + branches: + - staging # Change this to your desired branch +env: + REGION: ap-northeast-2 # Seoul + + +jobs: + build-and-push: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up JDK 17 + uses: actions/setup-java@v2 + with: + java-version: 17 + + - name: make application.yml + run: | + mkdir ./src/main/resources + cd ./src/main/resources + touch ./application.yml + echo "${{ secrets.YML }}" > ./application.yml + shell: bash + + - name: make application-dev.yml + run: | + cd ./src/main/resources + touch ./application-dev.yml + echo "${{ secrets.YML_DEV }}" > ./application-dev.yml + shell: bash + + - name: Build Spring Boot application + run: ./gradlew clean build + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v1 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ env.REGION }} + + - name: Login to Amazon ECR + id: login-ecr + run: | + echo ${{ secrets.AWS_SECRET_ACCESS_KEY }} | docker login --username AWS --password-stdin ${{ secrets.AWS_ACCESS_KEY_ID }}.dkr.ecr.ap-northeast-2.amazonaws.com + + - name: Build and tag Docker image + run: | + docker build -t ${{ secrets.ECR_REGISTRY }}/spring-app-image:latest . + + - name: Push Docker image to ECR + run: | + docker push ${{ secrets.ECR_REGISTRY }}/spring-app-image:latest diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java new file mode 100644 index 0000000..91f122b --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java @@ -0,0 +1,2 @@ +package com.kumofactory.cloud.blueprint.dto.aws;public class AwsCdkDto { +} From 036de9fdd29448947848c0af886f35afe25079e9 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 16:50:20 +0900 Subject: [PATCH 20/63] feat: add AwsCdkDto --- .../cloud/blueprint/dto/aws/AwsCdkDto.java | 26 ++++++++++++++- .../service/AwsBlueprintService.java | 3 +- .../service/AwsBlueprintServiceImpl.java | 16 +++++++--- .../cloud/global/config/RabbitMQConfig.java | 26 ++++++++++++--- .../global/rabbitmq/MessageProducer.java | 32 +++++++++++++++++++ .../cloud/member/domain/Member.java | 2 ++ 6 files changed, 95 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/kumofactory/cloud/global/rabbitmq/MessageProducer.java diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java index 91f122b..d9cf59d 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java @@ -1,2 +1,26 @@ -package com.kumofactory.cloud.blueprint.dto.aws;public class AwsCdkDto { +package com.kumofactory.cloud.blueprint.dto.aws; + +import com.kumofactory.cloud.blueprint.domain.aws.AwsComponentType; +import lombok.Getter; +import lombok.Setter; + +import java.util.Map; +import java.util.UUID; + +@Getter +@Setter +public class AwsCdkDto { + String id; + AwsComponentType type; + AccessScope scope; + Map options; + + public static AwsCdkDto createAwsCdkDto(AwsComponentDto awsComponentDto) { + AwsCdkDto awsCdkDto = new AwsCdkDto(); + awsCdkDto.setId(UUID.randomUUID().toString()); + awsCdkDto.setType(awsComponentDto.getType()); + awsCdkDto.setScope(awsComponentDto.getScope()); + awsCdkDto.setOptions(awsComponentDto.getOptions()); + return awsCdkDto; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java index 9e1f8c3..af1eb98 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java @@ -1,6 +1,7 @@ package com.kumofactory.cloud.blueprint.service; +import com.fasterxml.jackson.core.JsonProcessingException; import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; @@ -13,5 +14,5 @@ public interface AwsBlueprintService { List getMyAwsBlueprints(String userId); - void store(AwsBluePrintDto awsBluePrintDto, String userId); + void store(AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException; } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 28fef92..e67b6a9 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -1,5 +1,6 @@ package com.kumofactory.cloud.blueprint.service; +import com.fasterxml.jackson.core.JsonProcessingException; import com.kumofactory.cloud.blueprint.domain.ComponentLine; import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.domain.aws.AwsComponent; @@ -7,11 +8,13 @@ import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; +import com.kumofactory.cloud.blueprint.dto.aws.AwsCdkDto; import com.kumofactory.cloud.blueprint.dto.aws.AwsComponentDto; import com.kumofactory.cloud.blueprint.repository.ComponentDotRepository; import com.kumofactory.cloud.blueprint.repository.ComponentLineRepository; import com.kumofactory.cloud.blueprint.repository.aws.AwsBluePrintRepository; import com.kumofactory.cloud.blueprint.repository.aws.AwsComponentRepository; +import com.kumofactory.cloud.global.rabbitmq.MessageProducer; import com.kumofactory.cloud.member.MemberRepository; import com.kumofactory.cloud.member.domain.Member; import lombok.RequiredArgsConstructor; @@ -34,7 +37,7 @@ public class AwsBlueprintServiceImpl implements AwsBlueprintService { private final AwsBluePrintRepository awsBluePrintRepository; private final AwsComponentRepository awsComponentRepository; private final ComponentLineRepository componentLineRepository; - private final ComponentDotRepository componentDotRepository; + private final MessageProducer sender; private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); @@ -74,7 +77,7 @@ public List getMyAwsBlueprints(String oauthId) { } @Override - public void store(AwsBluePrintDto awsBluePrintDto, String userId) { + public void store(AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException { Member member = memberRepository.findMemberByOauthId(userId); // BluePrint 저장 AwsBluePrint awsBluePrint = new AwsBluePrint(); @@ -85,13 +88,16 @@ public void store(AwsBluePrintDto awsBluePrintDto, String userId) { List components = new ArrayList<>(); List links = awsBluePrintDto.getLinks(); + List awsCdkDtos = new ArrayList<>(); // Components 저장 for (AwsComponentDto component : awsBluePrintDto.getComponents()) { AwsComponent awsComponent = AwsComponent.createAwsComponent(component, savedBlueprint); + AwsCdkDto awsCdkDto = AwsCdkDto.createAwsCdkDto(component); components.add(awsComponent); + awsCdkDtos.add(awsCdkDto); } - awsComponentRepository.saveAll(components); +// awsComponentRepository.saveAll(components); // Lines 저장 List componentLines = new ArrayList<>(); @@ -99,6 +105,8 @@ public void store(AwsBluePrintDto awsBluePrintDto, String userId) { ComponentLine componentLink = ComponentLine.createComponentLink(link, savedBlueprint); componentLines.add(componentLink); } - componentLineRepository.saveAll(componentLines); +// componentLineRepository.saveAll(componentLines); + + sender.sendAwsCdkOption(awsCdkDtos); } } diff --git a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java index 9c3322e..0c4c781 100644 --- a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java +++ b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java @@ -1,22 +1,39 @@ -package com.kumofactory.cloud.config; +package com.kumofactory.cloud.global.config; import com.rabbitmq.client.ConnectionFactory; -import org.springframework.amqp.core.AmqpTemplate; -import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.*; +import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitMQConfig { - private final String queueName = "aws.cdk.queue"; + public static final String topicExchangeName = "aws.cdk"; + private final String queueName = "kumofactory-queue"; @Bean public Queue queue() { return new Queue(queueName, false); } + @Bean + DirectExchange exchange() { + return new DirectExchange("direct"); + } + + @Bean + TopicExchange exchange2() { + return new TopicExchange(topicExchangeName); + } + + @Bean + Binding binding(Queue queue, TopicExchange exchange) { + return BindingBuilder.bind(queue).to(exchange).with("foo.bar"); + } + @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory factory = new CachingConnectionFactory(); @@ -30,6 +47,7 @@ public ConnectionFactory connectionFactory() { public AmqpTemplate rabbitTemplate() { RabbitTemplate template = new RabbitTemplate((org.springframework.amqp.rabbit.connection.ConnectionFactory) connectionFactory()); template.setRoutingKey(queueName); + template.setMessageConverter(new Jackson2JsonMessageConverter()); return template; } } diff --git a/src/main/java/com/kumofactory/cloud/global/rabbitmq/MessageProducer.java b/src/main/java/com/kumofactory/cloud/global/rabbitmq/MessageProducer.java new file mode 100644 index 0000000..4189915 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/rabbitmq/MessageProducer.java @@ -0,0 +1,32 @@ +package com.kumofactory.cloud.global.rabbitmq; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.kumofactory.cloud.blueprint.domain.aws.AwsComponentType; +import com.kumofactory.cloud.blueprint.dto.aws.AccessScope; +import com.kumofactory.cloud.blueprint.dto.aws.AwsCdkDto; +import com.kumofactory.cloud.global.config.RabbitMQConfig; +import lombok.RequiredArgsConstructor; +import org.springframework.amqp.AmqpException; +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.amqp.core.Exchange; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessagePostProcessor; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Service +@RequiredArgsConstructor +public class MessageProducer { + private final AmqpTemplate rabbitTemplate; + private final String queueName = "kumofactory-queue"; + + public void sendAwsCdkOption(List list) throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + String s = objectMapper.writeValueAsString(list); + rabbitTemplate.convertAndSend(queueName, s); + } +} diff --git a/src/main/java/com/kumofactory/cloud/member/domain/Member.java b/src/main/java/com/kumofactory/cloud/member/domain/Member.java index 0055d94..0bf5505 100644 --- a/src/main/java/com/kumofactory/cloud/member/domain/Member.java +++ b/src/main/java/com/kumofactory/cloud/member/domain/Member.java @@ -28,6 +28,8 @@ public class Member { private String provider; + private String githubAccessToken; + @OneToMany(mappedBy = "member") private List bluePrints; From ac3eeae55c880654e64380e4f818c68ce2fab680 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 16:54:43 +0900 Subject: [PATCH 21/63] update : update staging.yml --- .github/workflows/Staging.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/Staging.yml b/.github/workflows/Staging.yml index 647f14a..9fd2a1e 100644 --- a/.github/workflows/Staging.yml +++ b/.github/workflows/Staging.yml @@ -15,10 +15,13 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - - name: Set up JDK 17 - uses: actions/setup-java@v2 + - uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + name: Set up JDK 17 with: - java-version: 17 + distribution: 'temurin' + java-version: '17' + check-latest: true - name: make application.yml run: | From e4a5dbde39d35fc0f5052d6c9d6252edebb96563 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 17:00:50 +0900 Subject: [PATCH 22/63] refactor : refactor --- .../com/kumofactory/cloud/AppController.java | 21 ++- .../kumofactory/cloud/CloudApplication.java | 12 +- .../cloud/auth/AuthController.java | 119 ++++++------ .../cloud/blueprint/BlueprintController.java | 27 +-- .../cloud/global/config/OAuthProvider.java | 6 +- .../cloud/global/config/OauthConfig.java | 4 +- .../cloud/oauth/OAuthController.java | 23 ++- .../cloud/oauth/service/OAuthService.java | 177 +++++++++--------- .../service/github/GitHubServiceImpl.java | 113 +++++------ .../service/google/GoogleServiceImpl.java | 106 +++++------ 10 files changed, 308 insertions(+), 300 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/AppController.java b/src/main/java/com/kumofactory/cloud/AppController.java index a2bffab..b922bb6 100644 --- a/src/main/java/com/kumofactory/cloud/AppController.java +++ b/src/main/java/com/kumofactory/cloud/AppController.java @@ -1,12 +1,25 @@ package com.kumofactory.cloud; +import com.kumofactory.cloud.auth.jwt.dto.TokenDto; +import com.kumofactory.cloud.auth.jwt.provider.JwtTokenProvider; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Required; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController +@RequiredArgsConstructor public class AppController { - @GetMapping("/") - public String checkHealth() { - return "success"; - } + private final JwtTokenProvider provider; + + @GetMapping("/") + public String checkHealth() { + return "success"; + } + + @GetMapping("/token") + public String createMockTest() { + TokenDto tokenDto = provider.create("11"); + return tokenDto.getAccessToken(); + } } diff --git a/src/main/java/com/kumofactory/cloud/CloudApplication.java b/src/main/java/com/kumofactory/cloud/CloudApplication.java index c494869..7d579ab 100644 --- a/src/main/java/com/kumofactory/cloud/CloudApplication.java +++ b/src/main/java/com/kumofactory/cloud/CloudApplication.java @@ -1,15 +1,21 @@ package com.kumofactory.cloud; +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import java.nio.charset.StandardCharsets; + @SpringBootApplication public class CloudApplication { + private final static String QUEUE_NAME = "hello"; - public static void main(String[] args) { - SpringApplication.run(CloudApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(CloudApplication.class, args); + } } diff --git a/src/main/java/com/kumofactory/cloud/auth/AuthController.java b/src/main/java/com/kumofactory/cloud/auth/AuthController.java index be120df..d38cd52 100644 --- a/src/main/java/com/kumofactory/cloud/auth/AuthController.java +++ b/src/main/java/com/kumofactory/cloud/auth/AuthController.java @@ -3,14 +3,13 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.kumofactory.cloud.auth.jwt.dto.TokenDto; -import com.kumofactory.cloud.global.middleware.auth.AuthorizationFromToken; +import com.kumofactory.cloud.global.annotation.auth.AuthorizationFromToken; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseCookie; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @@ -27,68 +26,68 @@ @Slf4j @RequiredArgsConstructor public class AuthController { - private final AuthService authService; + private final AuthService authService; - @GetMapping("/refresh") - public Object refresh(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException { - try { - Cookie[] cookies = request.getCookies(); - String refreshToken = null; - for (Cookie cookie : cookies) { - if (cookie.getName().equals("refreshToken")) { - log.info("take refreshToken: {}", cookie.getValue()); - refreshToken = cookie.getValue(); - break; - } - } - TokenDto token = authService.refresh(refreshToken); - HttpHeaders responseHeaders = new HttpHeaders(); - ResponseCookie refreshTokenCookie = ResponseCookie.from("refreshToken", token.getRefreshToken()) - .httpOnly(true) - .path("/") - .maxAge(60 * 60 * 24 * 30) - .build(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); - responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); - Map map = new HashMap<>(); - map.put("accessToken", token.getAccessToken()); - log.info("create accessToken: {}", token.getAccessToken()); + @GetMapping("/refresh") + public Object refresh(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException { + try { + Cookie[] cookies = request.getCookies(); + String refreshToken = null; + for (Cookie cookie : cookies) { + if (cookie.getName().equals("refreshToken")) { + log.info("take refreshToken: {}", cookie.getValue()); + refreshToken = cookie.getValue(); + break; + } + } + TokenDto token = authService.refresh(refreshToken); + HttpHeaders responseHeaders = new HttpHeaders(); + ResponseCookie refreshTokenCookie = ResponseCookie.from("refreshToken", token.getRefreshToken()) + .httpOnly(true) + .path("/") + .maxAge(60 * 60 * 24 * 30) + .build(); + responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); + responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); + Map map = new HashMap<>(); + map.put("accessToken", token.getAccessToken()); + log.info("create accessToken: {}", token.getAccessToken()); - return ResponseEntity.ok() - .headers(responseHeaders) - .body(new ObjectMapper().writeValueAsString(map)); + return ResponseEntity.ok() + .headers(responseHeaders) + .body(new ObjectMapper().writeValueAsString(map)); - } catch (RuntimeException e) { - log.info("Refresh Token is expired"); - for (Cookie cookie : request.getCookies()) { - if (cookie.getName().equals("refreshToken")) { - cookie.setMaxAge(0); - cookie.setPath("/"); - response.addCookie(cookie); - return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Refresh Token is expired"); - } - } - } + } catch (RuntimeException e) { + log.info("Refresh Token is expired"); + for (Cookie cookie : request.getCookies()) { + if (cookie.getName().equals("refreshToken")) { + cookie.setMaxAge(0); + cookie.setPath("/"); + response.addCookie(cookie); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Refresh Token is expired"); + } + } + } - return null; - } + return null; + } - @GetMapping("/logout") - public Object logout(HttpServletRequest request, HttpServletResponse response) { - for (Cookie cookie : request.getCookies()) { - if (cookie.getName().equals("refreshToken")) { - cookie.setMaxAge(0); - cookie.setPath("/"); - response.addCookie(cookie); - return ResponseEntity.ok().body("logout"); - } - } - return ResponseEntity.status(HttpStatus.OK).body("logout"); - } + @GetMapping("/logout") + public Object logout(HttpServletRequest request, HttpServletResponse response) { + for (Cookie cookie : request.getCookies()) { + if (cookie.getName().equals("refreshToken")) { + cookie.setMaxAge(0); + cookie.setPath("/"); + response.addCookie(cookie); + return ResponseEntity.ok().body("logout"); + } + } + return ResponseEntity.status(HttpStatus.OK).body("logout"); + } - @DeleteMapping("/withdrawal") - @AuthorizationFromToken - public Object withdrawal(String userId) { - return authService.withdraw(userId); - } + @DeleteMapping("/withdrawal") + @AuthorizationFromToken + public Object withdrawal(String userId) { + return authService.withdraw(userId); + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index 4ce311c..f341bb5 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -1,5 +1,6 @@ package com.kumofactory.cloud.blueprint; +import com.fasterxml.jackson.core.JsonProcessingException; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; import com.kumofactory.cloud.global.annotation.auth.AuthorizationFromToken; @@ -36,33 +37,9 @@ public Object getAwsBlueprintList(String userId) { @PostMapping("/aws") @AuthorizationFromToken - public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) { + public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException { logger.info(userId); awsBlueprintService.store(awsBluePrintDto, userId); return "hello-world"; } - - @GetMapping("/test") - public String testMiddleware() { - String message = "Hello World I'm test Message"; - try { - sender.sendMessage(message); - return "send message success"; - } catch (Exception e) { - System.out.println(e); - return "send message fail"; - } - } - - @GetMapping("/test2") - public String testMiddleware2() { - String message = "Hello World I'm test Message2"; - try { - sender.sendMessage2(message); - return "send message success"; - } catch (Exception e) { - System.out.println(e); - return "send message fail"; - } - } } diff --git a/src/main/java/com/kumofactory/cloud/global/config/OAuthProvider.java b/src/main/java/com/kumofactory/cloud/global/config/OAuthProvider.java index 6d9af0a..aff2b3d 100644 --- a/src/main/java/com/kumofactory/cloud/global/config/OAuthProvider.java +++ b/src/main/java/com/kumofactory/cloud/global/config/OAuthProvider.java @@ -1,6 +1,6 @@ -package com.kumofactory.cloud.config; +package com.kumofactory.cloud.global.config; public enum OAuthProvider { - GOOGLE, - GITHUB + GOOGLE, + GITHUB } diff --git a/src/main/java/com/kumofactory/cloud/global/config/OauthConfig.java b/src/main/java/com/kumofactory/cloud/global/config/OauthConfig.java index ee49593..929debe 100644 --- a/src/main/java/com/kumofactory/cloud/global/config/OauthConfig.java +++ b/src/main/java/com/kumofactory/cloud/global/config/OauthConfig.java @@ -1,4 +1,4 @@ -package com.kumofactory.cloud.config; +package com.kumofactory.cloud.global.config; import lombok.Data; import org.springframework.beans.factory.annotation.Value; @@ -30,5 +30,5 @@ public class OauthConfig { @Value("${oauth.google.user_info_endpoint}") private String getUserInfoUrlFromGoogle; - + } diff --git a/src/main/java/com/kumofactory/cloud/oauth/OAuthController.java b/src/main/java/com/kumofactory/cloud/oauth/OAuthController.java index 44609fa..44dd750 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/OAuthController.java +++ b/src/main/java/com/kumofactory/cloud/oauth/OAuthController.java @@ -1,7 +1,7 @@ package com.kumofactory.cloud.oauth; import com.fasterxml.jackson.core.JsonProcessingException; -import com.kumofactory.cloud.config.OAuthProvider; +import com.kumofactory.cloud.global.config.OAuthProvider; import com.kumofactory.cloud.oauth.service.OAuthService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -12,13 +12,18 @@ @RequiredArgsConstructor public class OAuthController { - private final OAuthService oauthService; + private final OAuthService oauthService; - @GetMapping("/{socialLoginType}") - public ResponseEntity socialLoginRedirect(@PathVariable(name="socialLoginType") String SocialLoginPath, - @RequestParam("code") String code) - throws JsonProcessingException { - OAuthProvider provider = OAuthProvider.valueOf(SocialLoginPath.toUpperCase()); - return oauthService.request(provider, code); - } + @GetMapping("/{socialLoginType}") + public ResponseEntity socialLoginRedirect(@PathVariable(name = "socialLoginType") String SocialLoginPath, + @RequestParam("code") String code) + throws JsonProcessingException { + OAuthProvider provider = OAuthProvider.valueOf(SocialLoginPath.toUpperCase()); + return oauthService.request(provider, code); + } + + @GetMapping("/test") + public String test() throws JsonProcessingException { + return oauthService.generateTestToken().getAccessToken(); + } } diff --git a/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java b/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java index d5539d6..00e0bd0 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java +++ b/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java @@ -1,7 +1,7 @@ package com.kumofactory.cloud.oauth.service; import com.fasterxml.jackson.databind.ObjectMapper; -import com.kumofactory.cloud.config.OAuthProvider; +import com.kumofactory.cloud.global.config.OAuthProvider; import com.kumofactory.cloud.auth.jwt.dto.TokenDto; import com.kumofactory.cloud.auth.jwt.provider.JwtTokenProvider; import com.kumofactory.cloud.member.MemberRepository; @@ -9,10 +9,12 @@ import com.kumofactory.cloud.oauth.dto.UserInfoDto; import com.kumofactory.cloud.oauth.service.github.GitHubService; import com.kumofactory.cloud.oauth.service.google.GoogleService; + import static com.kumofactory.cloud.oauth.dto.OAuthDto.*; import lombok.extern.slf4j.Slf4j; import lombok.RequiredArgsConstructor; +import org.apache.catalina.User; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseCookie; import org.springframework.http.ResponseEntity; @@ -27,88 +29,93 @@ @Slf4j @RequiredArgsConstructor public class OAuthService { - private final GoogleService googleService; - private final GitHubService githubService; - - private final JwtTokenProvider jwtTokenProvider; - private final MemberRepository memberRepository; - - private TokenDto token; - - public ResponseEntity request(OAuthProvider provider, String code) - throws JsonProcessingException { - - HttpHeaders responseHeaders = new HttpHeaders(); - - switch (provider) { - case GOOGLE: { - token = getAccessTokenFromGoogle(code); - break; - } - case GITHUB: { - token = getAccessTokenFromGitHub(code); - break; - } - default: { - throw new IllegalArgumentException("Unknown type of social login."); - } - } - - responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); - - ResponseCookie refreshTokenCookie = ResponseCookie - .from("refreshToken", token.getRefreshToken()) - .httpOnly(true) - .path("/") - .maxAge(Duration.ofDays(365)) - .build(); - - responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); - - Map map = new HashMap<>(); - map.put("accessToken", token.getAccessToken()); - - return ResponseEntity.ok() - .headers(responseHeaders) - .body(new ObjectMapper().writeValueAsString(map)); - } - - // TODO : 중복된 코드 간소화 (getAccessTokenFromXXX) - private TokenDto getAccessTokenFromGoogle(String code) - throws JsonProcessingException { - - GoogleToken accessTokenFromGoogle = googleService.requestAccessToken(code); - if (accessTokenFromGoogle != null) { - - UserInfoDto userInfo = googleService.requestUserInfo(accessTokenFromGoogle.accessToken()); - saveMember(userInfo); - - return jwtTokenProvider.create(userInfo.id()); - } - return null; - } - - private TokenDto getAccessTokenFromGitHub(String code) - throws JsonProcessingException { - - GitHubToken accessTokenFromGithub = githubService.requestAccessToken(code); - if (accessTokenFromGithub != null) { - - UserInfoDto userInfo = githubService.requestUserInfo(accessTokenFromGithub.accessToken()); - saveMember(userInfo); - - - return jwtTokenProvider.create(userInfo.id()); - } - return null; - } - - // 처음 가입한 member 일때만 저장 - private void saveMember(UserInfoDto userInfo) { - Member member = memberRepository.findMemberByOauthId(userInfo.id()); - if (member == null) { - member = Member.createMember(userInfo); - memberRepository.save(member); - } - } + private final GoogleService googleService; + private final GitHubService githubService; + + private final JwtTokenProvider jwtTokenProvider; + private final MemberRepository memberRepository; + + private TokenDto token; + + public ResponseEntity request(OAuthProvider provider, String code) + throws JsonProcessingException { + + HttpHeaders responseHeaders = new HttpHeaders(); + + switch (provider) { + case GOOGLE: { + token = getAccessTokenFromGoogle(code); + break; + } + case GITHUB: { + token = getAccessTokenFromGitHub(code); + break; + } + default: { + throw new IllegalArgumentException("Unknown type of social login."); + } + } + + responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json"); + + ResponseCookie refreshTokenCookie = ResponseCookie + .from("refreshToken", token.getRefreshToken()) + .httpOnly(true) + .path("/") + .maxAge(Duration.ofDays(365)) + .build(); + + responseHeaders.add(HttpHeaders.SET_COOKIE, refreshTokenCookie.toString()); + + Map map = new HashMap<>(); + map.put("accessToken", token.getAccessToken()); + + return ResponseEntity.ok() + .headers(responseHeaders) + .body(new ObjectMapper().writeValueAsString(map)); + } + + public TokenDto generateTestToken() { + UserInfoDto userInfoDto = new UserInfoDto("1234", "github"); + return jwtTokenProvider.create(userInfoDto.id()); + } + + // TODO : 중복된 코드 간소화 (getAccessTokenFromXXX) + private TokenDto getAccessTokenFromGoogle(String code) + throws JsonProcessingException { + + GoogleToken accessTokenFromGoogle = googleService.requestAccessToken(code); + if (accessTokenFromGoogle != null) { + + UserInfoDto userInfo = googleService.requestUserInfo(accessTokenFromGoogle.accessToken()); + saveMember(userInfo); + + return jwtTokenProvider.create(userInfo.id()); + } + return null; + } + + private TokenDto getAccessTokenFromGitHub(String code) + throws JsonProcessingException { + + GitHubToken accessTokenFromGithub = githubService.requestAccessToken(code); + if (accessTokenFromGithub != null) { + + UserInfoDto userInfo = githubService.requestUserInfo(accessTokenFromGithub.accessToken()); + saveMember(userInfo); + + + return jwtTokenProvider.create(userInfo.id()); + } + return null; + } + + // 처음 가입한 member 일때만 저장 + private void saveMember(UserInfoDto userInfo) { + Member member = memberRepository.findMemberByOauthId(userInfo.id()); + if (member == null) { + member = Member.createMember(userInfo); + memberRepository.save(member); + } + } } diff --git a/src/main/java/com/kumofactory/cloud/oauth/service/github/GitHubServiceImpl.java b/src/main/java/com/kumofactory/cloud/oauth/service/github/GitHubServiceImpl.java index 9e77c16..e0ef40e 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/service/github/GitHubServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/oauth/service/github/GitHubServiceImpl.java @@ -1,11 +1,12 @@ package com.kumofactory.cloud.oauth.service.github; -import com.kumofactory.cloud.config.OAuthProvider; -import com.kumofactory.cloud.config.OauthConfig; +import com.kumofactory.cloud.global.config.OAuthProvider; +import com.kumofactory.cloud.global.config.OauthConfig; import com.kumofactory.cloud.oauth.dto.OAuthDto.GitHubToken; import com.kumofactory.cloud.oauth.dto.UserInfoDto; import java.util.Map; + import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; @@ -26,67 +27,67 @@ @RequiredArgsConstructor public class GitHubServiceImpl implements GitHubService { - private final OauthConfig oauthConfig; - private final Logger logger = LoggerFactory.getLogger(GitHubServiceImpl.class); - private final RestTemplate restTemplate = new RestTemplate(); + private final OauthConfig oauthConfig; + private final Logger logger = LoggerFactory.getLogger(GitHubServiceImpl.class); + private final RestTemplate restTemplate = new RestTemplate(); - @Override - public GitHubToken requestAccessToken(String code) throws JsonProcessingException { - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - HttpEntity httpEntity = new HttpEntity<>(headers); + @Override + public GitHubToken requestAccessToken(String code) throws JsonProcessingException { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + HttpEntity httpEntity = new HttpEntity<>(headers); - MultiValueMap queryParams = new LinkedMultiValueMap<>(); - queryParams.add("client_id", oauthConfig.getGithubClientId()); - queryParams.add("client_secret", oauthConfig.getGithubClientSecretId()); - queryParams.add("code", code); + MultiValueMap queryParams = new LinkedMultiValueMap<>(); + queryParams.add("client_id", oauthConfig.getGithubClientId()); + queryParams.add("client_secret", oauthConfig.getGithubClientSecretId()); + queryParams.add("code", code); - UriComponents uri = UriComponentsBuilder.fromHttpUrl( - oauthConfig.getGetAccessTokenUrlFromGithub()) - .queryParams(queryParams) - .build(); - ResponseEntity response = restTemplate - .postForEntity(uri.toUriString(), httpEntity, Map.class); - if (response.getStatusCode() == HttpStatus.OK){ - logger.info("response : {}", response.getBody()); - return new ObjectMapper().readValue(new ObjectMapper().writeValueAsString(response.getBody()), - GitHubToken.class); - } - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - return null; - } + UriComponents uri = UriComponentsBuilder.fromHttpUrl( + oauthConfig.getGetAccessTokenUrlFromGithub()) + .queryParams(queryParams) + .build(); + ResponseEntity response = restTemplate + .postForEntity(uri.toUriString(), httpEntity, Map.class); + if (response.getStatusCode() == HttpStatus.OK) { + logger.info("response : {}", response.getBody()); + return new ObjectMapper().readValue(new ObjectMapper().writeValueAsString(response.getBody()), + GitHubToken.class); + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return null; + } - @Override - public UserInfoDto requestUserInfo(String accessToken) throws JsonProcessingException { + @Override + public UserInfoDto requestUserInfo(String accessToken) throws JsonProcessingException { - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/vnd.github+json"); - headers.set("Authorization", "Bearer " + accessToken); - headers.set("X-GitHub-Api-Version", "2022-11-28"); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/vnd.github+json"); + headers.set("Authorization", "Bearer " + accessToken); + headers.set("X-GitHub-Api-Version", "2022-11-28"); - UriComponents uri = UriComponentsBuilder.fromHttpUrl( - oauthConfig.getGetUserInfoUrlFromGitHub()).build(); + UriComponents uri = UriComponentsBuilder.fromHttpUrl( + oauthConfig.getGetUserInfoUrlFromGitHub()).build(); - RequestEntity requestEntity = RequestEntity - .get(uri.toUri()) - .headers(headers) - .build(); + RequestEntity requestEntity = RequestEntity + .get(uri.toUri()) + .headers(headers) + .build(); - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity response = restTemplate.exchange(requestEntity, JsonNode.class); + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity response = restTemplate.exchange(requestEntity, JsonNode.class); - if (response.getStatusCode() == HttpStatus.OK) { - JsonNode responseBody = response.getBody(); - logger.info("response : {}", response.getBody()); - if(responseBody != null) { - String id = responseBody.get("id").asText(); - String provider = String.valueOf(OAuthProvider.GITHUB); - return new UserInfoDto(id, provider); - } - } - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - return null; - } + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + logger.info("response : {}", response.getBody()); + if (responseBody != null) { + String id = responseBody.get("id").asText(); + String provider = String.valueOf(OAuthProvider.GITHUB); + return new UserInfoDto(id, provider); + } + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return null; + } } diff --git a/src/main/java/com/kumofactory/cloud/oauth/service/google/GoogleServiceImpl.java b/src/main/java/com/kumofactory/cloud/oauth/service/google/GoogleServiceImpl.java index ae7be5c..4397f4a 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/service/google/GoogleServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/oauth/service/google/GoogleServiceImpl.java @@ -3,8 +3,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.kumofactory.cloud.config.OAuthProvider; -import com.kumofactory.cloud.config.OauthConfig; +import com.kumofactory.cloud.global.config.OAuthProvider; +import com.kumofactory.cloud.global.config.OauthConfig; import com.kumofactory.cloud.oauth.dto.OAuthDto.GoogleToken; import com.kumofactory.cloud.oauth.dto.UserInfoDto; import lombok.RequiredArgsConstructor; @@ -30,63 +30,63 @@ @RequiredArgsConstructor public class GoogleServiceImpl implements GoogleService { - private final OauthConfig oauthConfig; - private final Logger logger = LoggerFactory.getLogger(GoogleServiceImpl.class); - private final RestTemplate restTemplate = new RestTemplate(); + private final OauthConfig oauthConfig; + private final Logger logger = LoggerFactory.getLogger(GoogleServiceImpl.class); + private final RestTemplate restTemplate = new RestTemplate(); - @Override - public GoogleToken requestAccessToken(String code) throws JsonProcessingException { - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - HttpEntity httpEntity = new HttpEntity<>(headers); + @Override + public GoogleToken requestAccessToken(String code) throws JsonProcessingException { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + HttpEntity httpEntity = new HttpEntity<>(headers); - MultiValueMap queryParams = new LinkedMultiValueMap<>(); - queryParams.add("client_id", oauthConfig.getGoogleClientId()); - queryParams.add("client_secret", oauthConfig.getGoogleClientSecretId()); - queryParams.add("code", code); - queryParams.add("redirect_uri", oauthConfig.getGoogleOauthRedirectUrl()); - queryParams.add("grant_type", "authorization_code"); + MultiValueMap queryParams = new LinkedMultiValueMap<>(); + queryParams.add("client_id", oauthConfig.getGoogleClientId()); + queryParams.add("client_secret", oauthConfig.getGoogleClientSecretId()); + queryParams.add("code", code); + queryParams.add("redirect_uri", oauthConfig.getGoogleOauthRedirectUrl()); + queryParams.add("grant_type", "authorization_code"); - UriComponents uri = UriComponentsBuilder.fromHttpUrl( - oauthConfig.getGetAccessTokenUrlFromGoogle()) - .queryParams(queryParams) - .build(); + UriComponents uri = UriComponentsBuilder.fromHttpUrl( + oauthConfig.getGetAccessTokenUrlFromGoogle()) + .queryParams(queryParams) + .build(); - ResponseEntity response = restTemplate - .postForEntity(uri.toUriString(), httpEntity, Map.class); - if (response.getStatusCode() == HttpStatus.OK) { - logger.info("response : {}", response.getBody()); - return new ObjectMapper().readValue(new ObjectMapper().writeValueAsString(response.getBody()), - GoogleToken.class); - } - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - return null; - } + ResponseEntity response = restTemplate + .postForEntity(uri.toUriString(), httpEntity, Map.class); + if (response.getStatusCode() == HttpStatus.OK) { + logger.info("response : {}", response.getBody()); + return new ObjectMapper().readValue(new ObjectMapper().writeValueAsString(response.getBody()), + GoogleToken.class); + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return null; + } - @Override - public UserInfoDto requestUserInfo(String accessToken) throws JsonProcessingException { - MultiValueMap queryParams = new LinkedMultiValueMap<>(); - queryParams.add("access_token", accessToken); + @Override + public UserInfoDto requestUserInfo(String accessToken) throws JsonProcessingException { + MultiValueMap queryParams = new LinkedMultiValueMap<>(); + queryParams.add("access_token", accessToken); - UriComponents uri = UriComponentsBuilder.fromHttpUrl( - oauthConfig.getGetUserInfoUrlFromGoogle()) - .queryParams(queryParams) - .build(); + UriComponents uri = UriComponentsBuilder.fromHttpUrl( + oauthConfig.getGetUserInfoUrlFromGoogle()) + .queryParams(queryParams) + .build(); - ResponseEntity response = restTemplate.getForEntity(uri.toUriString(), JsonNode.class); + ResponseEntity response = restTemplate.getForEntity(uri.toUriString(), JsonNode.class); - if (response.getStatusCode() == HttpStatus.OK) { - logger.info("response : {}", response.getBody()); - JsonNode responseBody = response.getBody(); - if(responseBody != null) { - String id = responseBody.get("id").asText(); - String provider = String.valueOf(OAuthProvider.GOOGLE); - return new UserInfoDto(id, provider); - } - } - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - return null; - } + if (response.getStatusCode() == HttpStatus.OK) { + logger.info("response : {}", response.getBody()); + JsonNode responseBody = response.getBody(); + if (responseBody != null) { + String id = responseBody.get("id").asText(); + String provider = String.valueOf(OAuthProvider.GOOGLE); + return new UserInfoDto(id, provider); + } + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return null; + } } \ No newline at end of file From 82f71db6a84c2c76d9e6791e0098d1411fe69280 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 17:03:48 +0900 Subject: [PATCH 23/63] update: update login to ecr in staging.yml --- .github/workflows/Staging.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/Staging.yml b/.github/workflows/Staging.yml index 9fd2a1e..e450b91 100644 --- a/.github/workflows/Staging.yml +++ b/.github/workflows/Staging.yml @@ -50,9 +50,8 @@ jobs: - name: Login to Amazon ECR id: login-ecr - run: | - echo ${{ secrets.AWS_SECRET_ACCESS_KEY }} | docker login --username AWS --password-stdin ${{ secrets.AWS_ACCESS_KEY_ID }}.dkr.ecr.ap-northeast-2.amazonaws.com - + uses: aws-actions/amazon-ecr-login@v1 + - name: Build and tag Docker image run: | docker build -t ${{ secrets.ECR_REGISTRY }}/spring-app-image:latest . From a8d47f3261f75673a5dabba99378ce01210e9125 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 17:11:14 +0900 Subject: [PATCH 24/63] update : update ecr repository name --- .github/workflows/Staging.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/Staging.yml b/.github/workflows/Staging.yml index e450b91..51a29df 100644 --- a/.github/workflows/Staging.yml +++ b/.github/workflows/Staging.yml @@ -35,7 +35,7 @@ jobs: run: | cd ./src/main/resources touch ./application-dev.yml - echo "${{ secrets.YML_DEV }}" > ./application-dev.yml + echo "${{ secrets.YML_STAGING }}" > ./application-dev.yml shell: bash - name: Build Spring Boot application @@ -51,11 +51,11 @@ jobs: - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@v1 - + - name: Build and tag Docker image run: | - docker build -t ${{ secrets.ECR_REGISTRY }}/spring-app-image:latest . + docker build -t ${{ secrets.ECR_REGISTRY }}//dev:latest . - name: Push Docker image to ECR run: | - docker push ${{ secrets.ECR_REGISTRY }}/spring-app-image:latest + docker push ${{ secrets.ECR_REGISTRY }}//dev:latest From 2d66f0fd173632306799416427164305e13abe7f Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 17:14:33 +0900 Subject: [PATCH 25/63] =?UTF-8?q?fix=20:=20/=201=EA=B0=9C=20=EC=82=AD?= =?UTF-8?q?=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/Staging.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Staging.yml b/.github/workflows/Staging.yml index 51a29df..e79ba64 100644 --- a/.github/workflows/Staging.yml +++ b/.github/workflows/Staging.yml @@ -54,8 +54,8 @@ jobs: - name: Build and tag Docker image run: | - docker build -t ${{ secrets.ECR_REGISTRY }}//dev:latest . + docker build -t ${{ secrets.ECR_REGISTRY }}/dev:latest . - name: Push Docker image to ECR run: | - docker push ${{ secrets.ECR_REGISTRY }}//dev:latest + docker push ${{ secrets.ECR_REGISTRY }}/dev:latest From d7c0a005f8391a281c2d5de86e3ea5801312ad73 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 18:58:48 +0900 Subject: [PATCH 26/63] test : check yml file content --- .github/workflows/Staging.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/Staging.yml b/.github/workflows/Staging.yml index e79ba64..00ac8c9 100644 --- a/.github/workflows/Staging.yml +++ b/.github/workflows/Staging.yml @@ -36,6 +36,7 @@ jobs: cd ./src/main/resources touch ./application-dev.yml echo "${{ secrets.YML_STAGING }}" > ./application-dev.yml + cat ./application-dev.yml shell: bash - name: Build Spring Boot application From 75c0450a845e06e3594c441dc6919b30231383b0 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Sat, 5 Aug 2023 20:20:39 +0900 Subject: [PATCH 27/63] update : update rabbitmq host url --- .../com/kumofactory/cloud/global/config/RabbitMQConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java index 0c4c781..4de3a27 100644 --- a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java +++ b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java @@ -37,7 +37,7 @@ Binding binding(Queue queue, TopicExchange exchange) { @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory factory = new CachingConnectionFactory(); - factory.setHost("localhost"); + factory.setHost("rabbitmq"); factory.setUsername("guest"); factory.setPassword("guest"); return factory.getRabbitConnectionFactory(); From 3809d564e688aa7078351fd75f889a52a50bf1ad Mon Sep 17 00:00:00 2001 From: wook Date: Sun, 6 Aug 2023 18:08:37 +0900 Subject: [PATCH 28/63] update : add uuid in blueprint dto --- .../cloud/blueprint/BlueprintController.java | 45 +++--- .../blueprint/domain/aws/AwsBluePrint.java | 2 + .../blueprint/domain/aws/AwsComponent.java | 89 ++++++------ .../blueprint/dto/aws/AwsBluePrintDto.java | 40 +++--- .../dto/aws/AwsBluePrintListDto.java | 7 +- .../service/AwsBlueprintServiceImpl.java | 134 +++++++++--------- .../cloud/global/config/RabbitMQConfig.java | 78 +++++----- 7 files changed, 196 insertions(+), 199 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index f341bb5..980e262 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -16,30 +16,29 @@ @RequestMapping("/blueprint") @Slf4j public class BlueprintController { - private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); - private final AwsBlueprintService awsBlueprintService; - private final MessageProducer sender; + private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); + private final AwsBlueprintService awsBlueprintService; - @GetMapping("/aws/{id}") - @AuthorizationFromToken - public Object getAwsBlueprint(@PathVariable("id") Long id, String userId) { - logger.info("aws blue print id: {}", id); - AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); - return awsBlueprint; - } + @GetMapping("/aws/{id}") + @AuthorizationFromToken + public Object getAwsBlueprint(@PathVariable("id") Long id, String userId) { + logger.info("aws blue print id: {}", id); + AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); + return awsBlueprint; + } - @GetMapping("/aws/list") - @AuthorizationFromToken - public Object getAwsBlueprintList(String userId) { - logger.info("userId: {}", userId); - return awsBlueprintService.getMyAwsBlueprints(userId); - } + @GetMapping("/aws/list") + @AuthorizationFromToken + public Object getAwsBlueprintList(String userId) { + logger.info("userId: {}", userId); + return awsBlueprintService.getMyAwsBlueprints(userId); + } - @PostMapping("/aws") - @AuthorizationFromToken - public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException { - logger.info(userId); - awsBlueprintService.store(awsBluePrintDto, userId); - return "hello-world"; - } + @PostMapping("/aws") + @AuthorizationFromToken + public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException { + logger.info(userId); + awsBlueprintService.store(awsBluePrintDto, userId); + return "hello-world"; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java index d520931..a7f746d 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java @@ -34,6 +34,8 @@ public class AwsBluePrint { private Date created_at; @UpdateTimestamp private Date updated_at; + + private String uuid; // Client 에서 생성하는 uuid private String name; // 블루프린트 이름 diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java index 2ca2ff6..8bea9c7 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java @@ -1,15 +1,8 @@ package com.kumofactory.cloud.blueprint.domain.aws; -import com.fasterxml.jackson.annotation.JsonSubTypes; import com.kumofactory.cloud.blueprint.dto.aws.AccessScope; import com.kumofactory.cloud.blueprint.dto.aws.AvailabilityZone; import com.kumofactory.cloud.blueprint.dto.aws.AwsComponentDto; - -import java.util.Date; -import java.util.List; -import java.util.Map; -import javax.persistence.*; - import io.hypersistence.utils.hibernate.type.json.JsonType; import lombok.AllArgsConstructor; import lombok.Getter; @@ -20,6 +13,10 @@ import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.UpdateTimestamp; +import javax.persistence.*; +import java.util.Date; +import java.util.Map; + import static javax.persistence.EnumType.STRING; @Entity @@ -27,56 +24,52 @@ @Setter @NoArgsConstructor @AllArgsConstructor -@TypeDef( - name = "json", - typeClass = JsonType.class -) +@TypeDef(name = "json", typeClass = JsonType.class) public class AwsComponent { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @CreationTimestamp - private Date created_at; - @UpdateTimestamp - private Date updated_at; + @CreationTimestamp + private Date created_at; + @UpdateTimestamp + private Date updated_at; - @Column(unique = true) - private String ui_id; // Client 에서 생성하는 uuid + @Column(unique = true) + private String ui_id; // Client 에서 생성하는 uuid - @Enumerated(STRING) - private AwsComponentType type; // Component 타입 (vm, vpc, subnet, ...) + @Enumerated(STRING) + private AwsComponentType type; // Component 타입 (vm, vpc, subnet, ...) - @Enumerated(STRING) - private AccessScope scope; + @Enumerated(STRING) + private AccessScope scope; - @Enumerated(STRING) - private AvailabilityZone az; + @Enumerated(STRING) + private AvailabilityZone az; - @Type(type = "json") - @Column(columnDefinition = "json") - private Map options; + @Type(type = "json") + @Column(columnDefinition = "json") + private Map options; - // Component 의 좌측 상단 좌표 - private Integer position_x; - private Integer position_y; + // Component 의 좌측 상단 좌표 + private Integer position_x; + private Integer position_y; - @ManyToOne - private AwsBluePrint bluePrint; + @ManyToOne + private AwsBluePrint bluePrint; - // ============== 생성함수 ================= // - public static AwsComponent createAwsComponent(AwsComponentDto awsComponentDto, - AwsBluePrint awsBluePrint) { - AwsComponent awsComponent = new AwsComponent(); - awsComponent.setUi_id(awsComponentDto.getId()); - awsComponent.setPosition_x(awsComponentDto.getX()); - awsComponent.setPosition_y(awsComponentDto.getY()); - awsComponent.setType(awsComponentDto.getType()); - awsComponent.setAz(awsComponentDto.getAz()); - awsComponent.setScope(awsComponentDto.getScope()); - awsComponent.setOptions(awsComponentDto.getOptions()); - awsComponent.setBluePrint(awsBluePrint); - return awsComponent; - } + // ============== 생성함수 ================= // + public static AwsComponent createAwsComponent(AwsComponentDto awsComponentDto, AwsBluePrint awsBluePrint) { + AwsComponent awsComponent = new AwsComponent(); + awsComponent.setUi_id(awsComponentDto.getId()); + awsComponent.setPosition_x(awsComponentDto.getX()); + awsComponent.setPosition_y(awsComponentDto.getY()); + awsComponent.setType(awsComponentDto.getType()); + awsComponent.setAz(awsComponentDto.getAz()); + awsComponent.setScope(awsComponentDto.getScope()); + awsComponent.setOptions(awsComponentDto.getOptions()); + awsComponent.setBluePrint(awsBluePrint); + return awsComponent; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index eb73f6d..cdf25ac 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -12,24 +12,24 @@ @Data public class AwsBluePrintDto { - - private String name; - private List components; - private List links; - - public static List awsComponentDtosMapper(List awsComponentDtos) { - List awsComponentDtoList = new ArrayList<>(); - for (AwsComponent awsComponent : awsComponentDtos) { - awsComponentDtoList.add(AwsComponentDto.mapper(awsComponent)); - } - return awsComponentDtoList; - } - - public static List componentLinkDtoListMapper(List componentLinks) { - List componentLinkDtoList = new ArrayList<>(); - for (ComponentLine pointLink : componentLinks) { - componentLinkDtoList.add(ComponentLineDto.mapper(pointLink)); - } - return componentLinkDtoList; - } + private String uuid; + private String name; + private List components; + private List links; + + public static List awsComponentDtosMapper(List awsComponentDtos) { + List awsComponentDtoList = new ArrayList<>(); + for (AwsComponent awsComponent : awsComponentDtos) { + awsComponentDtoList.add(AwsComponentDto.mapper(awsComponent)); + } + return awsComponentDtoList; + } + + public static List componentLinkDtoListMapper(List componentLinks) { + List componentLinkDtoList = new ArrayList<>(); + for (ComponentLine pointLink : componentLinks) { + componentLinkDtoList.add(ComponentLineDto.mapper(pointLink)); + } + return componentLinkDtoList; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java index 99bec33..0d88072 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java @@ -8,7 +8,8 @@ @Getter @Setter public class AwsBluePrintListDto { - private Long id; - private String name; - private Date createdAt; + private Long id; + private String uuid; + private String name; + private Date createdAt; } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index e67b6a9..d49a6c2 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -33,80 +33,82 @@ @Repository public class AwsBlueprintServiceImpl implements AwsBlueprintService { - private final MemberRepository memberRepository; - private final AwsBluePrintRepository awsBluePrintRepository; - private final AwsComponentRepository awsComponentRepository; - private final ComponentLineRepository componentLineRepository; - private final MessageProducer sender; - private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); + private final MemberRepository memberRepository; + private final AwsBluePrintRepository awsBluePrintRepository; + private final AwsComponentRepository awsComponentRepository; + private final ComponentLineRepository componentLineRepository; + private final MessageProducer sender; + private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); - @Override - public AwsBluePrintDto getAwsBlueprint(Long bluePrintId) { - AwsBluePrint awsBluePrintById = awsBluePrintRepository.findAwsBluePrintById(bluePrintId); - if (awsBluePrintById == null) { - throw new RuntimeException("awsBluePrintById is null"); - } + @Override + public AwsBluePrintDto getAwsBlueprint(Long bluePrintId) { + AwsBluePrint awsBluePrintById = awsBluePrintRepository.findAwsBluePrintById(bluePrintId); + if (awsBluePrintById == null) { + throw new RuntimeException("awsBluePrintById is null"); + } - List awsComponents = awsComponentRepository.findAllByBluePrint(awsBluePrintById); - List componentLines = componentLineRepository.findAllByBluePrint(awsBluePrintById); - AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); - awsBluePrintDto.setName(awsBluePrintById.getName()); - awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); - awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); - return awsBluePrintDto; - } + List awsComponents = awsComponentRepository.findAllByBluePrint(awsBluePrintById); + List componentLines = componentLineRepository.findAllByBluePrint(awsBluePrintById); + AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); + awsBluePrintDto.setName(awsBluePrintById.getName()); + awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); + awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); + return awsBluePrintDto; + } - @Override - public List getMyAwsBlueprints(String oauthId) { - Member member = memberRepository.findMemberByOauthId(oauthId); - if (member == null) { - throw new RuntimeException("member is null"); - } + @Override + public List getMyAwsBlueprints(String oauthId) { + Member member = memberRepository.findMemberByOauthId(oauthId); + if (member == null) { + throw new RuntimeException("member is null"); + } - List awsBluePrints = awsBluePrintRepository.findAwsBluePrintsByMember(member); - List awsBluePrintDtos = new ArrayList<>(); - for (AwsBluePrint awsBluePrint : awsBluePrints) { - AwsBluePrintListDto dto = new AwsBluePrintListDto(); - dto.setName(awsBluePrint.getName()); - dto.setId(awsBluePrint.getId()); - dto.setCreatedAt(awsBluePrint.getCreated_at()); - awsBluePrintDtos.add(dto); - } - return awsBluePrintDtos; - } + List awsBluePrints = awsBluePrintRepository.findAwsBluePrintsByMember(member); + List awsBluePrintDtos = new ArrayList<>(); + for (AwsBluePrint awsBluePrint : awsBluePrints) { + AwsBluePrintListDto dto = new AwsBluePrintListDto(); + dto.setName(awsBluePrint.getName()); + dto.setUuid(awsBluePrint.getUuid()); + dto.setId(awsBluePrint.getId()); + dto.setCreatedAt(awsBluePrint.getCreated_at()); + awsBluePrintDtos.add(dto); + } + return awsBluePrintDtos; + } - @Override - public void store(AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException { - Member member = memberRepository.findMemberByOauthId(userId); - // BluePrint 저장 - AwsBluePrint awsBluePrint = new AwsBluePrint(); - awsBluePrint.setName(awsBluePrintDto.getName()); - awsBluePrint.setMember(member); - AwsBluePrint savedBlueprint = awsBluePrintRepository.save(awsBluePrint); - logger.info("savedBlueprint: {}", savedBlueprint); + @Override + public void store(AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException { + Member member = memberRepository.findMemberByOauthId(userId); + // BluePrint 저장 + AwsBluePrint awsBluePrint = new AwsBluePrint(); + awsBluePrint.setUuid(awsBluePrintDto.getUuid()); + awsBluePrint.setName(awsBluePrintDto.getName()); + awsBluePrint.setMember(member); + AwsBluePrint savedBlueprint = awsBluePrintRepository.save(awsBluePrint); + logger.info("savedBlueprint: {}", savedBlueprint); - List components = new ArrayList<>(); - List links = awsBluePrintDto.getLinks(); - List awsCdkDtos = new ArrayList<>(); + List components = new ArrayList<>(); + List links = awsBluePrintDto.getLinks(); + List awsCdkDtos = new ArrayList<>(); - // Components 저장 - for (AwsComponentDto component : awsBluePrintDto.getComponents()) { - AwsComponent awsComponent = AwsComponent.createAwsComponent(component, savedBlueprint); - AwsCdkDto awsCdkDto = AwsCdkDto.createAwsCdkDto(component); - components.add(awsComponent); - awsCdkDtos.add(awsCdkDto); - } -// awsComponentRepository.saveAll(components); + // Components 저장 + for (AwsComponentDto component : awsBluePrintDto.getComponents()) { + AwsComponent awsComponent = AwsComponent.createAwsComponent(component, savedBlueprint); + AwsCdkDto awsCdkDto = AwsCdkDto.createAwsCdkDto(component); + components.add(awsComponent); + awsCdkDtos.add(awsCdkDto); + } + awsComponentRepository.saveAll(components); - // Lines 저장 - List componentLines = new ArrayList<>(); - for (ComponentLineDto link : links) { - ComponentLine componentLink = ComponentLine.createComponentLink(link, savedBlueprint); - componentLines.add(componentLink); - } -// componentLineRepository.saveAll(componentLines); + // Lines 저장 + List componentLines = new ArrayList<>(); + for (ComponentLineDto link : links) { + ComponentLine componentLink = ComponentLine.createComponentLink(link, savedBlueprint); + componentLines.add(componentLink); + } + componentLineRepository.saveAll(componentLines); - sender.sendAwsCdkOption(awsCdkDtos); - } + sender.sendAwsCdkOption(awsCdkDtos); + } } diff --git a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java index 4de3a27..7fb0b1e 100644 --- a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java +++ b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java @@ -11,43 +11,43 @@ @Configuration public class RabbitMQConfig { - public static final String topicExchangeName = "aws.cdk"; - private final String queueName = "kumofactory-queue"; - - @Bean - public Queue queue() { - return new Queue(queueName, false); - } - - @Bean - DirectExchange exchange() { - return new DirectExchange("direct"); - } - - @Bean - TopicExchange exchange2() { - return new TopicExchange(topicExchangeName); - } - - @Bean - Binding binding(Queue queue, TopicExchange exchange) { - return BindingBuilder.bind(queue).to(exchange).with("foo.bar"); - } - - @Bean - public ConnectionFactory connectionFactory() { - CachingConnectionFactory factory = new CachingConnectionFactory(); - factory.setHost("rabbitmq"); - factory.setUsername("guest"); - factory.setPassword("guest"); - return factory.getRabbitConnectionFactory(); - } - - @Bean - public AmqpTemplate rabbitTemplate() { - RabbitTemplate template = new RabbitTemplate((org.springframework.amqp.rabbit.connection.ConnectionFactory) connectionFactory()); - template.setRoutingKey(queueName); - template.setMessageConverter(new Jackson2JsonMessageConverter()); - return template; - } + public static final String topicExchangeName = "aws.cdk"; + private final String queueName = "kumofactory-queue"; + + @Bean + public Queue queue() { + return new Queue(queueName, false); + } + + @Bean + DirectExchange exchange() { + return new DirectExchange("direct"); + } + + @Bean + TopicExchange exchange2() { + return new TopicExchange(topicExchangeName); + } + + @Bean + Binding binding(Queue queue, TopicExchange exchange) { + return BindingBuilder.bind(queue).to(exchange).with("foo.bar"); + } + + @Bean + public ConnectionFactory connectionFactory() { + CachingConnectionFactory factory = new CachingConnectionFactory(); + factory.setHost("localhost"); + factory.setUsername("guest"); + factory.setPassword("guest"); + return factory.getRabbitConnectionFactory(); + } + + @Bean + public AmqpTemplate rabbitTemplate() { + RabbitTemplate template = new RabbitTemplate((org.springframework.amqp.rabbit.connection.ConnectionFactory) connectionFactory()); + template.setRoutingKey(queueName); + template.setMessageConverter(new Jackson2JsonMessageConverter()); + return template; + } } From f4200a14db83304557d526c1df7a3e17369f12d2 Mon Sep 17 00:00:00 2001 From: wook Date: Sun, 6 Aug 2023 18:12:23 +0900 Subject: [PATCH 29/63] update : add az in AwsCdkDto --- .../cloud/blueprint/dto/aws/AwsCdkDto.java | 26 ++++----- .../blueprint/dto/aws/AwsComponentDto.java | 54 +++++++++---------- 2 files changed, 39 insertions(+), 41 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java index d9cf59d..aff7164 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java @@ -10,17 +10,19 @@ @Getter @Setter public class AwsCdkDto { - String id; - AwsComponentType type; - AccessScope scope; - Map options; + String id; + AwsComponentType type; + AccessScope scope; + AvailabilityZone az; + Map options; - public static AwsCdkDto createAwsCdkDto(AwsComponentDto awsComponentDto) { - AwsCdkDto awsCdkDto = new AwsCdkDto(); - awsCdkDto.setId(UUID.randomUUID().toString()); - awsCdkDto.setType(awsComponentDto.getType()); - awsCdkDto.setScope(awsComponentDto.getScope()); - awsCdkDto.setOptions(awsComponentDto.getOptions()); - return awsCdkDto; - } + public static AwsCdkDto createAwsCdkDto(AwsComponentDto awsComponentDto) { + AwsCdkDto awsCdkDto = new AwsCdkDto(); + awsCdkDto.setId(UUID.randomUUID().toString()); + awsCdkDto.setAz(awsComponentDto.getAz()); + awsCdkDto.setType(awsComponentDto.getType()); + awsCdkDto.setScope(awsComponentDto.getScope()); + awsCdkDto.setOptions(awsComponentDto.getOptions()); + return awsCdkDto; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java index be2b17d..929d1b9 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java @@ -2,15 +2,11 @@ import com.kumofactory.cloud.blueprint.domain.aws.AwsComponent; import com.kumofactory.cloud.blueprint.domain.aws.AwsComponentType; - -import javax.persistence.Enumerated; -import javax.validation.constraints.NotNull; - import com.kumofactory.cloud.global.annotation.validation.EnumValidator; import lombok.Getter; import lombok.Setter; -import org.springframework.validation.annotation.Validated; +import javax.validation.constraints.NotNull; import java.util.Map; // todo : Area Component Dto 추가 @@ -18,35 +14,35 @@ @Setter public class AwsComponentDto { - @NotNull - private String id; + @NotNull + private String id; - @NotNull - private Integer x; + @NotNull + private Integer x; - @NotNull - private Integer y; + @NotNull + private Integer y; - @NotNull - private AwsComponentType type; + @NotNull + private AwsComponentType type; - @EnumValidator(enumClass = AwsComponentType.class) - private AccessScope scope; + @EnumValidator(enumClass = AwsComponentType.class) + private AccessScope scope; - @EnumValidator(enumClass = AvailabilityZone.class) - private AvailabilityZone az; + @EnumValidator(enumClass = AvailabilityZone.class) + private AvailabilityZone az; - private Map options; + private Map options; - public static AwsComponentDto mapper(AwsComponent awsComponent) { - AwsComponentDto awsComponentDto = new AwsComponentDto(); - awsComponentDto.setId(awsComponent.getUi_id()); - awsComponentDto.setX(awsComponent.getPosition_x()); - awsComponentDto.setY(awsComponent.getPosition_y()); - awsComponentDto.setType(awsComponent.getType()); - awsComponentDto.setAz(awsComponent.getAz()); - awsComponentDto.setScope(awsComponent.getScope()); - awsComponentDto.setOptions(awsComponent.getOptions()); - return awsComponentDto; - } + public static AwsComponentDto mapper(AwsComponent awsComponent) { + AwsComponentDto awsComponentDto = new AwsComponentDto(); + awsComponentDto.setId(awsComponent.getUi_id()); + awsComponentDto.setX(awsComponent.getPosition_x()); + awsComponentDto.setY(awsComponent.getPosition_y()); + awsComponentDto.setType(awsComponent.getType()); + awsComponentDto.setAz(awsComponent.getAz()); + awsComponentDto.setScope(awsComponent.getScope()); + awsComponentDto.setOptions(awsComponent.getOptions()); + return awsComponentDto; + } } From 54a14615cb8e53c5af0f49ac6c9ac5b12b42d576 Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Mon, 7 Aug 2023 10:33:43 +0900 Subject: [PATCH 30/63] update : update awscomponentype --- .../cloud/blueprint/domain/aws/AwsComponentType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java index 51499cc..51b1ad3 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java @@ -1,5 +1,5 @@ package com.kumofactory.cloud.blueprint.domain.aws; public enum AwsComponentType { - VPC, SUBNET, ELB, EC2, EFS, WAF, ROUTE53, NAT_GATEWAY, RDS, S3, ElastiCache, CloudFront, AutoScaling + VPC, SUBNET, ALB, NLB, EC2, EFS, WAF, ROUTE53, NAT_GATEWAY, RDS, S3, ELASTIC_CACHE, CLOUDFRONT, AUTO_SCALING } From 256b5d28c1557990002cf723380eba20a23766c9 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Mon, 7 Aug 2023 12:07:19 +0900 Subject: [PATCH 31/63] fix: typo #16 --- .../kumofactory/cloud/appDeploy/dto/BuildRequestDto.java | 8 ++++---- .../cloud/appDeploy/service/BuildRequestService.java | 4 +++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java b/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java index 3908907..81b8b46 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/dto/BuildRequestDto.java @@ -10,7 +10,7 @@ public record BuildRequestDto( @JsonProperty("user") String user, // required @JsonProperty("repo") String repo, // required @JsonProperty("branch") String branch, // required - @JsonProperty("Dockerfile") Boolean dockerfile, + @JsonProperty("Dockerfile") Boolean Dockerfile, @JsonProperty("language") String language, // required @JsonProperty("env") List env) // required { @@ -19,11 +19,11 @@ public record EnvInfoDTO( @JsonProperty("value") String value ) { } - public BuildRequestDto setDockerfile(Boolean dockerfile) { - return new BuildRequestDto(instanceId, gitHubToken, user, repo, branch, dockerfile, language, env); + public BuildRequestDto setDockerfile(Boolean Dockerfile) { + return new BuildRequestDto(instanceId, gitHubToken, user, repo, branch, Dockerfile, language, env); } public BuildRequestDto setgithubToken(String gitHubToken) { - return new BuildRequestDto(instanceId, gitHubToken, user, repo, branch, dockerfile, language, env); + return new BuildRequestDto(instanceId, gitHubToken, user, repo, branch, Dockerfile, language, env); } } diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java index 3d16d90..fa87bce 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java @@ -22,13 +22,15 @@ public class BuildRequestService { private String token = null; private String baseUri = "https://api.github.com"; @Value("${build.server}") - private String buildServerUri; + private String buildServerUri = "http://3.38.34.254:8080"; public void RequestBuild(BuildRequestDto request) { String url = buildServerUri + "/api/v1/deploy"; request.setDockerfile(isDockerfileExist(request.user(), request.repo())); request.setgithubToken(token); + logger.info(request.toString()); + HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); HttpEntity httpEntity = new HttpEntity<>(request, headers); From 3af28504b963f18a87dd5864435d1e15b163557a Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Mon, 7 Aug 2023 12:13:43 +0900 Subject: [PATCH 32/63] af --- .../blueprint/domain/aws/AwsComponent.java | 74 +++++++++---------- .../cloud/blueprint/dto/aws/AwsCdkDto.java | 26 +++---- .../blueprint/dto/aws/AwsComponentDto.java | 44 +++++------ 3 files changed, 62 insertions(+), 82 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java index 8bea9c7..a019d69 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java @@ -27,49 +27,41 @@ @TypeDef(name = "json", typeClass = JsonType.class) public class AwsComponent { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @CreationTimestamp + private Date created_at; + @UpdateTimestamp + private Date updated_at; + + @Column(unique = true) + private String ui_id; // Client 에서 생성하는 uuid - @CreationTimestamp - private Date created_at; - @UpdateTimestamp - private Date updated_at; + @Enumerated(STRING) + private AwsComponentType type; // Component 타입 (vm, vpc, subnet, ...) + + @Type(type = "json") + @Column(columnDefinition = "json") + private Map options; - @Column(unique = true) - private String ui_id; // Client 에서 생성하는 uuid + // Component 의 좌측 상단 좌표 + private Integer position_x; + private Integer position_y; - @Enumerated(STRING) - private AwsComponentType type; // Component 타입 (vm, vpc, subnet, ...) + @ManyToOne + private AwsBluePrint bluePrint; - @Enumerated(STRING) - private AccessScope scope; - - @Enumerated(STRING) - private AvailabilityZone az; - - @Type(type = "json") - @Column(columnDefinition = "json") - private Map options; - - // Component 의 좌측 상단 좌표 - private Integer position_x; - private Integer position_y; - - @ManyToOne - private AwsBluePrint bluePrint; - - // ============== 생성함수 ================= // - public static AwsComponent createAwsComponent(AwsComponentDto awsComponentDto, AwsBluePrint awsBluePrint) { - AwsComponent awsComponent = new AwsComponent(); - awsComponent.setUi_id(awsComponentDto.getId()); - awsComponent.setPosition_x(awsComponentDto.getX()); - awsComponent.setPosition_y(awsComponentDto.getY()); - awsComponent.setType(awsComponentDto.getType()); - awsComponent.setAz(awsComponentDto.getAz()); - awsComponent.setScope(awsComponentDto.getScope()); - awsComponent.setOptions(awsComponentDto.getOptions()); - awsComponent.setBluePrint(awsBluePrint); - return awsComponent; - } + // ============== 생성함수 ================= // + public static AwsComponent createAwsComponent(AwsComponentDto awsComponentDto, AwsBluePrint awsBluePrint) { + AwsComponent awsComponent = new AwsComponent(); + awsComponent.setUi_id(awsComponentDto.getId()); + awsComponent.setPosition_x(awsComponentDto.getX()); + awsComponent.setPosition_y(awsComponentDto.getY()); + awsComponent.setType(awsComponentDto.getType()); + awsComponent.setOptions(awsComponentDto.getOptions()); + awsComponent.setBluePrint(awsBluePrint); + return awsComponent; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java index aff7164..dbeb254 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsCdkDto.java @@ -10,19 +10,15 @@ @Getter @Setter public class AwsCdkDto { - String id; - AwsComponentType type; - AccessScope scope; - AvailabilityZone az; - Map options; - - public static AwsCdkDto createAwsCdkDto(AwsComponentDto awsComponentDto) { - AwsCdkDto awsCdkDto = new AwsCdkDto(); - awsCdkDto.setId(UUID.randomUUID().toString()); - awsCdkDto.setAz(awsComponentDto.getAz()); - awsCdkDto.setType(awsComponentDto.getType()); - awsCdkDto.setScope(awsComponentDto.getScope()); - awsCdkDto.setOptions(awsComponentDto.getOptions()); - return awsCdkDto; - } + String id; + AwsComponentType type; + Map options; + + public static AwsCdkDto createAwsCdkDto(AwsComponentDto awsComponentDto) { + AwsCdkDto awsCdkDto = new AwsCdkDto(); + awsCdkDto.setId(awsComponentDto.getId()); + awsCdkDto.setType(awsComponentDto.getType()); + awsCdkDto.setOptions(awsComponentDto.getOptions()); + return awsCdkDto; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java index 929d1b9..431e20b 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsComponentDto.java @@ -14,35 +14,27 @@ @Setter public class AwsComponentDto { - @NotNull - private String id; + @NotNull + private String id; - @NotNull - private Integer x; + @NotNull + private Integer x; - @NotNull - private Integer y; + @NotNull + private Integer y; - @NotNull - private AwsComponentType type; + @NotNull + private AwsComponentType type; - @EnumValidator(enumClass = AwsComponentType.class) - private AccessScope scope; + private Map options; - @EnumValidator(enumClass = AvailabilityZone.class) - private AvailabilityZone az; - - private Map options; - - public static AwsComponentDto mapper(AwsComponent awsComponent) { - AwsComponentDto awsComponentDto = new AwsComponentDto(); - awsComponentDto.setId(awsComponent.getUi_id()); - awsComponentDto.setX(awsComponent.getPosition_x()); - awsComponentDto.setY(awsComponent.getPosition_y()); - awsComponentDto.setType(awsComponent.getType()); - awsComponentDto.setAz(awsComponent.getAz()); - awsComponentDto.setScope(awsComponent.getScope()); - awsComponentDto.setOptions(awsComponent.getOptions()); - return awsComponentDto; - } + public static AwsComponentDto mapper(AwsComponent awsComponent) { + AwsComponentDto awsComponentDto = new AwsComponentDto(); + awsComponentDto.setId(awsComponent.getUi_id()); + awsComponentDto.setX(awsComponent.getPosition_x()); + awsComponentDto.setY(awsComponent.getPosition_y()); + awsComponentDto.setType(awsComponent.getType()); + awsComponentDto.setOptions(awsComponent.getOptions()); + return awsComponentDto; + } } From d654701eb1060a0aa63baf7b6166b4f4c75675ca Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 7 Aug 2023 16:09:41 +0900 Subject: [PATCH 33/63] feat : add enum type ProvisionStatus --- .../cloud/blueprint/domain/ProvisionStatus.java | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/domain/ProvisionStatus.java diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/ProvisionStatus.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/ProvisionStatus.java new file mode 100644 index 0000000..3f1d781 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/ProvisionStatus.java @@ -0,0 +1,8 @@ +package com.kumofactory.cloud.blueprint.domain; + +public enum ProvisionStatus { + PENDING, // 아키텍처 다이어그램만 저장 + PROVISIONING, // 아키텍처 배포 중 + SUCCESS, // 배포 성공 + FAIL // 배포 실패 +} From 3610ffc0cab9e68d0885f8359d1be48b79cf7b64 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 7 Aug 2023 16:10:39 +0900 Subject: [PATCH 34/63] feat : select blueprint by uuid, store provision status --- .../cloud/blueprint/BlueprintController.java | 12 ++--- .../blueprint/domain/aws/AwsBluePrint.java | 14 ++--- .../aws/AwsBluePrintRepository.java | 9 ++-- .../service/AwsBlueprintService.java | 6 +-- .../service/AwsBlueprintServiceImpl.java | 51 +++++++++++++------ 5 files changed, 54 insertions(+), 38 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index 980e262..1a12d40 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -19,12 +19,10 @@ public class BlueprintController { private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); private final AwsBlueprintService awsBlueprintService; - @GetMapping("/aws/{id}") + @GetMapping("/aws/{uuid}") @AuthorizationFromToken - public Object getAwsBlueprint(@PathVariable("id") Long id, String userId) { - logger.info("aws blue print id: {}", id); - AwsBluePrintDto awsBlueprint = awsBlueprintService.getAwsBlueprint(id); - return awsBlueprint; + public Object getAwsBlueprint(@PathVariable("uuid") String uuid, String userId) { + return awsBlueprintService.getAwsBlueprint(uuid); } @GetMapping("/aws/list") @@ -36,9 +34,9 @@ public Object getAwsBlueprintList(String userId) { @PostMapping("/aws") @AuthorizationFromToken - public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException { + public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, @RequestParam String provision, String userId) throws JsonProcessingException { logger.info(userId); - awsBlueprintService.store(awsBluePrintDto, userId); + awsBlueprintService.store(awsBluePrintDto, provision, userId); return "hello-world"; } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java index a7f746d..2cc8457 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java @@ -1,18 +1,12 @@ package com.kumofactory.cloud.blueprint.domain.aws; import com.kumofactory.cloud.blueprint.domain.ComponentLine; +import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; import com.kumofactory.cloud.member.domain.Member; import java.util.Date; import java.util.List; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; +import javax.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; @@ -34,10 +28,12 @@ public class AwsBluePrint { private Date created_at; @UpdateTimestamp private Date updated_at; - + private String uuid; // Client 에서 생성하는 uuid private String name; // 블루프린트 이름 + @Enumerated(EnumType.STRING) + private ProvisionStatus status; // 배포 상태 @ManyToOne private Member member; diff --git a/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java b/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java index c8ddacf..1868f78 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java @@ -9,9 +9,12 @@ @Repository public interface AwsBluePrintRepository extends JpaRepository { - AwsBluePrint findAwsBluePrintById(long id); + AwsBluePrint findAwsBluePrintById(long id); - AwsBluePrint findAwsBluePrintByMemberId(long memberId); + AwsBluePrint findAwsBluePrintByUuid(String uuid); + + AwsBluePrint findAwsBluePrintByMemberId(long memberId); + + List findAwsBluePrintsByMember(Member member); - List findAwsBluePrintsByMember(Member member); } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java index af1eb98..d780b4c 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java @@ -10,9 +10,9 @@ public interface AwsBlueprintService { - AwsBluePrintDto getAwsBlueprint(Long bluePrintId); + AwsBluePrintDto getAwsBlueprint(String uuid); - List getMyAwsBlueprints(String userId); + List getMyAwsBlueprints(String userId); - void store(AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException; + void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException; } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index d49a6c2..ab186ac 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.kumofactory.cloud.blueprint.domain.ComponentLine; +import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.domain.aws.AwsComponent; import com.kumofactory.cloud.blueprint.dto.ComponentLineDto; @@ -27,6 +28,8 @@ import java.util.ArrayList; import java.util.List; +import static java.lang.Boolean.parseBoolean; + @Service @RequiredArgsConstructor @Slf4j @@ -42,8 +45,8 @@ public class AwsBlueprintServiceImpl implements AwsBlueprintService { @Override - public AwsBluePrintDto getAwsBlueprint(Long bluePrintId) { - AwsBluePrint awsBluePrintById = awsBluePrintRepository.findAwsBluePrintById(bluePrintId); + public AwsBluePrintDto getAwsBlueprint(String uuid) { + AwsBluePrint awsBluePrintById = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); if (awsBluePrintById == null) { throw new RuntimeException("awsBluePrintById is null"); } @@ -78,18 +81,11 @@ public List getMyAwsBlueprints(String oauthId) { } @Override - public void store(AwsBluePrintDto awsBluePrintDto, String userId) throws JsonProcessingException { - Member member = memberRepository.findMemberByOauthId(userId); - // BluePrint 저장 - AwsBluePrint awsBluePrint = new AwsBluePrint(); - awsBluePrint.setUuid(awsBluePrintDto.getUuid()); - awsBluePrint.setName(awsBluePrintDto.getName()); - awsBluePrint.setMember(member); - AwsBluePrint savedBlueprint = awsBluePrintRepository.save(awsBluePrint); - logger.info("savedBlueprint: {}", savedBlueprint); + public void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException { + AwsBluePrint savedBlueprint = saveBlueprint(awsBluePrintDto, provision, userId); // BluePrint 저장 + saveComponentLines(savedBlueprint, awsBluePrintDto.getLinks()); // ComponentLine 저장 List components = new ArrayList<>(); - List links = awsBluePrintDto.getLinks(); List awsCdkDtos = new ArrayList<>(); // Components 저장 @@ -101,14 +97,37 @@ public void store(AwsBluePrintDto awsBluePrintDto, String userId) throws JsonPro } awsComponentRepository.saveAll(components); - // Lines 저장 + if (parseBoolean(provision)) { + sender.sendAwsCdkOption(awsCdkDtos); + } + } + + // Blueprint 저장 + private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provision, String userId) { + Member member = memberRepository.findMemberByOauthId(userId); + ProvisionStatus status; + if (parseBoolean(provision)) { + status = ProvisionStatus.PROVISIONING; + } else { + status = ProvisionStatus.PENDING; + } + // BluePrint 저장 + AwsBluePrint awsBluePrint = new AwsBluePrint(); + awsBluePrint.setUuid(awsBluePrintDto.getUuid()); + awsBluePrint.setName(awsBluePrintDto.getName()); + awsBluePrint.setStatus(status); + awsBluePrint.setMember(member); + return awsBluePrintRepository.save(awsBluePrint); + } + + // ComponentLine 저장 + private void saveComponentLines(AwsBluePrint blueprint, List lines) { List componentLines = new ArrayList<>(); - for (ComponentLineDto link : links) { - ComponentLine componentLink = ComponentLine.createComponentLink(link, savedBlueprint); + for (ComponentLineDto link : lines) { + ComponentLine componentLink = ComponentLine.createComponentLink(link, blueprint); componentLines.add(componentLink); } componentLineRepository.saveAll(componentLines); - sender.sendAwsCdkOption(awsCdkDtos); } } From 6df2f586fad037e6852a0b3072d96568ef611ba5 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 7 Aug 2023 16:11:00 +0900 Subject: [PATCH 35/63] update : update AwsComponentType --- .../cloud/blueprint/domain/aws/AwsComponentType.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java index 51b1ad3..a84a3c7 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java @@ -1,5 +1,5 @@ package com.kumofactory.cloud.blueprint.domain.aws; public enum AwsComponentType { - VPC, SUBNET, ALB, NLB, EC2, EFS, WAF, ROUTE53, NAT_GATEWAY, RDS, S3, ELASTIC_CACHE, CLOUDFRONT, AUTO_SCALING -} + VPC, SUBNET, ALB, NLB, EC2, EFS, WAF, ROUTE53, NAT_GATEWAY, RDS, S3, ELASTIC_CACHE, CLOUDFRONT, AUTO_SCALING +} \ No newline at end of file From 40eed4f6e33f417688038854c878b51c9c6ffd62 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 7 Aug 2023 16:32:33 +0900 Subject: [PATCH 36/63] chore : add swagger-ui --- build.gradle | 1 + .../cloud/global/config/SwaggerConfig.java | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 src/main/java/com/kumofactory/cloud/global/config/SwaggerConfig.java diff --git a/build.gradle b/build.gradle index e2457ae..458a9ac 100644 --- a/build.gradle +++ b/build.gradle @@ -36,6 +36,7 @@ dependencies { implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2' implementation "io.hypersistence:hypersistence-utils-hibernate-55:3.5.0" + implementation 'org.springdoc:springdoc-openapi-ui:1.6.9' // dependency of rabbitmq diff --git a/src/main/java/com/kumofactory/cloud/global/config/SwaggerConfig.java b/src/main/java/com/kumofactory/cloud/global/config/SwaggerConfig.java new file mode 100644 index 0000000..26183d5 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/config/SwaggerConfig.java @@ -0,0 +1,26 @@ +package com.kumofactory.cloud.global.config; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springdoc.core.GroupedOpenApi; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SwaggerConfig { + @Bean + public GroupedOpenApi publicApi() { + return GroupedOpenApi.builder() + .group("v1-definition") + .pathsToMatch("/**") + .build(); + } + + @Bean + public OpenAPI springShopOpenAPI() { + return new OpenAPI() + .info(new Info().title("Bstagram API") + .description("Kumofactory API 명세") + .version("v0.0.1")); + } +} From 8defe75f7be8bdeffb205432fb7c846ffd693ca5 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 7 Aug 2023 16:44:03 +0900 Subject: [PATCH 37/63] feat : select blueprint by uuid and add status --- .../kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java | 2 ++ .../cloud/blueprint/dto/aws/AwsBluePrintListDto.java | 2 ++ .../cloud/blueprint/service/AwsBlueprintServiceImpl.java | 2 ++ 3 files changed, 6 insertions(+) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index cdf25ac..fc6af54 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -1,6 +1,7 @@ package com.kumofactory.cloud.blueprint.dto.aws; import com.kumofactory.cloud.blueprint.domain.ComponentLine; +import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; import com.kumofactory.cloud.blueprint.domain.aws.AwsComponent; import com.kumofactory.cloud.blueprint.dto.ComponentLineDto; @@ -14,6 +15,7 @@ public class AwsBluePrintDto { private String uuid; private String name; + private ProvisionStatus status; private List components; private List links; diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java index 0d88072..fd8c795 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java @@ -1,5 +1,6 @@ package com.kumofactory.cloud.blueprint.dto.aws; +import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; import lombok.Getter; import lombok.Setter; @@ -12,4 +13,5 @@ public class AwsBluePrintListDto { private String uuid; private String name; private Date createdAt; + private ProvisionStatus status; } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index ab186ac..f30a55c 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -55,6 +55,7 @@ public AwsBluePrintDto getAwsBlueprint(String uuid) { List componentLines = componentLineRepository.findAllByBluePrint(awsBluePrintById); AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); awsBluePrintDto.setName(awsBluePrintById.getName()); + awsBluePrintDto.setStatus(awsBluePrintById.getStatus()); awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); return awsBluePrintDto; @@ -75,6 +76,7 @@ public List getMyAwsBlueprints(String oauthId) { dto.setUuid(awsBluePrint.getUuid()); dto.setId(awsBluePrint.getId()); dto.setCreatedAt(awsBluePrint.getCreated_at()); + dto.setStatus(awsBluePrint.getStatus()); awsBluePrintDtos.add(dto); } return awsBluePrintDtos; From 6fbc32074e1d31a14e26d075ea1ceb52b565a7d6 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 7 Aug 2023 16:49:29 +0900 Subject: [PATCH 38/63] ff --- .../cloud/blueprint/BlueprintController.java | 12 ++++++++---- .../blueprint/service/AwsBlueprintServiceImpl.java | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index 1a12d40..0ec7d7d 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -2,15 +2,20 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; +import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; import com.kumofactory.cloud.global.annotation.auth.AuthorizationFromToken; import com.kumofactory.cloud.global.rabbitmq.MessageProducer; +import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; +import java.util.List; + +@Tag(name = "AwsBlueprintService", description = "AwsBlueprintService") @RestController @RequiredArgsConstructor @RequestMapping("/blueprint") @@ -21,21 +26,20 @@ public class BlueprintController { @GetMapping("/aws/{uuid}") @AuthorizationFromToken - public Object getAwsBlueprint(@PathVariable("uuid") String uuid, String userId) { + + public AwsBluePrintDto getAwsBlueprint(@PathVariable("uuid") String uuid, String userId) { return awsBlueprintService.getAwsBlueprint(uuid); } @GetMapping("/aws/list") @AuthorizationFromToken - public Object getAwsBlueprintList(String userId) { - logger.info("userId: {}", userId); + public List getAwsBlueprintList(String userId) { return awsBlueprintService.getMyAwsBlueprints(userId); } @PostMapping("/aws") @AuthorizationFromToken public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, @RequestParam String provision, String userId) throws JsonProcessingException { - logger.info(userId); awsBlueprintService.store(awsBluePrintDto, provision, userId); return "hello-world"; } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index f30a55c..d2562b6 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -18,6 +18,7 @@ import com.kumofactory.cloud.global.rabbitmq.MessageProducer; import com.kumofactory.cloud.member.MemberRepository; import com.kumofactory.cloud.member.domain.Member; +import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; From 823120ca36e5e2e298dc539286d952f6fa317050 Mon Sep 17 00:00:00 2001 From: wook Date: Mon, 7 Aug 2023 16:57:55 +0900 Subject: [PATCH 39/63] =?UTF-8?q?add=20:=20swagger=20=EC=97=90=20get=20dto?= =?UTF-8?q?=20=EB=AA=85=EC=84=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kumofactory/cloud/blueprint/BlueprintController.java | 7 ++++++- .../cloud/blueprint/dto/aws/AwsBluePrintDto.java | 2 ++ .../cloud/blueprint/dto/aws/AwsBluePrintListDto.java | 2 ++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index 0ec7d7d..78c64ca 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -6,6 +6,9 @@ import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; import com.kumofactory.cloud.global.annotation.auth.AuthorizationFromToken; import com.kumofactory.cloud.global.rabbitmq.MessageProducer; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -13,6 +16,7 @@ import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; +import java.util.ArrayList; import java.util.List; @Tag(name = "AwsBlueprintService", description = "AwsBlueprintService") @@ -24,13 +28,14 @@ public class BlueprintController { private final Logger logger = LoggerFactory.getLogger(BlueprintController.class); private final AwsBlueprintService awsBlueprintService; + @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = AwsBluePrintDto.class))) @GetMapping("/aws/{uuid}") @AuthorizationFromToken - public AwsBluePrintDto getAwsBlueprint(@PathVariable("uuid") String uuid, String userId) { return awsBlueprintService.getAwsBlueprint(uuid); } + @ApiResponse(responseCode = "200", description = "OK") @GetMapping("/aws/list") @AuthorizationFromToken public List getAwsBlueprintList(String userId) { diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index fc6af54..2def79c 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -8,10 +8,12 @@ import java.util.ArrayList; import java.util.List; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data +@Schema(name = "AwsBluePrintDto", description = "AwsBluePrintDto") public class AwsBluePrintDto { private String uuid; private String name; diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java index fd8c795..162e311 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java @@ -1,6 +1,7 @@ package com.kumofactory.cloud.blueprint.dto.aws; import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Getter; import lombok.Setter; @@ -8,6 +9,7 @@ @Getter @Setter +@Schema(name = "AwsBluePrintListDto", description = "AwsBluePrintListDto") public class AwsBluePrintListDto { private Long id; private String uuid; From 00f1ba9eb5a0f8751b4cc3d510cda6565bec3d88 Mon Sep 17 00:00:00 2001 From: wook Date: Tue, 8 Aug 2023 00:38:59 +0900 Subject: [PATCH 40/63] =?UTF-8?q?feat=20:=20area=20=EC=86=8D=EC=84=B1=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cloud/blueprint/domain/AccessScope.java | 5 ++ .../domain/aws/AvailabilityZone.java | 5 ++ .../cloud/blueprint/domain/aws/AwsArea.java | 62 +++++++++++++++++ .../blueprint/domain/aws/AwsAreaType.java | 5 ++ .../blueprint/domain/aws/AwsBluePrint.java | 5 ++ .../blueprint/domain/aws/AwsComponent.java | 68 +++++++++---------- .../cloud/blueprint/dto/aws/AccessScope.java | 5 -- .../blueprint/dto/aws/AvailabilityZone.java | 5 -- .../cloud/blueprint/dto/aws/AwsAreaDto.java | 38 +++++++++++ .../blueprint/dto/aws/AwsBluePrintDto.java | 10 +++ .../repository/aws/AwsAreaRepository.java | 13 ++++ .../service/AwsBlueprintServiceImpl.java | 19 ++++-- .../global/rabbitmq/MessageProducer.java | 21 ++---- 13 files changed, 198 insertions(+), 63 deletions(-) create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/domain/AccessScope.java create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AvailabilityZone.java create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsArea.java create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java delete mode 100644 src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java delete mode 100644 src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsAreaDto.java create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsAreaRepository.java diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/AccessScope.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/AccessScope.java new file mode 100644 index 0000000..df91094 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/AccessScope.java @@ -0,0 +1,5 @@ +package com.kumofactory.cloud.blueprint.domain; + +public enum AccessScope { + PUBLIC, PRIVATE, DATABASE, NONE +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AvailabilityZone.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AvailabilityZone.java new file mode 100644 index 0000000..70b7b79 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AvailabilityZone.java @@ -0,0 +1,5 @@ +package com.kumofactory.cloud.blueprint.domain.aws; + +public enum AvailabilityZone { + AP_NORTHEAST_2A, AP_NORTHEAST_2B, AP_NORTHEAST_2C, AP_NORTHEAST_2D +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsArea.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsArea.java new file mode 100644 index 0000000..96adf7a --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsArea.java @@ -0,0 +1,62 @@ +package com.kumofactory.cloud.blueprint.domain.aws; + +import com.kumofactory.cloud.blueprint.domain.AccessScope; +import com.kumofactory.cloud.blueprint.dto.aws.AwsAreaDto; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import javax.persistence.*; +import java.util.Date; + +@Entity +@Getter +@Setter +@NoArgsConstructor +public class AwsArea { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @CreationTimestamp + private Date created_at; + + @UpdateTimestamp + private Date updated_at; + + @Enumerated(EnumType.STRING) + private AwsAreaType type; + + @Enumerated(EnumType.STRING) + private AccessScope scope; + + @Enumerated(EnumType.STRING) + private AvailabilityZone az; + + // ==== Diagram 에서 사용하는 정보 ==== // + private String ui_id; // Client 에서 생성하는 uuid + private Integer position_x; + private Integer position_y; + private Integer width; + private Integer height; + + @ManyToOne + private AwsBluePrint bluePrint; + + public static AwsArea createAwsArea(AwsAreaDto dto, AwsBluePrint bluePrint) { + AwsArea area = new AwsArea(); + area.setUi_id(dto.getId()); + area.setPosition_x(dto.getX()); + area.setPosition_y(dto.getY()); + area.setWidth(dto.getWidth()); + area.setHeight(dto.getHeight()); + area.setType(dto.getType()); + area.setScope(dto.getScope()); + area.setAz(dto.getAz()); + area.setBluePrint(bluePrint); + return area; + } + +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java new file mode 100644 index 0000000..b90a8ad --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java @@ -0,0 +1,5 @@ +package com.kumofactory.cloud.blueprint.domain.aws; + +public enum AwsAreaType { + VPC, SUBNET +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java index 2cc8457..5be771d 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java @@ -26,18 +26,23 @@ public class AwsBluePrint { @CreationTimestamp private Date created_at; + @UpdateTimestamp private Date updated_at; private String uuid; // Client 에서 생성하는 uuid private String name; // 블루프린트 이름 + @Enumerated(EnumType.STRING) private ProvisionStatus status; // 배포 상태 @ManyToOne private Member member; + @OneToMany(mappedBy = "bluePrint", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) + private List areas; + @OneToMany(mappedBy = "bluePrint", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private List cspComponents; diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java index a019d69..fda4936 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponent.java @@ -1,7 +1,5 @@ package com.kumofactory.cloud.blueprint.domain.aws; -import com.kumofactory.cloud.blueprint.dto.aws.AccessScope; -import com.kumofactory.cloud.blueprint.dto.aws.AvailabilityZone; import com.kumofactory.cloud.blueprint.dto.aws.AwsComponentDto; import io.hypersistence.utils.hibernate.type.json.JsonType; import lombok.AllArgsConstructor; @@ -27,41 +25,41 @@ @TypeDef(name = "json", typeClass = JsonType.class) public class AwsComponent { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @CreationTimestamp - private Date created_at; - @UpdateTimestamp - private Date updated_at; - - @Column(unique = true) - private String ui_id; // Client 에서 생성하는 uuid + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @Enumerated(STRING) - private AwsComponentType type; // Component 타입 (vm, vpc, subnet, ...) - - @Type(type = "json") - @Column(columnDefinition = "json") - private Map options; + @CreationTimestamp + private Date created_at; + @UpdateTimestamp + private Date updated_at; - // Component 의 좌측 상단 좌표 - private Integer position_x; - private Integer position_y; + @Column(unique = true) + private String ui_id; // Client 에서 생성하는 uuid - @ManyToOne - private AwsBluePrint bluePrint; + @Enumerated(STRING) + private AwsComponentType type; // Component 타입 (vm, vpc, subnet, ...) - // ============== 생성함수 ================= // - public static AwsComponent createAwsComponent(AwsComponentDto awsComponentDto, AwsBluePrint awsBluePrint) { - AwsComponent awsComponent = new AwsComponent(); - awsComponent.setUi_id(awsComponentDto.getId()); - awsComponent.setPosition_x(awsComponentDto.getX()); - awsComponent.setPosition_y(awsComponentDto.getY()); - awsComponent.setType(awsComponentDto.getType()); - awsComponent.setOptions(awsComponentDto.getOptions()); - awsComponent.setBluePrint(awsBluePrint); - return awsComponent; - } + @Type(type = "json") + @Column(columnDefinition = "json") + private Map options; + + // Component 의 좌측 상단 좌표 + private Integer position_x; + private Integer position_y; + + @ManyToOne + private AwsBluePrint bluePrint; + + // ============== 생성함수 ================= // + public static AwsComponent createAwsComponent(AwsComponentDto awsComponentDto, AwsBluePrint awsBluePrint) { + AwsComponent awsComponent = new AwsComponent(); + awsComponent.setUi_id(awsComponentDto.getId()); + awsComponent.setPosition_x(awsComponentDto.getX()); + awsComponent.setPosition_y(awsComponentDto.getY()); + awsComponent.setType(awsComponentDto.getType()); + awsComponent.setOptions(awsComponentDto.getOptions()); + awsComponent.setBluePrint(awsBluePrint); + return awsComponent; + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java deleted file mode 100644 index f7ce2d9..0000000 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AccessScope.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.kumofactory.cloud.blueprint.dto.aws; - -public enum AccessScope { - PUBLIC, PRIVATE, DATABASE -} \ No newline at end of file diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java deleted file mode 100644 index fda32f3..0000000 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AvailabilityZone.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.kumofactory.cloud.blueprint.dto.aws; - -public enum AvailabilityZone { - AP_NORTHEAST_2A, AP_NORTHEAST_2C -} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsAreaDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsAreaDto.java new file mode 100644 index 0000000..9ca932f --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsAreaDto.java @@ -0,0 +1,38 @@ +package com.kumofactory.cloud.blueprint.dto.aws; + +import com.kumofactory.cloud.blueprint.domain.AccessScope; +import com.kumofactory.cloud.blueprint.domain.aws.AvailabilityZone; +import com.kumofactory.cloud.blueprint.domain.aws.AwsArea; +import com.kumofactory.cloud.blueprint.domain.aws.AwsAreaType; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Schema(name = "AwsAreaDto", description = "AwsAreaDto") +public class AwsAreaDto { + private String id; + private Integer x; + private Integer y; + private Integer width; + private Integer height; + private AwsAreaType type; + private AccessScope scope; + private AvailabilityZone az; + + // todo : 필요하면 option 추가 + + public static AwsAreaDto mapper(AwsArea area) { + AwsAreaDto dto = new AwsAreaDto(); + dto.setId(area.getUi_id()); + dto.setX(area.getPosition_x()); + dto.setY(area.getPosition_y()); + dto.setWidth(area.getWidth()); + dto.setHeight(area.getHeight()); + dto.setType(area.getType()); + dto.setScope(area.getScope()); + dto.setAz(area.getAz()); + return dto; + } +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index 2def79c..50383ab 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -2,6 +2,7 @@ import com.kumofactory.cloud.blueprint.domain.ComponentLine; import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; +import com.kumofactory.cloud.blueprint.domain.aws.AwsArea; import com.kumofactory.cloud.blueprint.domain.aws.AwsComponent; import com.kumofactory.cloud.blueprint.dto.ComponentLineDto; @@ -18,9 +19,18 @@ public class AwsBluePrintDto { private String uuid; private String name; private ProvisionStatus status; + private List areas; private List components; private List links; + public static List awsAreaDtosMapper(List awsAreaDtos) { + List awsAreaDtoList = new ArrayList<>(); + for (AwsArea awsAreaDto : awsAreaDtos) { + awsAreaDtoList.add(AwsAreaDto.mapper(awsAreaDto)); + } + return awsAreaDtoList; + } + public static List awsComponentDtosMapper(List awsComponentDtos) { List awsComponentDtoList = new ArrayList<>(); for (AwsComponent awsComponent : awsComponentDtos) { diff --git a/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsAreaRepository.java b/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsAreaRepository.java new file mode 100644 index 0000000..0930327 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsAreaRepository.java @@ -0,0 +1,13 @@ +package com.kumofactory.cloud.blueprint.repository.aws; + +import com.kumofactory.cloud.blueprint.domain.aws.AwsArea; +import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface AwsAreaRepository extends JpaRepository { + List findAllByBluePrint(AwsBluePrint awsBluePrint); +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index d2562b6..1336beb 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -3,16 +3,15 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.kumofactory.cloud.blueprint.domain.ComponentLine; import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; +import com.kumofactory.cloud.blueprint.domain.aws.AwsArea; import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.domain.aws.AwsComponent; import com.kumofactory.cloud.blueprint.dto.ComponentLineDto; -import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; +import com.kumofactory.cloud.blueprint.dto.aws.*; -import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; -import com.kumofactory.cloud.blueprint.dto.aws.AwsCdkDto; -import com.kumofactory.cloud.blueprint.dto.aws.AwsComponentDto; import com.kumofactory.cloud.blueprint.repository.ComponentDotRepository; import com.kumofactory.cloud.blueprint.repository.ComponentLineRepository; +import com.kumofactory.cloud.blueprint.repository.aws.AwsAreaRepository; import com.kumofactory.cloud.blueprint.repository.aws.AwsBluePrintRepository; import com.kumofactory.cloud.blueprint.repository.aws.AwsComponentRepository; import com.kumofactory.cloud.global.rabbitmq.MessageProducer; @@ -41,6 +40,7 @@ public class AwsBlueprintServiceImpl implements AwsBlueprintService { private final AwsBluePrintRepository awsBluePrintRepository; private final AwsComponentRepository awsComponentRepository; private final ComponentLineRepository componentLineRepository; + private final AwsAreaRepository awsAreaRepository; private final MessageProducer sender; private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); @@ -52,11 +52,13 @@ public AwsBluePrintDto getAwsBlueprint(String uuid) { throw new RuntimeException("awsBluePrintById is null"); } + List awsAreas = awsAreaRepository.findAllByBluePrint(awsBluePrintById); List awsComponents = awsComponentRepository.findAllByBluePrint(awsBluePrintById); List componentLines = componentLineRepository.findAllByBluePrint(awsBluePrintById); AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); awsBluePrintDto.setName(awsBluePrintById.getName()); awsBluePrintDto.setStatus(awsBluePrintById.getStatus()); + awsBluePrintDto.setAreas(AwsBluePrintDto.awsAreaDtosMapper(awsAreas)); awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); return awsBluePrintDto; @@ -87,6 +89,7 @@ public List getMyAwsBlueprints(String oauthId) { public void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException { AwsBluePrint savedBlueprint = saveBlueprint(awsBluePrintDto, provision, userId); // BluePrint 저장 saveComponentLines(savedBlueprint, awsBluePrintDto.getLinks()); // ComponentLine 저장 + saveAwsAreas(savedBlueprint, awsBluePrintDto.getAreas()); // Area 저장 List components = new ArrayList<>(); List awsCdkDtos = new ArrayList<>(); @@ -131,6 +134,14 @@ private void saveComponentLines(AwsBluePrint blueprint, List l componentLines.add(componentLink); } componentLineRepository.saveAll(componentLines); + } + private void saveAwsAreas(AwsBluePrint blueprint, List areas) { + List awsArea = new ArrayList<>(); + for (AwsAreaDto link : areas) { + AwsArea area = AwsArea.createAwsArea(link, blueprint); + awsArea.add(area); + } + awsAreaRepository.saveAll(awsArea); } } diff --git a/src/main/java/com/kumofactory/cloud/global/rabbitmq/MessageProducer.java b/src/main/java/com/kumofactory/cloud/global/rabbitmq/MessageProducer.java index 4189915..f3a2839 100644 --- a/src/main/java/com/kumofactory/cloud/global/rabbitmq/MessageProducer.java +++ b/src/main/java/com/kumofactory/cloud/global/rabbitmq/MessageProducer.java @@ -2,16 +2,9 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.kumofactory.cloud.blueprint.domain.aws.AwsComponentType; -import com.kumofactory.cloud.blueprint.dto.aws.AccessScope; import com.kumofactory.cloud.blueprint.dto.aws.AwsCdkDto; -import com.kumofactory.cloud.global.config.RabbitMQConfig; import lombok.RequiredArgsConstructor; -import org.springframework.amqp.AmqpException; import org.springframework.amqp.core.AmqpTemplate; -import org.springframework.amqp.core.Exchange; -import org.springframework.amqp.core.Message; -import org.springframework.amqp.core.MessagePostProcessor; import org.springframework.stereotype.Service; import java.util.HashMap; @@ -21,12 +14,12 @@ @Service @RequiredArgsConstructor public class MessageProducer { - private final AmqpTemplate rabbitTemplate; - private final String queueName = "kumofactory-queue"; + private final AmqpTemplate rabbitTemplate; + private final String queueName = "kumofactory-queue"; - public void sendAwsCdkOption(List list) throws JsonProcessingException { - ObjectMapper objectMapper = new ObjectMapper(); - String s = objectMapper.writeValueAsString(list); - rabbitTemplate.convertAndSend(queueName, s); - } + public void sendAwsCdkOption(List list) throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + String s = objectMapper.writeValueAsString(list); + rabbitTemplate.convertAndSend(queueName, s); + } } From 2301b9ee72fe024b412c65eea4d666c17b3f0a62 Mon Sep 17 00:00:00 2001 From: wook Date: Tue, 8 Aug 2023 00:47:10 +0900 Subject: [PATCH 41/63] update : add AZ in AwsAreaType --- .../com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java index b90a8ad..3eb8865 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsAreaType.java @@ -1,5 +1,5 @@ package com.kumofactory.cloud.blueprint.domain.aws; public enum AwsAreaType { - VPC, SUBNET + VPC, SUBNET, AZ } From 476b435f283a8914264ef1821849f74237060ebe Mon Sep 17 00:00:00 2001 From: coding-convention Date: Tue, 8 Aug 2023 01:30:32 +0900 Subject: [PATCH 42/63] feat: Util for AWS S3 #33 --- build.gradle | 4 + .../cloud/util/aws/s3/AwsS3Helper.java | 13 +++ .../cloud/util/aws/s3/AwsS3HelperImpl.java | 83 +++++++++++++++++++ 3 files changed, 100 insertions(+) create mode 100644 src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3Helper.java create mode 100644 src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java diff --git a/build.gradle b/build.gradle index 91a416c..a82e430 100644 --- a/build.gradle +++ b/build.gradle @@ -33,6 +33,10 @@ dependencies { implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2' implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2' implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2' + +// implementation 'com.amazonaws:aws-java-sdk-s3:1.12.112' + + implementation 'software.amazon.awssdk:s3:2.17.112' } tasks.named('test') { diff --git a/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3Helper.java b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3Helper.java new file mode 100644 index 0000000..1045e66 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3Helper.java @@ -0,0 +1,13 @@ +package com.kumofactory.cloud.util.aws.s3; + +import org.springframework.web.multipart.MultipartFile; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import java.io.IOException; + +public interface AwsS3Helper { + + void putS3Object(MultipartFile svgFile, String keyName) throws S3Exception, IOException; + + String getPresignedUrl(String keyName) throws S3Exception; +} diff --git a/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java new file mode 100644 index 0000000..9422d65 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java @@ -0,0 +1,83 @@ +package com.kumofactory.cloud.util.aws.s3; + +import com.kumofactory.cloud.config.S3Config; +import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.multipart.MultipartFile; +import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; +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.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; +import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; + +import java.io.IOException; +import java.time.Duration; + +@RequiredArgsConstructor +public class AwsS3HelperImpl implements AwsS3Helper { + + private final S3Config s3Config; + private final ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create(); + private final Logger logger = LoggerFactory.getLogger(AwsS3HelperImpl.class); + + public void putS3Object(MultipartFile svgFile, String keyName) throws S3Exception, IOException{ + + S3Client s3Client = S3Client.builder() + .region(Region.of(s3Config.getRegion())) + .credentialsProvider(credentialsProvider) + .build(); + + try { + s3Client.putObject(PutObjectRequest.builder() + .bucket(s3Config.getBucket()) + .key(keyName) + .build(), + RequestBody.fromFile(svgFile.getResource().getFile())); + + logger.info("File uploaded to S3 bucket successfully"); + } catch (S3Exception e) { + throw e; + } catch (IOException e) { + throw e; + } finally { + s3Client.close(); + } + } + + public String getPresignedUrl(String keyName) { + + S3Presigner presigner = S3Presigner.builder() + .region(Region.of(s3Config.getRegion())) + .credentialsProvider(credentialsProvider) + .build(); + + try { + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(s3Config.getBucket()) + .key(keyName) + .build(); + + GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder() + .signatureDuration(Duration.ofMinutes(60)) + .getObjectRequest(getObjectRequest) + .build(); + + PresignedGetObjectRequest presignedGetObjectRequest = presigner.presignGetObject(getObjectPresignRequest); + String presignedUrl = presignedGetObjectRequest.url().toString(); + logger.info("Presigned URL: {}", presignedUrl); + return presignedUrl; + + } catch (S3Exception e) { + logger.error(e.awsErrorDetails().errorMessage()); + throw e; + } finally { + presigner.close(); + } + } +} From 5088e03ca2a0fb397b0cec9aee3960722352217e Mon Sep 17 00:00:00 2001 From: coding-convention Date: Tue, 8 Aug 2023 01:31:14 +0900 Subject: [PATCH 43/63] feat: S3 config #33 --- .../com/kumofactory/cloud/config/S3Config.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/main/java/com/kumofactory/cloud/config/S3Config.java diff --git a/src/main/java/com/kumofactory/cloud/config/S3Config.java b/src/main/java/com/kumofactory/cloud/config/S3Config.java new file mode 100644 index 0000000..7e5c2f3 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/config/S3Config.java @@ -0,0 +1,16 @@ +package com.kumofactory.cloud.config; + +import lombok.Data; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@Data +@ConfigurationProperties(prefix = "aws") +public class S3Config { + @Value("${aws.s3.bucket}") + private String bucket; + @Value("${aws.s3.region}") + private String region; +} From ee077d43532a9af3d96b7134644a3eb203bf6c47 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Tue, 8 Aug 2023 01:33:03 +0900 Subject: [PATCH 44/63] feat: add thumbnail content to dtos #33 --- .../kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java | 2 ++ .../cloud/blueprint/dto/aws/AwsBluePrintListDto.java | 1 + 2 files changed, 3 insertions(+) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index eb73f6d..8cab01b 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -8,6 +8,7 @@ import java.util.List; import lombok.Data; +import org.springframework.web.multipart.MultipartFile; @Data @@ -16,6 +17,7 @@ public class AwsBluePrintDto { private String name; private List components; private List links; + private MultipartFile svgFile; public static List awsComponentDtosMapper(List awsComponentDtos) { List awsComponentDtoList = new ArrayList<>(); diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java index 99bec33..ad3109a 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintListDto.java @@ -11,4 +11,5 @@ public class AwsBluePrintListDto { private Long id; private String name; private Date createdAt; + private String presignedUrl; } From ca55228c9ce871efba2d9eaa8d44314961127d17 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Tue, 8 Aug 2023 01:33:42 +0900 Subject: [PATCH 45/63] feat: add thumbnail content to impl #33 --- .../service/AwsBlueprintServiceImpl.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 28fef92..388a721 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -14,6 +14,7 @@ import com.kumofactory.cloud.blueprint.repository.aws.AwsComponentRepository; import com.kumofactory.cloud.member.MemberRepository; import com.kumofactory.cloud.member.domain.Member; +import com.kumofactory.cloud.util.aws.s3.AwsS3Helper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; @@ -35,6 +36,8 @@ public class AwsBlueprintServiceImpl implements AwsBlueprintService { private final AwsComponentRepository awsComponentRepository; private final ComponentLineRepository componentLineRepository; private final ComponentDotRepository componentDotRepository; + + private final AwsS3Helper awsS3Helper; private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); @@ -68,6 +71,7 @@ public List getMyAwsBlueprints(String oauthId) { dto.setName(awsBluePrint.getName()); dto.setId(awsBluePrint.getId()); dto.setCreatedAt(awsBluePrint.getCreated_at()); + dto.setPresignedUrl(_getObjectKey(member.getId(), awsBluePrint.getId())); awsBluePrintDtos.add(dto); } return awsBluePrintDtos; @@ -100,5 +104,17 @@ public void store(AwsBluePrintDto awsBluePrintDto, String userId) { componentLines.add(componentLink); } componentLineRepository.saveAll(componentLines); + + // thumbnail 저장 + String objectKey = _getObjectKey(member.getId(), savedBlueprint.getId()); + try { + awsS3Helper.putS3Object(awsBluePrintDto.getSvgFile(), objectKey); + } catch (Exception e) { + logger.error("thumbnail upload failed: {}", e.getMessage()); + } + } + + private String _getObjectKey(Long memberId, Long blueprintId) { + return memberId + "/" + blueprintId + ".svg"; } } From e6f9742f6038299dc4a7160cd254e6f3226ffa3d Mon Sep 17 00:00:00 2001 From: wook Date: Tue, 8 Aug 2023 13:44:09 +0900 Subject: [PATCH 46/63] fix: fix error --- .../cloud/blueprint/service/AwsBlueprintServiceImpl.java | 9 +++++---- .../kumofactory/cloud/{ => global}/config/S3Config.java | 2 +- .../kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java | 6 ++++-- 3 files changed, 10 insertions(+), 7 deletions(-) rename src/main/java/com/kumofactory/cloud/{ => global}/config/S3Config.java (90%) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 65de304..4511007 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -23,6 +23,7 @@ import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; @@ -146,8 +147,8 @@ private void saveAwsAreas(AwsBluePrint blueprint, List areas) { } awsAreaRepository.saveAll(awsArea); } - - private String _getObjectKey(Long memberId, Long blueprintId) { - return memberId + "/" + blueprintId + ".svg"; - } + + private String _getObjectKey(Long memberId, Long blueprintId) { + return memberId + "/" + blueprintId + ".svg"; + } } diff --git a/src/main/java/com/kumofactory/cloud/config/S3Config.java b/src/main/java/com/kumofactory/cloud/global/config/S3Config.java similarity index 90% rename from src/main/java/com/kumofactory/cloud/config/S3Config.java rename to src/main/java/com/kumofactory/cloud/global/config/S3Config.java index 7e5c2f3..34c3b21 100644 --- a/src/main/java/com/kumofactory/cloud/config/S3Config.java +++ b/src/main/java/com/kumofactory/cloud/global/config/S3Config.java @@ -1,4 +1,4 @@ -package com.kumofactory.cloud.config; +package com.kumofactory.cloud.global.config; import lombok.Data; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java index 9422d65..120e209 100644 --- a/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java +++ b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java @@ -1,9 +1,10 @@ package com.kumofactory.cloud.util.aws.s3; -import com.kumofactory.cloud.config.S3Config; +import com.kumofactory.cloud.global.config.S3Config; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.core.sync.RequestBody; @@ -19,6 +20,7 @@ import java.io.IOException; import java.time.Duration; +@Service @RequiredArgsConstructor public class AwsS3HelperImpl implements AwsS3Helper { @@ -26,7 +28,7 @@ public class AwsS3HelperImpl implements AwsS3Helper { private final ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create(); private final Logger logger = LoggerFactory.getLogger(AwsS3HelperImpl.class); - public void putS3Object(MultipartFile svgFile, String keyName) throws S3Exception, IOException{ + public void putS3Object(MultipartFile svgFile, String keyName) throws S3Exception, IOException { S3Client s3Client = S3Client.builder() .region(Region.of(s3Config.getRegion())) From b2e060690c6e0fc75000ce69cab82fa00297cd78 Mon Sep 17 00:00:00 2001 From: wook Date: Tue, 8 Aug 2023 14:34:58 +0900 Subject: [PATCH 47/63] update : RDS -> RDS_MYSQL --- .../cloud/blueprint/domain/aws/AwsComponentType.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java index a84a3c7..6a0f22b 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsComponentType.java @@ -1,5 +1,5 @@ package com.kumofactory.cloud.blueprint.domain.aws; public enum AwsComponentType { - VPC, SUBNET, ALB, NLB, EC2, EFS, WAF, ROUTE53, NAT_GATEWAY, RDS, S3, ELASTIC_CACHE, CLOUDFRONT, AUTO_SCALING + VPC, SUBNET, ALB, NLB, EC2, EFS, WAF, ROUTE53, NAT_GATEWAY, RDS_MYSQL, S3, ELASTIC_CACHE, CLOUDFRONT, AUTO_SCALING } \ No newline at end of file From 93ca34951d6a6465eb4ef66ec12969c05765f671 Mon Sep 17 00:00:00 2001 From: wook Date: Tue, 8 Aug 2023 15:12:25 +0900 Subject: [PATCH 48/63] feat : delete blueprint --- .../cloud/blueprint/BlueprintController.java | 10 ++++++++ .../blueprint/domain/aws/AwsBluePrint.java | 6 ++--- .../service/AwsBlueprintService.java | 2 ++ .../service/AwsBlueprintServiceImpl.java | 24 ++++++++++++++++++- .../cloud/global/dto/ResultDto.java | 11 +++++++++ 5 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/kumofactory/cloud/global/dto/ResultDto.java diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index 78c64ca..ffce850 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -5,6 +5,7 @@ import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; import com.kumofactory.cloud.global.annotation.auth.AuthorizationFromToken; +import com.kumofactory.cloud.global.dto.ResultDto; import com.kumofactory.cloud.global.rabbitmq.MessageProducer; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @@ -48,4 +49,13 @@ public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, @ awsBlueprintService.store(awsBluePrintDto, provision, userId); return "hello-world"; } + + @DeleteMapping("/aws/{uuid}") + public ResultDto deleteAwsBlueprint(@PathVariable("uuid") String uuid) { + boolean result = awsBlueprintService.delete(uuid); + return ResultDto.builder() + .result(result) + .message(!result ? "Not Found " : "") + .build(); + } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java index 5be771d..1f8b2b8 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java @@ -40,13 +40,13 @@ public class AwsBluePrint { @ManyToOne private Member member; - @OneToMany(mappedBy = "bluePrint", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) + @OneToMany(mappedBy = "bluePrint", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List areas; - @OneToMany(mappedBy = "bluePrint", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) + @OneToMany(mappedBy = "bluePrint", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List cspComponents; - @OneToMany(mappedBy = "bluePrint", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) + @OneToMany(mappedBy = "bluePrint", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List lines; } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java index d780b4c..15d16f1 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java @@ -15,4 +15,6 @@ public interface AwsBlueprintService { List getMyAwsBlueprints(String userId); void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException; + + boolean delete(String uuid); // blueprint uuid 로 모든 정보 삭세 } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 4511007..525a6e5 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -83,6 +83,7 @@ public List getMyAwsBlueprints(String oauthId) { dto.setId(awsBluePrint.getId()); dto.setCreatedAt(awsBluePrint.getCreated_at()); dto.setStatus(awsBluePrint.getStatus()); + dto.setPresignedUrl(_getObjectKey(member.getOauthId(), awsBluePrint.getUuid())); awsBluePrintDtos.add(dto); } return awsBluePrintDtos; @@ -90,6 +91,8 @@ public List getMyAwsBlueprints(String oauthId) { @Override public void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException { + this.delete(awsBluePrintDto.getUuid()); // 기존 BluePrint 삭제 + AwsBluePrint savedBlueprint = saveBlueprint(awsBluePrintDto, provision, userId); // BluePrint 저장 saveComponentLines(savedBlueprint, awsBluePrintDto.getLinks()); // ComponentLine 저장 saveAwsAreas(savedBlueprint, awsBluePrintDto.getAreas()); // Area 저장 @@ -111,6 +114,16 @@ public void store(AwsBluePrintDto awsBluePrintDto, String provision, String user } } + @Override + public boolean delete(String uuid) { + AwsBluePrint awsBluePrint = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); + if (awsBluePrint == null) { + return false; + } + awsBluePrintRepository.delete(awsBluePrint); + return true; + } + // Blueprint 저장 private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provision, String userId) { Member member = memberRepository.findMemberByOauthId(userId); @@ -126,6 +139,15 @@ private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provi awsBluePrint.setName(awsBluePrintDto.getName()); awsBluePrint.setStatus(status); awsBluePrint.setMember(member); + + // thumbnail 저장 + String objectKey = _getObjectKey(member.getOauthId(), awsBluePrint.getUuid()); + try { + awsS3Helper.putS3Object(awsBluePrintDto.getSvgFile(), objectKey); + } catch (Exception e) { + logger.error("thumbnail upload failed: {}", e.getMessage()); + } + return awsBluePrintRepository.save(awsBluePrint); } @@ -148,7 +170,7 @@ private void saveAwsAreas(AwsBluePrint blueprint, List areas) { awsAreaRepository.saveAll(awsArea); } - private String _getObjectKey(Long memberId, Long blueprintId) { + private String _getObjectKey(String memberId, String blueprintId) { return memberId + "/" + blueprintId + ".svg"; } } diff --git a/src/main/java/com/kumofactory/cloud/global/dto/ResultDto.java b/src/main/java/com/kumofactory/cloud/global/dto/ResultDto.java new file mode 100644 index 0000000..d5daa52 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/global/dto/ResultDto.java @@ -0,0 +1,11 @@ +package com.kumofactory.cloud.global.dto; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class ResultDto { + boolean result; + String message; +} From f4acb3511a7131c3274cc6eb1a41ac00656e4f56 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Tue, 8 Aug 2023 15:38:29 +0900 Subject: [PATCH 49/63] fix: method call #33 --- .../cloud/blueprint/service/AwsBlueprintServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 525a6e5..44eb08a 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -83,7 +83,7 @@ public List getMyAwsBlueprints(String oauthId) { dto.setId(awsBluePrint.getId()); dto.setCreatedAt(awsBluePrint.getCreated_at()); dto.setStatus(awsBluePrint.getStatus()); - dto.setPresignedUrl(_getObjectKey(member.getOauthId(), awsBluePrint.getUuid())); + dto.setPresignedUrl(awsS3Helper.getPresignedUrl(_getObjectKey(member.getOauthId(), awsBluePrint.getUuid()))); awsBluePrintDtos.add(dto); } return awsBluePrintDtos; From d3ce6e2bd6e6488d6a0a86a1ff7af6980d040d11 Mon Sep 17 00:00:00 2001 From: wook Date: Tue, 8 Aug 2023 15:55:46 +0900 Subject: [PATCH 50/63] =?UTF-8?q?feat=20:=20blueprint=20scope=20=EC=83=81?= =?UTF-8?q?=ED=83=9C=20=EC=B6=94=EA=B0=80=20=EB=B0=8F=20api=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cloud/blueprint/BlueprintController.java | 42 +++++++++++++++---- .../blueprint/domain/BluePrintScope.java | 7 ++++ .../blueprint/domain/aws/AwsBluePrint.java | 4 ++ .../blueprint/dto/aws/AwsBluePrintDto.java | 4 +- .../service/AwsBlueprintService.java | 3 ++ .../service/AwsBlueprintServiceImpl.java | 27 +++++++++--- .../cloud/global/config/SwaggerConfig.java | 23 +++++++--- 7 files changed, 89 insertions(+), 21 deletions(-) create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/domain/BluePrintScope.java diff --git a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java index ffce850..537f076 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/BlueprintController.java @@ -1,15 +1,18 @@ package com.kumofactory.cloud.blueprint; import com.fasterxml.jackson.core.JsonProcessingException; +import com.kumofactory.cloud.blueprint.domain.BluePrintScope; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; import com.kumofactory.cloud.blueprint.service.AwsBlueprintService; import com.kumofactory.cloud.global.annotation.auth.AuthorizationFromToken; import com.kumofactory.cloud.global.dto.ResultDto; import com.kumofactory.cloud.global.rabbitmq.MessageProducer; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -36,6 +39,36 @@ public AwsBluePrintDto getAwsBlueprint(@PathVariable("uuid") String uuid, String return awsBlueprintService.getAwsBlueprint(uuid); } + @Operation( + summary = "BluePrint scope 업데이트", + description = "Requires authentication.", + security = @SecurityRequirement(name = "bearerAuth") + ) + @PutMapping("/aws/{uuid}") + @AuthorizationFromToken + public ResultDto updateBluePrintScope(@PathVariable("uuid") String uuid, @RequestParam("scope") BluePrintScope scope, String userId) { + boolean result = awsBlueprintService.updateBluePrintScope(scope, uuid, userId); + return ResultDto.builder() + .result(result) + .message(!result ? "Not Found or Not Authorized" : "") + .build(); + } + + @Operation( + summary = "BluePrint 삭제", + description = "Requires authentication.", + security = @SecurityRequirement(name = "bearerAuth") + ) + @DeleteMapping("/aws/{uuid}") + @AuthorizationFromToken + public ResultDto deleteAwsBlueprint(@PathVariable("uuid") String uuid, String userId) { + boolean result = awsBlueprintService.delete(uuid); + return ResultDto.builder() + .result(result) + .message(!result ? "Not Found " : "") + .build(); + } + @ApiResponse(responseCode = "200", description = "OK") @GetMapping("/aws/list") @AuthorizationFromToken @@ -49,13 +82,4 @@ public Object createAwsBlueprint(@RequestBody AwsBluePrintDto awsBluePrintDto, @ awsBlueprintService.store(awsBluePrintDto, provision, userId); return "hello-world"; } - - @DeleteMapping("/aws/{uuid}") - public ResultDto deleteAwsBlueprint(@PathVariable("uuid") String uuid) { - boolean result = awsBlueprintService.delete(uuid); - return ResultDto.builder() - .result(result) - .message(!result ? "Not Found " : "") - .build(); - } } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/BluePrintScope.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/BluePrintScope.java new file mode 100644 index 0000000..146b65c --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/BluePrintScope.java @@ -0,0 +1,7 @@ +package com.kumofactory.cloud.blueprint.domain; + +public enum BluePrintScope { + PUBLIC, // 공개 ( 모든 사용자가 볼 수 있음 ) + PRIVATE, // + KUMOFACTORY // kumofactory 에서 만든 template +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java index 1f8b2b8..735a7fe 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java @@ -1,5 +1,6 @@ package com.kumofactory.cloud.blueprint.domain.aws; +import com.kumofactory.cloud.blueprint.domain.BluePrintScope; import com.kumofactory.cloud.blueprint.domain.ComponentLine; import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; import com.kumofactory.cloud.member.domain.Member; @@ -37,6 +38,9 @@ public class AwsBluePrint { @Enumerated(EnumType.STRING) private ProvisionStatus status; // 배포 상태 + @Enumerated(EnumType.STRING) + private BluePrintScope scope; // 블루프린트 공개 범위 + @ManyToOne private Member member; diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index 7ecf386..263796c 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -1,5 +1,6 @@ package com.kumofactory.cloud.blueprint.dto.aws; +import com.kumofactory.cloud.blueprint.domain.BluePrintScope; import com.kumofactory.cloud.blueprint.domain.ComponentLine; import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; import com.kumofactory.cloud.blueprint.domain.aws.AwsArea; @@ -17,10 +18,11 @@ @Data @Schema(name = "AwsBluePrintDto", description = "AwsBluePrintDto") public class AwsBluePrintDto { - + private String uuid; private String name; private ProvisionStatus status; + private BluePrintScope scope; private List areas; private List components; private List links; diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java index 15d16f1..97b3b1d 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintService.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; +import com.kumofactory.cloud.blueprint.domain.BluePrintScope; import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintDto; import com.kumofactory.cloud.blueprint.dto.aws.AwsBluePrintListDto; @@ -17,4 +18,6 @@ public interface AwsBlueprintService { void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException; boolean delete(String uuid); // blueprint uuid 로 모든 정보 삭세 + + boolean updateBluePrintScope(BluePrintScope scope, String uuid, String userId); } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 525a6e5..e0f33a0 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -1,6 +1,7 @@ package com.kumofactory.cloud.blueprint.service; import com.fasterxml.jackson.core.JsonProcessingException; +import com.kumofactory.cloud.blueprint.domain.BluePrintScope; import com.kumofactory.cloud.blueprint.domain.ComponentLine; import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; import com.kumofactory.cloud.blueprint.domain.aws.AwsArea; @@ -124,6 +125,17 @@ public boolean delete(String uuid) { return true; } + @Override + public boolean updateBluePrintScope(BluePrintScope scope, String uuid, String userId) { + AwsBluePrint awsBluePrintByUuid = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); + if (awsBluePrintByUuid == null || !awsBluePrintByUuid.getMember().getOauthId().equals(userId)) { + return false; + } + awsBluePrintByUuid.setScope(scope); + awsBluePrintRepository.save(awsBluePrintByUuid); + return true; + } + // Blueprint 저장 private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provision, String userId) { Member member = memberRepository.findMemberByOauthId(userId); @@ -139,16 +151,21 @@ private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provi awsBluePrint.setName(awsBluePrintDto.getName()); awsBluePrint.setStatus(status); awsBluePrint.setMember(member); + awsBluePrint.setScope(BluePrintScope.PRIVATE); - // thumbnail 저장 - String objectKey = _getObjectKey(member.getOauthId(), awsBluePrint.getUuid()); + saveThumbnail(awsBluePrintDto, member); // thumbnail 저장 + + return awsBluePrintRepository.save(awsBluePrint); + } + + // thumbnail 저장 + private void saveThumbnail(AwsBluePrintDto bluePrint, Member member) { + String objectKey = _getObjectKey(member.getOauthId(), bluePrint.getUuid()); try { - awsS3Helper.putS3Object(awsBluePrintDto.getSvgFile(), objectKey); + awsS3Helper.putS3Object(bluePrint.getSvgFile(), objectKey); } catch (Exception e) { logger.error("thumbnail upload failed: {}", e.getMessage()); } - - return awsBluePrintRepository.save(awsBluePrint); } // ComponentLine 저장 diff --git a/src/main/java/com/kumofactory/cloud/global/config/SwaggerConfig.java b/src/main/java/com/kumofactory/cloud/global/config/SwaggerConfig.java index 26183d5..6eb9e2b 100644 --- a/src/main/java/com/kumofactory/cloud/global/config/SwaggerConfig.java +++ b/src/main/java/com/kumofactory/cloud/global/config/SwaggerConfig.java @@ -1,7 +1,9 @@ package com.kumofactory.cloud.global.config; +import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityScheme; import org.springdoc.core.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -10,17 +12,26 @@ public class SwaggerConfig { @Bean public GroupedOpenApi publicApi() { - return GroupedOpenApi.builder() - .group("v1-definition") - .pathsToMatch("/**") - .build(); + return GroupedOpenApi.builder().group("v1-definition").pathsToMatch("/**").build(); } @Bean public OpenAPI springShopOpenAPI() { return new OpenAPI() - .info(new Info().title("Bstagram API") + .components( + new Components().addSecuritySchemes("bearer-key", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")) + ) + .info(new Info() + .title("Bstagram API") .description("Kumofactory API 명세") - .version("v0.0.1")); + .version("v0.0.1") + ); + } + + private io.swagger.v3.oas.models.security.SecurityScheme securityScheme() { + return new io.swagger.v3.oas.models.security.SecurityScheme() + .type(io.swagger.v3.oas.models.security.SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT"); } } From 43fe8e441006ddd744a2390744208d01c7221333 Mon Sep 17 00:00:00 2001 From: wook Date: Tue, 8 Aug 2023 16:49:40 +0900 Subject: [PATCH 51/63] feat : set env from application.yml --- .../cloud/global/config/RabbitMQConfig.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java index 7fb0b1e..6672d45 100644 --- a/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java +++ b/src/main/java/com/kumofactory/cloud/global/config/RabbitMQConfig.java @@ -6,6 +6,7 @@ import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -14,6 +15,15 @@ public class RabbitMQConfig { public static final String topicExchangeName = "aws.cdk"; private final String queueName = "kumofactory-queue"; + @Value("${rabbitmq.host}") + private String host; + + @Value("${rabbitmq.user}") + private String user; + + @Value("${rabbitmq.password}") + private String password; + @Bean public Queue queue() { return new Queue(queueName, false); @@ -37,9 +47,9 @@ Binding binding(Queue queue, TopicExchange exchange) { @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory factory = new CachingConnectionFactory(); - factory.setHost("localhost"); - factory.setUsername("guest"); - factory.setPassword("guest"); + factory.setHost(host); + factory.setUsername(user); + factory.setPassword(password); return factory.getRabbitConnectionFactory(); } From ab842a26a2cb068fb30abeb3afe7dcc8b0998ef6 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Wed, 9 Aug 2023 04:49:55 +0900 Subject: [PATCH 52/63] fix: Convert frontend to send Blob instead of binary --- build.gradle | 1 + .../cloud/blueprint/dto/aws/AwsBluePrintDto.java | 2 +- .../cloud/blueprint/service/AwsBlueprintServiceImpl.java | 7 ++++++- .../com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index 33bb7ce..114e8b4 100644 --- a/build.gradle +++ b/build.gradle @@ -19,6 +19,7 @@ repositories { } dependencies { + implementation 'org.springframework:spring-test:5.3.10' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' developmentOnly 'org.springframework.boot:spring-boot-devtools' implementation 'org.springframework.boot:spring-boot-starter-web' diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index 7ecf386..e737b73 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -24,7 +24,7 @@ public class AwsBluePrintDto { private List areas; private List components; private List links; - private MultipartFile svgFile; + private String svgFile; public static List awsAreaDtosMapper(List awsAreaDtos) { List awsAreaDtoList = new ArrayList<>(); diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 44eb08a..1f2cc99 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -24,10 +24,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockMultipartFile; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; +import java.util.Base64; import java.util.List; import static java.lang.Boolean.parseBoolean; @@ -143,7 +146,9 @@ private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provi // thumbnail 저장 String objectKey = _getObjectKey(member.getOauthId(), awsBluePrint.getUuid()); try { - awsS3Helper.putS3Object(awsBluePrintDto.getSvgFile(), objectKey); + byte[] svgContent = Base64.getDecoder().decode(awsBluePrintDto.getSvgFile()); + MultipartFile svgFile = new MockMultipartFile("file", objectKey, "image/svg+xml", svgContent); + awsS3Helper.putS3Object(svgFile, objectKey); } catch (Exception e) { logger.error("thumbnail upload failed: {}", e.getMessage()); } diff --git a/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java index 120e209..18e349b 100644 --- a/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java +++ b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java @@ -40,7 +40,7 @@ public void putS3Object(MultipartFile svgFile, String keyName) throws S3Exceptio .bucket(s3Config.getBucket()) .key(keyName) .build(), - RequestBody.fromFile(svgFile.getResource().getFile())); + RequestBody.fromInputStream(svgFile.getInputStream(), svgFile.getSize())); logger.info("File uploaded to S3 bucket successfully"); } catch (S3Exception e) { From aa4b6d2460d8ed6b9bf6ac5cc1150f717682a7c9 Mon Sep 17 00:00:00 2001 From: wook Date: Wed, 9 Aug 2023 11:16:04 +0900 Subject: [PATCH 53/63] feat : add s3 keyname --- .../cloud/blueprint/domain/aws/AwsBluePrint.java | 2 ++ .../cloud/blueprint/dto/aws/AwsBluePrintDto.java | 1 + .../repository/aws/AwsBluePrintRepository.java | 5 +++++ .../blueprint/service/AwsBlueprintServiceImpl.java | 12 ++++++++---- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java index 735a7fe..9040a75 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/domain/aws/AwsBluePrint.java @@ -35,6 +35,8 @@ public class AwsBluePrint { private String name; // 블루프린트 이름 + private String keyName; // 썸네일 이미지 파일명 (S3) + @Enumerated(EnumType.STRING) private ProvisionStatus status; // 배포 상태 diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java index 263796c..6742b1b 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/aws/AwsBluePrintDto.java @@ -4,6 +4,7 @@ import com.kumofactory.cloud.blueprint.domain.ComponentLine; import com.kumofactory.cloud.blueprint.domain.ProvisionStatus; import com.kumofactory.cloud.blueprint.domain.aws.AwsArea; +import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.blueprint.domain.aws.AwsComponent; import com.kumofactory.cloud.blueprint.dto.ComponentLineDto; diff --git a/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java b/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java index 1868f78..307127c 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/repository/aws/AwsBluePrintRepository.java @@ -1,7 +1,9 @@ package com.kumofactory.cloud.blueprint.repository.aws; +import com.kumofactory.cloud.blueprint.domain.BluePrintScope; import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; import com.kumofactory.cloud.member.domain.Member; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @@ -17,4 +19,7 @@ public interface AwsBluePrintRepository extends JpaRepository findAwsBluePrintsByMember(Member member); + List findAllByScope(BluePrintScope scope, Pageable pageable); + + List findAllByName(String name, Pageable pageable); } diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index e0f33a0..6056ea1 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -62,6 +62,7 @@ public AwsBluePrintDto getAwsBlueprint(String uuid) { AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); awsBluePrintDto.setName(awsBluePrintById.getName()); awsBluePrintDto.setStatus(awsBluePrintById.getStatus()); + awsBluePrintDto.setUuid(awsBluePrintById.getUuid()); awsBluePrintDto.setAreas(AwsBluePrintDto.awsAreaDtosMapper(awsAreas)); awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); @@ -84,7 +85,7 @@ public List getMyAwsBlueprints(String oauthId) { dto.setId(awsBluePrint.getId()); dto.setCreatedAt(awsBluePrint.getCreated_at()); dto.setStatus(awsBluePrint.getStatus()); - dto.setPresignedUrl(_getObjectKey(member.getOauthId(), awsBluePrint.getUuid())); + dto.setPresignedUrl(awsBluePrint.getKeyName()); awsBluePrintDtos.add(dto); } return awsBluePrintDtos; @@ -146,26 +147,29 @@ private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provi status = ProvisionStatus.PENDING; } // BluePrint 저장 + String keyname = saveThumbnail(awsBluePrintDto, member);// thumbnail 저장 + AwsBluePrint awsBluePrint = new AwsBluePrint(); awsBluePrint.setUuid(awsBluePrintDto.getUuid()); awsBluePrint.setName(awsBluePrintDto.getName()); awsBluePrint.setStatus(status); awsBluePrint.setMember(member); awsBluePrint.setScope(BluePrintScope.PRIVATE); - - saveThumbnail(awsBluePrintDto, member); // thumbnail 저장 + awsBluePrint.setKeyName(keyname); return awsBluePrintRepository.save(awsBluePrint); } // thumbnail 저장 - private void saveThumbnail(AwsBluePrintDto bluePrint, Member member) { + private String saveThumbnail(AwsBluePrintDto bluePrint, Member member) { String objectKey = _getObjectKey(member.getOauthId(), bluePrint.getUuid()); try { awsS3Helper.putS3Object(bluePrint.getSvgFile(), objectKey); } catch (Exception e) { logger.error("thumbnail upload failed: {}", e.getMessage()); } + + return objectKey; } // ComponentLine 저장 From 5f6da6e2de20f31875202977c5d2856422f5f3d3 Mon Sep 17 00:00:00 2001 From: wook Date: Wed, 9 Aug 2023 11:16:22 +0900 Subject: [PATCH 54/63] feat : add templatePreviewDto --- .../dto/template/TemplatePreviewDto.java | 26 ++++++++++ .../blueprint/service/AwsTemplateService.java | 16 ++++++ .../service/AwsTemplateServiceImpl.java | 49 +++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/dto/template/TemplatePreviewDto.java create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateService.java create mode 100644 src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateServiceImpl.java diff --git a/src/main/java/com/kumofactory/cloud/blueprint/dto/template/TemplatePreviewDto.java b/src/main/java/com/kumofactory/cloud/blueprint/dto/template/TemplatePreviewDto.java new file mode 100644 index 0000000..ccf1406 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/dto/template/TemplatePreviewDto.java @@ -0,0 +1,26 @@ +package com.kumofactory.cloud.blueprint.dto.template; + +import com.kumofactory.cloud.blueprint.domain.BluePrintScope; +import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Builder +public class TemplatePreviewDto { + private String uuid; + private String name; + private BluePrintScope scope; + private String thumbnail_url; + + public static TemplatePreviewDto mapper(AwsBluePrint bluePrint, String thumbnailUrl) { + return TemplatePreviewDto.builder() + .uuid(bluePrint.getUuid()) + .name(bluePrint.getName()) + .scope(bluePrint.getScope()) + .thumbnail_url(thumbnailUrl) + .build(); + } +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateService.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateService.java new file mode 100644 index 0000000..11ff94a --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateService.java @@ -0,0 +1,16 @@ +package com.kumofactory.cloud.blueprint.service; + +import com.kumofactory.cloud.blueprint.dto.template.TemplatePreviewDto; +import org.springframework.data.domain.Pageable; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import java.util.List; + +public interface AwsTemplateService { + // blueprint 이름으로 조회 + List searchTemplateFromKumofactory(Pageable pageable) throws S3Exception; + +// void searchTemplateFromUser(); + + List searchTemplateFromTemplateName(Pageable pageable, String templateName) throws S3Exception; +} diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateServiceImpl.java new file mode 100644 index 0000000..a05c777 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateServiceImpl.java @@ -0,0 +1,49 @@ +package com.kumofactory.cloud.blueprint.service; + +import com.kumofactory.cloud.blueprint.domain.BluePrintScope; +import com.kumofactory.cloud.blueprint.domain.aws.AwsBluePrint; +import com.kumofactory.cloud.blueprint.dto.template.TemplatePreviewDto; +import com.kumofactory.cloud.blueprint.repository.aws.AwsBluePrintRepository; +import com.kumofactory.cloud.util.aws.s3.AwsS3Helper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import java.util.ArrayList; +import java.util.List; + +@Service +@RequiredArgsConstructor +@Slf4j +public class AwsTemplateServiceImpl implements AwsTemplateService { + private final AwsBluePrintRepository templateRepository; + private final AwsS3Helper s3; + private final Logger logger = LoggerFactory.getLogger(AwsTemplateServiceImpl.class); + + @Override + public List searchTemplateFromKumofactory(Pageable pageable) throws S3Exception { + List all = templateRepository.findAllByScope(BluePrintScope.KUMOFACTORY, pageable); + List dtos = new ArrayList<>(); + try { + for (AwsBluePrint awsBluePrint : all) { + String url = s3.getPresignedUrl(awsBluePrint.getUuid()); + TemplatePreviewDto dto = TemplatePreviewDto.mapper(awsBluePrint, url); + dtos.add(dto); + } + return dtos; + } catch (S3Exception e) { + logger.error("S3Exception: {}", e.getMessage()); + throw S3Exception.builder().build(); + } + } + + @Override + public List searchTemplateFromTemplateName(Pageable pageable, String templateName) { + + } +} From bd778853d5a47e9d35308edd9a00607b8b9023ed Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Wed, 9 Aug 2023 11:17:26 +0900 Subject: [PATCH 55/63] #25-deploy-aws-cdk: Auto stash before merge of "feature/#25-deploy-aws-cdk" and "origin/feature/#25-deploy-aws-cdk" --- .github/workflows/Build-Deploy-dev.yaml | 2 +- .../service/AwsBlueprintServiceImpl.java | 156 +++++++++--------- 2 files changed, 79 insertions(+), 79 deletions(-) diff --git a/.github/workflows/Build-Deploy-dev.yaml b/.github/workflows/Build-Deploy-dev.yaml index 0b1206f..9ac19e9 100644 --- a/.github/workflows/Build-Deploy-dev.yaml +++ b/.github/workflows/Build-Deploy-dev.yaml @@ -45,7 +45,7 @@ jobs: shell: bash - name: Build Project - run: gradle build + run: ./gradlew clean build ############################################ ### Start Pushing container image on ECR ### diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 6056ea1..c5dddb4 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -39,22 +39,22 @@ @Repository public class AwsBlueprintServiceImpl implements AwsBlueprintService { - private final MemberRepository memberRepository; - private final AwsBluePrintRepository awsBluePrintRepository; - private final AwsComponentRepository awsComponentRepository; - private final ComponentLineRepository componentLineRepository; - private final AwsAreaRepository awsAreaRepository; - private final MessageProducer sender; - private final AwsS3Helper awsS3Helper; - private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); - - - @Override - public AwsBluePrintDto getAwsBlueprint(String uuid) { - AwsBluePrint awsBluePrintById = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); - if (awsBluePrintById == null) { - throw new RuntimeException("awsBluePrintById is null"); - } + private final MemberRepository memberRepository; + private final AwsBluePrintRepository awsBluePrintRepository; + private final AwsComponentRepository awsComponentRepository; + private final ComponentLineRepository componentLineRepository; + private final AwsAreaRepository awsAreaRepository; + private final MessageProducer sender; + private final AwsS3Helper awsS3Helper; + private final Logger logger = LoggerFactory.getLogger(AwsBlueprintServiceImpl.class); + + + @Override + public AwsBluePrintDto getAwsBlueprint(String uuid) { + AwsBluePrint awsBluePrintById = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); + if (awsBluePrintById == null) { + throw new RuntimeException("awsBluePrintById is null"); + } List awsAreas = awsAreaRepository.findAllByBluePrint(awsBluePrintById); List awsComponents = awsComponentRepository.findAllByBluePrint(awsBluePrintById); @@ -69,12 +69,12 @@ public AwsBluePrintDto getAwsBlueprint(String uuid) { return awsBluePrintDto; } - @Override - public List getMyAwsBlueprints(String oauthId) { - Member member = memberRepository.findMemberByOauthId(oauthId); - if (member == null) { - throw new RuntimeException("member is null"); - } + @Override + public List getMyAwsBlueprints(String oauthId) { + Member member = memberRepository.findMemberByOauthId(oauthId); + if (member == null) { + throw new RuntimeException("member is null"); + } List awsBluePrints = awsBluePrintRepository.findAwsBluePrintsByMember(member); List awsBluePrintDtos = new ArrayList<>(); @@ -91,40 +91,40 @@ public List getMyAwsBlueprints(String oauthId) { return awsBluePrintDtos; } - @Override - public void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException { - this.delete(awsBluePrintDto.getUuid()); // 기존 BluePrint 삭제 - - AwsBluePrint savedBlueprint = saveBlueprint(awsBluePrintDto, provision, userId); // BluePrint 저장 - saveComponentLines(savedBlueprint, awsBluePrintDto.getLinks()); // ComponentLine 저장 - saveAwsAreas(savedBlueprint, awsBluePrintDto.getAreas()); // Area 저장 - - List components = new ArrayList<>(); - List awsCdkDtos = new ArrayList<>(); - - // Components 저장 - for (AwsComponentDto component : awsBluePrintDto.getComponents()) { - AwsComponent awsComponent = AwsComponent.createAwsComponent(component, savedBlueprint); - AwsCdkDto awsCdkDto = AwsCdkDto.createAwsCdkDto(component); - components.add(awsComponent); - awsCdkDtos.add(awsCdkDto); - } - awsComponentRepository.saveAll(components); - - if (parseBoolean(provision)) { - sender.sendAwsCdkOption(awsCdkDtos); - } - } - - @Override - public boolean delete(String uuid) { - AwsBluePrint awsBluePrint = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); - if (awsBluePrint == null) { - return false; - } - awsBluePrintRepository.delete(awsBluePrint); - return true; - } + @Override + public void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException { + this.delete(awsBluePrintDto.getUuid()); // 기존 BluePrint 삭제 + + AwsBluePrint savedBlueprint = saveBlueprint(awsBluePrintDto, provision, userId); // BluePrint 저장 + saveComponentLines(savedBlueprint, awsBluePrintDto.getLinks()); // ComponentLine 저장 + saveAwsAreas(savedBlueprint, awsBluePrintDto.getAreas()); // Area 저장 + + List components = new ArrayList<>(); + List awsCdkDtos = new ArrayList<>(); + + // Components 저장 + for (AwsComponentDto component : awsBluePrintDto.getComponents()) { + AwsComponent awsComponent = AwsComponent.createAwsComponent(component, savedBlueprint); + AwsCdkDto awsCdkDto = AwsCdkDto.createAwsCdkDto(component); + components.add(awsComponent); + awsCdkDtos.add(awsCdkDto); + } + awsComponentRepository.saveAll(components); + + if (parseBoolean(provision)) { + sender.sendAwsCdkOption(awsCdkDtos); + } + } + + @Override + public boolean delete(String uuid) { + AwsBluePrint awsBluePrint = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); + if (awsBluePrint == null) { + return false; + } + awsBluePrintRepository.delete(awsBluePrint); + return true; + } @Override public boolean updateBluePrintScope(BluePrintScope scope, String uuid, String userId) { @@ -172,26 +172,26 @@ private String saveThumbnail(AwsBluePrintDto bluePrint, Member member) { return objectKey; } - // ComponentLine 저장 - private void saveComponentLines(AwsBluePrint blueprint, List lines) { - List componentLines = new ArrayList<>(); - for (ComponentLineDto link : lines) { - ComponentLine componentLink = ComponentLine.createComponentLink(link, blueprint); - componentLines.add(componentLink); - } - componentLineRepository.saveAll(componentLines); - } - - private void saveAwsAreas(AwsBluePrint blueprint, List areas) { - List awsArea = new ArrayList<>(); - for (AwsAreaDto link : areas) { - AwsArea area = AwsArea.createAwsArea(link, blueprint); - awsArea.add(area); - } - awsAreaRepository.saveAll(awsArea); - } - - private String _getObjectKey(String memberId, String blueprintId) { - return memberId + "/" + blueprintId + ".svg"; - } + // ComponentLine 저장 + private void saveComponentLines(AwsBluePrint blueprint, List lines) { + List componentLines = new ArrayList<>(); + for (ComponentLineDto link : lines) { + ComponentLine componentLink = ComponentLine.createComponentLink(link, blueprint); + componentLines.add(componentLink); + } + componentLineRepository.saveAll(componentLines); + } + + private void saveAwsAreas(AwsBluePrint blueprint, List areas) { + List awsArea = new ArrayList<>(); + for (AwsAreaDto link : areas) { + AwsArea area = AwsArea.createAwsArea(link, blueprint); + awsArea.add(area); + } + awsAreaRepository.saveAll(awsArea); + } + + private String _getObjectKey(String memberId, String blueprintId) { + return memberId + "/" + blueprintId + ".svg"; + } } From 8d9ca9f26266eb016ed883e61baf33277c81286e Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Wed, 9 Aug 2023 11:26:29 +0900 Subject: [PATCH 56/63] fix : rename variable name --- .../service/AwsBlueprintServiceImpl.java | 146 +++++++++--------- 1 file changed, 73 insertions(+), 73 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java index 6ea80a7..72bd6fb 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsBlueprintServiceImpl.java @@ -59,18 +59,18 @@ public AwsBluePrintDto getAwsBlueprint(String uuid) { throw new RuntimeException("awsBluePrintById is null"); } - List awsAreas = awsAreaRepository.findAllByBluePrint(awsBluePrintById); - List awsComponents = awsComponentRepository.findAllByBluePrint(awsBluePrintById); - List componentLines = componentLineRepository.findAllByBluePrint(awsBluePrintById); - AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); - awsBluePrintDto.setName(awsBluePrintById.getName()); - awsBluePrintDto.setStatus(awsBluePrintById.getStatus()); - awsBluePrintDto.setUuid(awsBluePrintById.getUuid()); - awsBluePrintDto.setAreas(AwsBluePrintDto.awsAreaDtosMapper(awsAreas)); - awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); - awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); - return awsBluePrintDto; - } + List awsAreas = awsAreaRepository.findAllByBluePrint(awsBluePrintById); + List awsComponents = awsComponentRepository.findAllByBluePrint(awsBluePrintById); + List componentLines = componentLineRepository.findAllByBluePrint(awsBluePrintById); + AwsBluePrintDto awsBluePrintDto = new AwsBluePrintDto(); + awsBluePrintDto.setName(awsBluePrintById.getName()); + awsBluePrintDto.setStatus(awsBluePrintById.getStatus()); + awsBluePrintDto.setUuid(awsBluePrintById.getUuid()); + awsBluePrintDto.setAreas(AwsBluePrintDto.awsAreaDtosMapper(awsAreas)); + awsBluePrintDto.setComponents(AwsBluePrintDto.awsComponentDtosMapper(awsComponents)); + awsBluePrintDto.setLinks(AwsBluePrintDto.componentLinkDtoListMapper(componentLines)); + return awsBluePrintDto; + } @Override public List getMyAwsBlueprints(String oauthId) { @@ -79,20 +79,20 @@ public List getMyAwsBlueprints(String oauthId) { throw new RuntimeException("member is null"); } - List awsBluePrints = awsBluePrintRepository.findAwsBluePrintsByMember(member); - List awsBluePrintDtos = new ArrayList<>(); - for (AwsBluePrint awsBluePrint : awsBluePrints) { - AwsBluePrintListDto dto = new AwsBluePrintListDto(); - dto.setName(awsBluePrint.getName()); - dto.setUuid(awsBluePrint.getUuid()); - dto.setId(awsBluePrint.getId()); - dto.setCreatedAt(awsBluePrint.getCreated_at()); - dto.setStatus(awsBluePrint.getStatus()); - dto.setPresignedUrl(awsS3Helper.getPresignedUrl(awsBluePrint.getKeyName())); - awsBluePrintDtos.add(dto); - } - return awsBluePrintDtos; - } + List awsBluePrints = awsBluePrintRepository.findAwsBluePrintsByMember(member); + List awsBluePrintDtos = new ArrayList<>(); + for (AwsBluePrint awsBluePrint : awsBluePrints) { + AwsBluePrintListDto dto = new AwsBluePrintListDto(); + dto.setName(awsBluePrint.getName()); + dto.setUuid(awsBluePrint.getUuid()); + dto.setId(awsBluePrint.getId()); + dto.setCreatedAt(awsBluePrint.getCreated_at()); + dto.setStatus(awsBluePrint.getStatus()); + dto.setPresignedUrl(awsS3Helper.getPresignedUrl(awsBluePrint.getKeyName())); + awsBluePrintDtos.add(dto); + } + return awsBluePrintDtos; + } @Override public void store(AwsBluePrintDto awsBluePrintDto, String provision, String userId) throws JsonProcessingException { @@ -129,53 +129,53 @@ public boolean delete(String uuid) { return true; } - @Override - public boolean updateBluePrintScope(BluePrintScope scope, String uuid, String userId) { - AwsBluePrint awsBluePrintByUuid = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); - if (awsBluePrintByUuid == null || !awsBluePrintByUuid.getMember().getOauthId().equals(userId)) { - return false; - } - awsBluePrintByUuid.setScope(scope); - awsBluePrintRepository.save(awsBluePrintByUuid); - return true; - } - - // Blueprint 저장 - private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provision, String userId) { - Member member = memberRepository.findMemberByOauthId(userId); - ProvisionStatus status; - if (parseBoolean(provision)) { - status = ProvisionStatus.PROVISIONING; - } else { - status = ProvisionStatus.PENDING; - } - // BluePrint 저장 - String keyname = saveThumbnail(awsBluePrintDto, member);// thumbnail 저장 - - AwsBluePrint awsBluePrint = new AwsBluePrint(); - awsBluePrint.setUuid(awsBluePrintDto.getUuid()); - awsBluePrint.setName(awsBluePrintDto.getName()); - awsBluePrint.setStatus(status); - awsBluePrint.setMember(member); - awsBluePrint.setScope(BluePrintScope.PRIVATE); - awsBluePrint.setKeyName(keyname); - - return awsBluePrintRepository.save(awsBluePrint); - } - - // thumbnail 저장 - private String saveThumbnail(AwsBluePrintDto bluePrint, Member member) { - String objectKey = _getObjectKey(member.getOauthId(), bluePrint.getUuid()); - try { - byte[] svgContent = Base64.getDecoder().decode(awsBluePrintDto.getSvgFile()); - MultipartFile svgFile = new MockMultipartFile("file", objectKey, "image/svg+xml", svgContent); - awsS3Helper.putS3Object(svgFile, objectKey); - } catch (Exception e) { - logger.error("thumbnail upload failed: {}", e.getMessage()); - } - - return objectKey; - } + @Override + public boolean updateBluePrintScope(BluePrintScope scope, String uuid, String userId) { + AwsBluePrint awsBluePrintByUuid = awsBluePrintRepository.findAwsBluePrintByUuid(uuid); + if (awsBluePrintByUuid == null || !awsBluePrintByUuid.getMember().getOauthId().equals(userId)) { + return false; + } + awsBluePrintByUuid.setScope(scope); + awsBluePrintRepository.save(awsBluePrintByUuid); + return true; + } + + // Blueprint 저장 + private AwsBluePrint saveBlueprint(AwsBluePrintDto awsBluePrintDto, String provision, String userId) { + Member member = memberRepository.findMemberByOauthId(userId); + ProvisionStatus status; + if (parseBoolean(provision)) { + status = ProvisionStatus.PROVISIONING; + } else { + status = ProvisionStatus.PENDING; + } + // BluePrint 저장 + String keyname = saveThumbnail(awsBluePrintDto, member);// thumbnail 저장 + + AwsBluePrint awsBluePrint = new AwsBluePrint(); + awsBluePrint.setUuid(awsBluePrintDto.getUuid()); + awsBluePrint.setName(awsBluePrintDto.getName()); + awsBluePrint.setStatus(status); + awsBluePrint.setMember(member); + awsBluePrint.setScope(BluePrintScope.PRIVATE); + awsBluePrint.setKeyName(keyname); + + return awsBluePrintRepository.save(awsBluePrint); + } + + // thumbnail 저장 + private String saveThumbnail(AwsBluePrintDto bluePrint, Member member) { + String objectKey = _getObjectKey(member.getOauthId(), bluePrint.getUuid()); + try { + byte[] svgContent = Base64.getDecoder().decode(bluePrint.getSvgFile()); + MultipartFile svgFile = new MockMultipartFile("file", objectKey, "image/svg+xml", svgContent); + awsS3Helper.putS3Object(svgFile, objectKey); + } catch (Exception e) { + logger.error("thumbnail upload failed: {}", e.getMessage()); + } + + return objectKey; + } // ComponentLine 저장 private void saveComponentLines(AwsBluePrint blueprint, List lines) { From cfc310659f6334ba81329451723b6b4e03a1454f Mon Sep 17 00:00:00 2001 From: Hyeonuook Kim Date: Wed, 9 Aug 2023 11:33:06 +0900 Subject: [PATCH 57/63] fix ; return null in searchTemplateFromTemplateName --- .../service/AwsTemplateServiceImpl.java | 45 ++++++++++--------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateServiceImpl.java b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateServiceImpl.java index a05c777..408e234 100644 --- a/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/blueprint/service/AwsTemplateServiceImpl.java @@ -21,29 +21,30 @@ @RequiredArgsConstructor @Slf4j public class AwsTemplateServiceImpl implements AwsTemplateService { - private final AwsBluePrintRepository templateRepository; - private final AwsS3Helper s3; - private final Logger logger = LoggerFactory.getLogger(AwsTemplateServiceImpl.class); + private final AwsBluePrintRepository templateRepository; + private final AwsS3Helper s3; + private final Logger logger = LoggerFactory.getLogger(AwsTemplateServiceImpl.class); - @Override - public List searchTemplateFromKumofactory(Pageable pageable) throws S3Exception { - List all = templateRepository.findAllByScope(BluePrintScope.KUMOFACTORY, pageable); - List dtos = new ArrayList<>(); - try { - for (AwsBluePrint awsBluePrint : all) { - String url = s3.getPresignedUrl(awsBluePrint.getUuid()); - TemplatePreviewDto dto = TemplatePreviewDto.mapper(awsBluePrint, url); - dtos.add(dto); - } - return dtos; - } catch (S3Exception e) { - logger.error("S3Exception: {}", e.getMessage()); - throw S3Exception.builder().build(); - } - } + @Override + public List searchTemplateFromKumofactory(Pageable pageable) throws S3Exception { + List all = templateRepository.findAllByScope(BluePrintScope.KUMOFACTORY, pageable); + List dtos = new ArrayList<>(); + try { + for (AwsBluePrint awsBluePrint : all) { + String url = s3.getPresignedUrl(awsBluePrint.getUuid()); + TemplatePreviewDto dto = TemplatePreviewDto.mapper(awsBluePrint, url); + dtos.add(dto); + } + return dtos; + } catch (S3Exception e) { + logger.error("S3Exception: {}", e.getMessage()); + throw S3Exception.builder().build(); + } + } - @Override - public List searchTemplateFromTemplateName(Pageable pageable, String templateName) { + @Override + public List searchTemplateFromTemplateName(Pageable pageable, String templateName) { - } + return null; + } } From b6ddcb6d80f66239d2a8b699c9f4aaf4b78d8cc3 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Wed, 9 Aug 2023 15:38:02 +0900 Subject: [PATCH 58/63] feat: get credentials provider via yaml instead .aws/credential --- .../kumofactory/cloud/global/config/S3Config.java | 12 ++++++++++++ .../cloud/util/aws/s3/AwsS3HelperImpl.java | 6 ++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/global/config/S3Config.java b/src/main/java/com/kumofactory/cloud/global/config/S3Config.java index 34c3b21..b47b49b 100644 --- a/src/main/java/com/kumofactory/cloud/global/config/S3Config.java +++ b/src/main/java/com/kumofactory/cloud/global/config/S3Config.java @@ -4,6 +4,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; @Component @Data @@ -13,4 +16,13 @@ public class S3Config { private String bucket; @Value("${aws.s3.region}") private String region; + + @Value("${aws.accessKey}") + private String accessKey; + @Value("${aws.secretKey}") + private String secretKey; + + public AwsCredentialsProvider getCredentialsProvider() { + return StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)); + } } diff --git a/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java index 18e349b..5656eda 100644 --- a/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java +++ b/src/main/java/com/kumofactory/cloud/util/aws/s3/AwsS3HelperImpl.java @@ -6,7 +6,6 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; -import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; @@ -25,14 +24,13 @@ public class AwsS3HelperImpl implements AwsS3Helper { private final S3Config s3Config; - private final ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create(); private final Logger logger = LoggerFactory.getLogger(AwsS3HelperImpl.class); public void putS3Object(MultipartFile svgFile, String keyName) throws S3Exception, IOException { S3Client s3Client = S3Client.builder() .region(Region.of(s3Config.getRegion())) - .credentialsProvider(credentialsProvider) + .credentialsProvider(s3Config.getCredentialsProvider()) .build(); try { @@ -56,7 +54,7 @@ public String getPresignedUrl(String keyName) { S3Presigner presigner = S3Presigner.builder() .region(Region.of(s3Config.getRegion())) - .credentialsProvider(credentialsProvider) + .credentialsProvider(s3Config.getCredentialsProvider()) .build(); try { From 27f3e922279f520919a5fd36751aa2dc8d89aca6 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Thu, 10 Aug 2023 03:02:13 +0900 Subject: [PATCH 59/63] feat: add accessToken, profileName columns #16 --- .../appDeploy/service/UserRepoService.java | 140 +----------------- .../cloud/oauth/dto/UserInfoDto.java | 4 +- .../service/github/GitHubServiceImpl.java | 13 +- .../service/google/GoogleServiceImpl.java | 2 +- 4 files changed, 17 insertions(+), 142 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java index b8373aa..1bc8792 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoService.java @@ -1,143 +1,15 @@ package com.kumofactory.cloud.appDeploy.service; -import com.fasterxml.jackson.databind.JsonNode; import com.kumofactory.cloud.appDeploy.dto.GitHubRepoDto; -import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.*; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.web.client.RestTemplate; - -import java.util.ArrayList; import java.util.List; -@Service -@Slf4j -public class UserRepoService { - - private final Logger logger = LoggerFactory.getLogger(UserRepoService.class); - private String token; - - public List RequestOrgRepoInfo(String org) { - String uri = "https://api.github.com/search/repositories?q=org:" + org; - ResponseEntity response = RequestGitHubAPIs(uri); - - if (response.getStatusCode() == HttpStatus.OK) { - JsonNode responseBody = response.getBody(); - - List repoInfoList = new ArrayList<>(); - - for (JsonNode node : responseBody.get("items")) { - String name = node.get("name").asText(); - String fullName = node.get("full_name").asText(); - Boolean isPrivate = node.get("private").asBoolean(); - Boolean isFork = node.get("fork").asBoolean(); - - GitHubRepoDto.RepoInfoDto repoInfo = new GitHubRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); - repoInfoList.add(repoInfo); - } - logger.info("response : {}", responseBody); - return repoInfoList; - } - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - return null; - } - - public GitHubRepoDto.UserDto RequestUserRepoInfoAndOrgList(String user) { - List repoInfoList = listUserRepos(user); - List orgList = new ArrayList<>(); - if( StringUtils.hasText(token) ) { - orgList = listOrganization(); - } - - return new GitHubRepoDto.UserDto(repoInfoList.size(), repoInfoList, orgList.size(), orgList); - } - - public List listUserRepos(String user) { - String uri = "https://api.github.com/search/repositories?q=user:" + user; - ResponseEntity response = RequestGitHubAPIs(uri); - - if (response.getStatusCode() == HttpStatus.OK) { - JsonNode responseBody = response.getBody(); - - List repoInfoList = new ArrayList<>(); - - for (JsonNode node : responseBody.get("items")) { - String name = node.get("name").asText(); - String fullName = node.get("full_name").asText(); - Boolean isPrivate = node.get("private").asBoolean(); - Boolean isFork = node.get("fork").asBoolean(); - - GitHubRepoDto.RepoInfoDto repoInfo = new GitHubRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); - repoInfoList.add(repoInfo); - } - logger.info("response : {}", responseBody); - return repoInfoList; - } - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - return null; - } - - public List listOrganization() { - String uri = "https://api.github.com/user/orgs"; - ResponseEntity response = RequestGitHubAPIs(uri); - - List organizationList = new ArrayList<>(); - - if (response.getStatusCode() == HttpStatus.OK) { - JsonNode responseBody = response.getBody(); - logger.info("response : {}", responseBody); - - if (responseBody.isArray()) { - for (JsonNode node : responseBody) { - if (node.has("login")) { - organizationList.add(node.get("login").asText()); - } - } - } - return organizationList; - } - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - return organizationList; - } - - private ResponseEntity RequestGitHubAPIs(String uri) { - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - if( StringUtils.hasText(token) ) { - headers.setBearerAuth(token); - } - HttpEntity httpEntity = new HttpEntity<>(headers); - return new RestTemplate().exchange(uri, HttpMethod.GET, httpEntity, JsonNode.class); - } - - public List RequestRepoBranches(String owner, String repo) { - String uri = "https://api.github.com/repos/" + owner + "/" + repo + "/branches"; - ResponseEntity response = RequestGitHubAPIs(uri); +public interface UserRepoService { + public List RequestOrgRepoInfo(String org, String oauthId); - List branchList = new ArrayList<>(); + public GitHubRepoDto.UserDto RequestUserRepoInfoAndOrgList(String oauthId); - if (response.getStatusCode() == HttpStatus.OK) { - JsonNode responseBody = response.getBody(); - logger.info("response : {}", responseBody); + public List RequestRepoBranches(String org, String repo, String oauthId); - if (responseBody.isArray()) { - for (JsonNode node : responseBody) { - if (node.has("name")) { - branchList.add(node.get("name").asText()); - } - } - } - return branchList; - } - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - return branchList; - } -} \ No newline at end of file + public List RequestRepoBranches(String repo, String oauthId); +} diff --git a/src/main/java/com/kumofactory/cloud/oauth/dto/UserInfoDto.java b/src/main/java/com/kumofactory/cloud/oauth/dto/UserInfoDto.java index a3bb05f..1b00593 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/dto/UserInfoDto.java +++ b/src/main/java/com/kumofactory/cloud/oauth/dto/UserInfoDto.java @@ -4,5 +4,7 @@ public record UserInfoDto( @JsonProperty("id") String id, - @JsonProperty("provider") String provider + @JsonProperty("provider") String provider, + @JsonProperty("accessToken") String accessToken, + @JsonProperty("profileName") String profileName ){} diff --git a/src/main/java/com/kumofactory/cloud/oauth/service/github/GitHubServiceImpl.java b/src/main/java/com/kumofactory/cloud/oauth/service/github/GitHubServiceImpl.java index e0ef40e..187bc9d 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/service/github/GitHubServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/oauth/service/github/GitHubServiceImpl.java @@ -78,12 +78,13 @@ public UserInfoDto requestUserInfo(String accessToken) throws JsonProcessingExce ResponseEntity response = restTemplate.exchange(requestEntity, JsonNode.class); if (response.getStatusCode() == HttpStatus.OK) { - JsonNode responseBody = response.getBody(); - logger.info("response : {}", response.getBody()); - if (responseBody != null) { - String id = responseBody.get("id").asText(); - String provider = String.valueOf(OAuthProvider.GITHUB); - return new UserInfoDto(id, provider); + JsonNode responseBody = response.getBody(); + logger.info("response : {}", response.getBody()); + if (responseBody != null) { + String owner = responseBody.get("login").asText(); + String id = responseBody.get("id").asText(); + String provider = String.valueOf(OAuthProvider.GITHUB); + return new UserInfoDto(id, provider, accessToken, owner); } } logger.error("response : {}", response.getBody()); diff --git a/src/main/java/com/kumofactory/cloud/oauth/service/google/GoogleServiceImpl.java b/src/main/java/com/kumofactory/cloud/oauth/service/google/GoogleServiceImpl.java index 4397f4a..4cd2b4f 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/service/google/GoogleServiceImpl.java +++ b/src/main/java/com/kumofactory/cloud/oauth/service/google/GoogleServiceImpl.java @@ -82,7 +82,7 @@ public UserInfoDto requestUserInfo(String accessToken) throws JsonProcessingExce if (responseBody != null) { String id = responseBody.get("id").asText(); String provider = String.valueOf(OAuthProvider.GOOGLE); - return new UserInfoDto(id, provider); + return new UserInfoDto(id, provider, accessToken, "deprecated"); } } logger.error("response : {}", response.getBody()); From 862a1ae24ab8936e93627bfa7f97cb01db5166fc Mon Sep 17 00:00:00 2001 From: coding-convention Date: Thu, 10 Aug 2023 03:04:19 +0900 Subject: [PATCH 60/63] feat: find member via oauthId #16 --- .../service/BuildRequestService.java | 63 +------ .../service/BuildRequestServiceImpl.java | 76 ++++++++ .../service/UserRepoServiceImpl.java | 166 ++++++++++++++++++ 3 files changed, 244 insertions(+), 61 deletions(-) create mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestServiceImpl.java create mode 100644 src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoServiceImpl.java diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java index fa87bce..9a86aef 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestService.java @@ -1,66 +1,7 @@ package com.kumofactory.cloud.appDeploy.service; -import com.fasterxml.jackson.databind.JsonNode; import com.kumofactory.cloud.appDeploy.dto.BuildRequestDto; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.web.client.RestTemplate; -@Service -@Slf4j -public class BuildRequestService { - private final Logger logger = LoggerFactory.getLogger(BuildRequestService.class); - private String token = null; - private String baseUri = "https://api.github.com"; - @Value("${build.server}") - private String buildServerUri = "http://3.38.34.254:8080"; - - public void RequestBuild(BuildRequestDto request) { - String url = buildServerUri + "/api/v1/deploy"; - request.setDockerfile(isDockerfileExist(request.user(), request.repo())); - request.setgithubToken(token); - - logger.info(request.toString()); - - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - HttpEntity httpEntity = new HttpEntity<>(request, headers); - ResponseEntity response = new RestTemplate().exchange(url, HttpMethod.POST, httpEntity, String.class); - - if (response.getStatusCode().is2xxSuccessful()) { - logger.info("response : {}", response.getBody()); - } else { - logger.error("response : {}", response.getBody()); - logger.error("response : {}", response.getStatusCode()); - } - } - - private Boolean isDockerfileExist(String userName ,String repoName) { - String url = baseUri + "/repos/" + userName + "/" + repoName + "/contents/Dockerfile"; - try { - ResponseEntity response = RequestGitHubAPIs(url); - return true; - } catch (Exception e) { - return false; - } - } - - private ResponseEntity RequestGitHubAPIs(String uri) { - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json"); - if( StringUtils.hasText(token) ) { - headers.setBearerAuth(token); - } - HttpEntity httpEntity = new HttpEntity<>(headers); - return new RestTemplate().exchange(uri, HttpMethod.GET, httpEntity, JsonNode.class); - } +public interface BuildRequestService { + public void RequestBuild(BuildRequestDto request, String oauthId); } diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestServiceImpl.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestServiceImpl.java new file mode 100644 index 0000000..f2751d6 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/BuildRequestServiceImpl.java @@ -0,0 +1,76 @@ +package com.kumofactory.cloud.appDeploy.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.kumofactory.cloud.appDeploy.dto.BuildRequestDto; +import com.kumofactory.cloud.member.MemberRepository; +import com.kumofactory.cloud.member.domain.Member; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; + +@Service +@Slf4j +@Repository +@RequiredArgsConstructor +public class BuildRequestServiceImpl implements BuildRequestService { + + private final MemberRepository memberRepository; + private final Logger logger = LoggerFactory.getLogger(BuildRequestServiceImpl.class); + private String token; + private String baseUri = "https://api.github.com"; + @Value("${build.server}") + private String buildServerUri; + + @Override + public void RequestBuild(BuildRequestDto request, String oauthId) { + Member member = memberRepository.findMemberByOauthId(oauthId); + this.token = member.getGithubAccessToken(); + String url = buildServerUri + "/api/v1/deploy"; + request.setDockerfile(isDockerfileExist(request.user(), request.repo())); + request.setgithubToken(token); + + logger.info(request.toString()); + + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + HttpEntity httpEntity = new HttpEntity<>(request, headers); + ResponseEntity response = new RestTemplate().exchange(url, HttpMethod.POST, httpEntity, String.class); + + if (response.getStatusCode().is2xxSuccessful()) { + logger.info("response : {}", response.getBody()); + } else { + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + } + } + + private Boolean isDockerfileExist(String userName ,String repoName) { + String url = baseUri + "/repos/" + userName + "/" + repoName + "/contents/Dockerfile"; + try { + ResponseEntity response = RequestGitHubAPIs(url); + return true; + } catch (Exception e) { + return false; + } + } + + private ResponseEntity RequestGitHubAPIs(String uri) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + if( StringUtils.hasText(token) ) { + headers.setBearerAuth(token); + } + HttpEntity httpEntity = new HttpEntity<>(headers); + return new RestTemplate().exchange(uri, HttpMethod.GET, httpEntity, JsonNode.class); + } +} diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoServiceImpl.java b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoServiceImpl.java new file mode 100644 index 0000000..316d668 --- /dev/null +++ b/src/main/java/com/kumofactory/cloud/appDeploy/service/UserRepoServiceImpl.java @@ -0,0 +1,166 @@ +package com.kumofactory.cloud.appDeploy.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.kumofactory.cloud.appDeploy.dto.GitHubRepoDto; +import com.kumofactory.cloud.member.MemberRepository; +import com.kumofactory.cloud.member.domain.Member; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.*; +import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; + + +import java.util.ArrayList; +import java.util.List; + +@Service +@RequiredArgsConstructor +@Slf4j +@Repository +public class UserRepoServiceImpl implements UserRepoService { + + private final Logger logger = LoggerFactory.getLogger(UserRepoService.class); + private final MemberRepository memberRepository; + + @Override + public List RequestOrgRepoInfo(String org, String oauthId) { + Member member = memberRepository.findMemberByOauthId(oauthId); + String token = member.getGithubAccessToken(); + String uri = "https://api.github.com/search/repositories?q=org:" + org; + ResponseEntity response = RequestGitHubAPIs(uri, token); + + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + + List repoInfoList = new ArrayList<>(); + + for (JsonNode node : responseBody.get("items")) { + String name = node.get("name").asText(); + String fullName = node.get("full_name").asText(); + Boolean isPrivate = node.get("private").asBoolean(); + Boolean isFork = node.get("fork").asBoolean(); + + GitHubRepoDto.RepoInfoDto repoInfo = new GitHubRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); + repoInfoList.add(repoInfo); + } + logger.info("response : {}", responseBody); + return repoInfoList; + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return null; + } + + @Override + public GitHubRepoDto.UserDto RequestUserRepoInfoAndOrgList(String oauthId) { + Member member = memberRepository.findMemberByOauthId(oauthId); + String owner = member.getProfileName(); + String token = member.getGithubAccessToken(); + List repoInfoList = listUserRepos(owner, token); + List orgList = new ArrayList<>(); + if( StringUtils.hasText(token) ) { + orgList = listOrganization(token); + } + + return new GitHubRepoDto.UserDto(repoInfoList.size(), repoInfoList, orgList.size(), orgList); + } + + private List listUserRepos(String user, String token) { + String uri = "https://api.github.com/search/repositories?q=user:" + user; + ResponseEntity response = RequestGitHubAPIs(uri, token); + + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + + List repoInfoList = new ArrayList<>(); + + for (JsonNode node : responseBody.get("items")) { + String name = node.get("name").asText(); + String fullName = node.get("full_name").asText(); + Boolean isPrivate = node.get("private").asBoolean(); + Boolean isFork = node.get("fork").asBoolean(); + + GitHubRepoDto.RepoInfoDto repoInfo = new GitHubRepoDto.RepoInfoDto(name, fullName, isPrivate, isFork); + repoInfoList.add(repoInfo); + } + logger.info("response : {}", responseBody); + return repoInfoList; + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return null; + } + + private List listOrganization(String token) { + String uri = "https://api.github.com/user/orgs"; + ResponseEntity response = RequestGitHubAPIs(uri, token); + + List organizationList = new ArrayList<>(); + + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + logger.info("response : {}", responseBody); + + if (responseBody.isArray()) { + for (JsonNode node : responseBody) { + if (node.has("login")) { + organizationList.add(node.get("login").asText()); + } + } + } + return organizationList; + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return organizationList; + } + + @Override + public List RequestRepoBranches(String org, String repo, String oauthId) { + Member member = memberRepository.findMemberByOauthId(oauthId); + String token = member.getGithubAccessToken(); + String uri = "https://api.github.com/repos/" + org + "/" + repo + "/branches"; + ResponseEntity response = RequestGitHubAPIs(uri, token); + + List branchList = new ArrayList<>(); + + if (response.getStatusCode() == HttpStatus.OK) { + JsonNode responseBody = response.getBody(); + logger.info("response : {}", responseBody); + + if (responseBody.isArray()) { + for (JsonNode node : responseBody) { + if (node.has("name")) { + branchList.add(node.get("name").asText()); + } + } + } + return branchList; + } + logger.error("response : {}", response.getBody()); + logger.error("response : {}", response.getStatusCode()); + return branchList; + } + + @Override + public List RequestRepoBranches(String repo, String oauthId) { + Member member = memberRepository.findMemberByOauthId(oauthId); + String profileName = member.getProfileName(); + return RequestRepoBranches(profileName, repo, oauthId); + } + + private ResponseEntity RequestGitHubAPIs(String uri, String token) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json"); + if( StringUtils.hasText(token) ) { + headers.setBearerAuth(token); + } + HttpEntity httpEntity = new HttpEntity<>(headers); + return new RestTemplate().exchange(uri, HttpMethod.GET, httpEntity, JsonNode.class); + } +} \ No newline at end of file From 116a187b1bbe6742dbb30165268d7c903e0611aa Mon Sep 17 00:00:00 2001 From: coding-convention Date: Thu, 10 Aug 2023 03:05:00 +0900 Subject: [PATCH 61/63] feat: store profileName and GitHubAccessToke #16 --- src/main/java/com/kumofactory/cloud/member/domain/Member.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/kumofactory/cloud/member/domain/Member.java b/src/main/java/com/kumofactory/cloud/member/domain/Member.java index 0bf5505..6a4b033 100644 --- a/src/main/java/com/kumofactory/cloud/member/domain/Member.java +++ b/src/main/java/com/kumofactory/cloud/member/domain/Member.java @@ -30,6 +30,8 @@ public class Member { private String githubAccessToken; + private String profileName; + @OneToMany(mappedBy = "member") private List bluePrints; @@ -38,6 +40,8 @@ public static Member createMember(UserInfoDto userInfoDto) { Member member = new Member(); member.setOauthId(userInfoDto.id()); member.setProvider(userInfoDto.provider()); + member.setGithubAccessToken(userInfoDto.accessToken()); + member.setProfileName(userInfoDto.profileName()); return member; } } From b0d5c1781dc8f3f505d4b530b1b169223ea64178 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Thu, 10 Aug 2023 03:05:38 +0900 Subject: [PATCH 62/63] chore: trivial thing #16 --- .../java/com/kumofactory/cloud/oauth/service/OAuthService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java b/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java index 00e0bd0..3a3248f 100644 --- a/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java +++ b/src/main/java/com/kumofactory/cloud/oauth/service/OAuthService.java @@ -76,7 +76,7 @@ public ResponseEntity request(OAuthProvider provider, String code) } public TokenDto generateTestToken() { - UserInfoDto userInfoDto = new UserInfoDto("1234", "github"); + UserInfoDto userInfoDto = new UserInfoDto("1234", "github", "access", "coding-convention"); return jwtTokenProvider.create(userInfoDto.id()); } From 06e9151574329be27ead241117ee6b61a30271c6 Mon Sep 17 00:00:00 2001 From: coding-convention Date: Thu, 10 Aug 2023 03:06:28 +0900 Subject: [PATCH 63/63] chore: find member via oauthId #16 --- .../cloud/appDeploy/AppDeployController.java | 45 ++++++++++--------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java b/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java index 8697568..cbe23f5 100644 --- a/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java +++ b/src/main/java/com/kumofactory/cloud/appDeploy/AppDeployController.java @@ -4,7 +4,9 @@ import com.kumofactory.cloud.appDeploy.dto.GitHubRepoDto; import com.kumofactory.cloud.appDeploy.service.BuildRequestService; import com.kumofactory.cloud.appDeploy.service.UserRepoService; +import com.kumofactory.cloud.global.annotation.auth.AuthorizationFromToken; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -14,38 +16,41 @@ @RestController @RequestMapping("/build") @RequiredArgsConstructor +@Slf4j public class AppDeployController { - Logger logger = org.slf4j.LoggerFactory.getLogger(AppDeployController.class); + private final Logger logger = org.slf4j.LoggerFactory.getLogger(AppDeployController.class); - private final UserRepoService userRepoService = new UserRepoService(); - private final BuildRequestService buildRequestService = new BuildRequestService(); + private final UserRepoService userRepoService; + private final BuildRequestService buildRequestService; @GetMapping("/list/{org}/repo") - public List listOrgRepo(@PathVariable String org) { - return userRepoService.RequestOrgRepoInfo(org); + @AuthorizationFromToken + public List listOrgRepo(@PathVariable String org, String userId) { + return userRepoService.RequestOrgRepoInfo(org, userId); } - @GetMapping("/list/{user}") - public GitHubRepoDto.UserDto listUserRepoAndOrgs(@PathVariable String user) { - return userRepoService.RequestUserRepoInfoAndOrgList(user); + @GetMapping("/list") + @AuthorizationFromToken + public GitHubRepoDto.UserDto listUserRepoAndOrgs(String userId) { + return userRepoService.RequestUserRepoInfoAndOrgList(userId); } - @GetMapping("/list/{owner}/{repo}/branch") - public List listRepoBranches(@PathVariable String owner, @PathVariable String repo) { - return userRepoService.RequestRepoBranches(owner, repo); + @GetMapping("/list/{org}/{repo}/branch") + @AuthorizationFromToken + public List listRepoBranches(@PathVariable String org, @PathVariable String repo, String userId) { + return userRepoService.RequestRepoBranches(org, repo, userId); } - @PostMapping("/deploy") - public ResponseEntity deployRequest(@RequestBody BuildRequestDto request) { - logger.info("request : {}", "message"); - buildRequestService.RequestBuild(request); -// logger.info("request : {}", request); - - return ResponseEntity.ok("success"); + @GetMapping("/list/{repo}/branch") + @AuthorizationFromToken + public List listRepoBranches(@PathVariable String repo, String userId) { + return userRepoService.RequestRepoBranches(repo, userId); } - @GetMapping("/health") - public ResponseEntity checkHealth() { + @PostMapping("/deploy") + @AuthorizationFromToken + public ResponseEntity deployRequest(@RequestBody BuildRequestDto request, String userId) { + buildRequestService.RequestBuild(request, userId); return ResponseEntity.ok("success"); } } \ No newline at end of file