Skip to content

Commit

Permalink
feat(sdk): added company id and name in activity log list (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
xuelianhan007 authored Nov 5, 2024
1 parent d2f5924 commit 6cccaaf
Show file tree
Hide file tree
Showing 16 changed files with 505 additions and 151 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.consoleconnect.kraken.operator.auth.dto;

import lombok.Data;

@Data
public class JwtTokenDto {
private Header header;
private Payload payload;

@Data
public static class Header {
private String kid;
private String alg;
}

@Data
public static class Payload {
private String sub;
private String iat;
private String exp;
private String iss;
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
package com.consoleconnect.kraken.operator.auth.jwt;

import com.consoleconnect.kraken.operator.auth.dto.JwtTokenDto;
import com.consoleconnect.kraken.operator.auth.model.AuthDataProperty;
import com.consoleconnect.kraken.operator.auth.security.JwtTokenVerifier;
import com.consoleconnect.kraken.operator.core.toolkit.JsonToolkit;
import com.fasterxml.jackson.core.type.TypeReference;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Optional;
import javax.crypto.spec.SecretKeySpec;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
Expand Down Expand Up @@ -64,4 +69,32 @@ public static NimbusJwtDecoder createJwtDecoderInstance(
log.info("jwtDecoderInstance created,issuer:{}", decodeConfig.getIssuer());
return nimbusJwtDecoder;
}

public static Optional<JwtTokenDto> decodeJWTToken(String tokenStr) {
if (StringUtils.isBlank(tokenStr)) {
return Optional.empty();
}
String token = tokenStr.replaceAll("^.*\\s+", "");
String[] chunks = token.split("\\.");
if (chunks.length < 2) {
return Optional.empty();
}
java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
try {
String headerStr = new String(decoder.decode(chunks[0]));
String payloadStr = new String(decoder.decode(chunks[1]));

JwtTokenDto.Header header =
JsonToolkit.fromJson(headerStr, new TypeReference<JwtTokenDto.Header>() {});
JwtTokenDto.Payload payload =
JsonToolkit.fromJson(payloadStr, new TypeReference<JwtTokenDto.Payload>() {});
JwtTokenDto jwtTokenDto = new JwtTokenDto();
jwtTokenDto.setHeader(header);
jwtTokenDto.setPayload(payload);
return Optional.of(jwtTokenDto);
} catch (Exception e) {
log.error("Failed to decode token", e);
}
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ void givenUserCreated_whenSearch_thenReturnOk() {
Assertions.assertNotNull(bodyStr);
assertThat(bodyStr, hasJsonPath("$.data.data", notNullValue()));
assertThat(bodyStr, hasJsonPath("$.data.data", hasSize(greaterThanOrEqualTo(1))));
assertThat(bodyStr, hasJsonPath("$.data.data[0].email", is("[email protected]")));
assertThat(bodyStr, hasJsonPath("$.data.data[0].email", equalTo("[email protected]")));
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.consoleconnect.kraken.operator.auth.helper;

import com.consoleconnect.kraken.operator.auth.dto.JwtTokenDto;
import com.consoleconnect.kraken.operator.auth.jwt.JwtDecoderToolkit;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

@Slf4j
class JwtDecoderToolkitTest {
public static String[] illegalDataSetForDecoding() {
return new String[] {"", " ", "xxswewwew.sssss", "xxswewwew"};
}

public static String[] legalDataSetForDecoding() {
return new String[] {
"bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXN1YmplY3QiLCJzY3AiOlsibWVzc2FnZTpyZWFkIl0sImV4cCI6NDY4Mzg5Nzc3Nn0.LtMVtIiRIwSyc3aX35Zl0JVwLTcQZAB3dyBOMHNaHCKUljwMrf20a_gT79LfhjDzE_fUVUmFiAO32W1vFnYpZSVaMDUgeIOIOpxfoe9shj_uYenAwIS-_UxqGVIJiJoXNZh_MK80ShNpvsQwamxWEEOAMBtpWNiVYNDMdfgho9n3o5_Z7Gjy8RLBo1tbDREbO9kTFwGIxm_EYpezmRCRq4w1DdS6UDW321hkwMxPnCMSWOvp-hRpmgY2yjzLgPJ6Aucmg9TJ8jloAP1DjJoF1gRR7NTAk8LOGkSjTzVYDYMbCF51YdpojhItSk80YzXiEsv1mTz4oMM49jXBmfXFMA",
"bearer eyJhbGciOiJSUzUxMiJ9.eyJzdWIiOiJ0ZXN0LXN1YmplY3QiLCJleHAiOjE5NzQzMjYxMTl9.LKAx-60EBfD7jC1jb1eKcjO4uLvf3ssISV-8tN-qp7gAjSvKvj4YA9-V2mIb6jcS1X_xGmNy6EIimZXpWaBR3nJmeu-jpe85u4WaW2Ztr8ecAi-dTO7ZozwdtljKuBKKvj4u1nF70zyCNl15AozSG0W1ASrjUuWrJtfyDG6WoZ8VfNMuhtU-xUYUFvscmeZKUYQcJ1KS-oV5tHeF8aNiwQoiPC_9KXCOZtNEJFdq6-uzFdHxvOP2yex5Gbmg5hXonauIFXG2ZPPGdXzm-5xkhBpgM8U7A_6wb3So8wBvLYYm2245QUump63AJRAy8tQpwt4n9MvQxQgS3z9R-NK92A"
};
}

@ParameterizedTest
@MethodSource(value = "illegalDataSetForDecoding")
void givenIllegalToken_whenDecode_thenReturnEmpty(String token) {
Optional<JwtTokenDto> result = JwtDecoderToolkit.decodeJWTToken(token);
Assertions.assertTrue(result.isEmpty());
}

@ParameterizedTest
@MethodSource(value = "legalDataSetForDecoding")
void givenLegalJwtToken_whenDecode_thenReturnOK(String token) {
Optional<JwtTokenDto> result = JwtDecoderToolkit.decodeJWTToken(token);
Assertions.assertTrue(result.isPresent());
Assertions.assertNotNull(result.get().getHeader());
Assertions.assertNotNull(result.get().getPayload());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public BuyerAssetDto create(String productId, CreateBuyerRequest buyerOnboard, S
PRODUCT_BUYER.getKind(),
buyerOnboard.getEnvId(),
buyerOnboard.getBuyerId(),
AssetStatusEnum.ACTIVATED.getKind(),
null,
null,
PageRequest.of(0, 1));
if (CollectionUtils.isNotEmpty(exist.getContent())) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.consoleconnect.kraken.operator.controller;

import com.consoleconnect.kraken.operator.core.entity.ApiActivityLogEntity;
import com.consoleconnect.kraken.operator.core.repo.ApiActivityLogRepository;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.UUID;

public interface ApiActivityLogCreator {

ApiActivityLogRepository getApiActivityLogRepository();

default ApiActivityLogEntity createApiActivityLog(String buyerId, String envId) {
ApiActivityLogEntity apiActivityLogEntity = new ApiActivityLogEntity();
apiActivityLogEntity.setRequestId(UUID.randomUUID().toString());
apiActivityLogEntity.setPath("/123");
apiActivityLogEntity.setUri("localhost");
apiActivityLogEntity.setMethod("GET");
apiActivityLogEntity.setEnv(envId);
Map<String, String> headers = Maps.newHashMap();
headers.put("acces_token", "2334");
apiActivityLogEntity.setHeaders(headers);
apiActivityLogEntity.setBuyer(buyerId);
apiActivityLogEntity.setCallSeq(0);
apiActivityLogEntity = getApiActivityLogRepository().save(apiActivityLogEntity);
return apiActivityLogEntity;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
import com.consoleconnect.kraken.operator.config.TestApplication;
import com.consoleconnect.kraken.operator.controller.dto.BuyerAssetDto;
import com.consoleconnect.kraken.operator.controller.dto.CreateBuyerRequest;
import com.consoleconnect.kraken.operator.controller.model.Environment;
import com.consoleconnect.kraken.operator.controller.service.EnvironmentService;
import com.consoleconnect.kraken.operator.core.dto.Tuple2;
import com.consoleconnect.kraken.operator.core.dto.UnifiedAssetDto;
import com.consoleconnect.kraken.operator.core.enums.AssetKindEnum;
import com.consoleconnect.kraken.operator.core.model.HttpResponse;
import com.consoleconnect.kraken.operator.core.service.UnifiedAssetService;
import com.consoleconnect.kraken.operator.core.toolkit.AssetsConstants;
import com.consoleconnect.kraken.operator.core.toolkit.JsonToolkit;
import com.consoleconnect.kraken.operator.core.toolkit.LabelConstants;
import com.consoleconnect.kraken.operator.test.AbstractIntegrationTest;
import com.consoleconnect.kraken.operator.test.MockIntegrationTest;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.MethodOrderer;
Expand All @@ -36,13 +36,11 @@
@ContextConfiguration(classes = {TestApplication.class})
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ActiveProfiles("test-rs256")
class BuyerControllerTest extends AbstractIntegrationTest {
private static final String PRODUCT_ID = "product.mef.sonata.api";
public static final String BASE_URL = String.format("/products/%s/buyers", PRODUCT_ID);
public static final String BUYER_ID = "consolecore-poping-company";
class BuyerControllerTest extends AbstractIntegrationTest implements EnvCreator, BuyerCreator {

private final WebTestClientHelper webTestClient;
@Getter private final WebTestClientHelper webTestClient;
@Autowired private UnifiedAssetService unifiedAssetService;
@Getter @Autowired EnvironmentService environmentService;

@Autowired
public BuyerControllerTest(WebTestClient webTestClient) {
Expand All @@ -52,26 +50,9 @@ public BuyerControllerTest(WebTestClient webTestClient) {
@Test
@Order(2)
void givenBuyer_whenCreate_thenOK() {
CreateBuyerRequest requestEntity = new CreateBuyerRequest();
requestEntity.setBuyerId(BUYER_ID);
requestEntity.setEnvId("stage");
requestEntity.setCompanyName("console connect");

String resp =
webTestClient.requestAndVerify(
HttpMethod.POST,
uriBuilder -> uriBuilder.path(BASE_URL).build(),
HttpStatus.OK.value(),
requestEntity,
bodyStr -> {
assertThat(bodyStr, hasJsonPath("$.data", notNullValue()));
assertThat(bodyStr, hasJsonPath("$.data.buyerToken", notNullValue()));
assertThat(bodyStr, hasJsonPath("$.data.buyerToken.accessToken", notNullValue()));
});
HttpResponse<BuyerAssetDto> buyerCreatedResp =
JsonToolkit.fromJson(resp, new TypeReference<HttpResponse<BuyerAssetDto>>() {});
BuyerAssetDto buyerCreated = buyerCreatedResp.getData();
String refreshAccessTokenUrl = BASE_URL + "/" + buyerCreated.getId() + "/access-tokens";
Environment envStage = createStage(PRODUCT_ID);
BuyerAssetDto buyerCreated = createBuyer(BUYER_ID, envStage.getId(), COMPANY_NAME);
String refreshAccessTokenUrl = BUYER_BASE_URL + "/" + buyerCreated.getId() + "/access-tokens";
webTestClient.requestAndVerify(
HttpMethod.POST,
uriBuilder ->
Expand All @@ -93,7 +74,7 @@ void givenBuyer_whenCreate_thenOK() {
void givenBuyer_whenSearch_thenOK() {
webTestClient.requestAndVerify(
HttpMethod.GET,
uriBuilder -> uriBuilder.path(BASE_URL).build(),
uriBuilder -> uriBuilder.path(BUYER_BASE_URL).build(),
HttpStatus.OK.value(),
null,
bodyStr -> {
Expand All @@ -107,15 +88,17 @@ void givenBuyer_whenSearch_thenOK() {
void givenDuplicatedBuyer_whenCreate_thenNot200() {
CreateBuyerRequest requestEntity = new CreateBuyerRequest();
requestEntity.setBuyerId(BUYER_ID);
requestEntity.setEnvId("stage");
Environment envStage = createStage(PRODUCT_ID);
requestEntity.setEnvId(envStage.getId());
requestEntity.setCompanyName("console connect");

webTestClient.requestAndVerify(
HttpMethod.POST,
uriBuilder -> uriBuilder.path(BASE_URL).build(),
uriBuilder -> uriBuilder.path(BUYER_BASE_URL).build(),
HttpStatus.BAD_REQUEST.value(),
requestEntity,
bodyStr -> {
log.info(bodyStr);
assertThat(bodyStr, hasJsonPath("$.code", not(200)));
});
}
Expand All @@ -129,7 +112,7 @@ void givenBlankBuyer_whenCreate_thenNot200() {
requestEntity.setCompanyName("console connect");
webTestClient.requestAndVerify(
HttpMethod.POST,
uriBuilder -> uriBuilder.path(BASE_URL).build(),
uriBuilder -> uriBuilder.path(BUYER_BASE_URL).build(),
HttpStatus.BAD_REQUEST.value(),
requestEntity,
bodyStr -> {
Expand All @@ -146,7 +129,7 @@ void givenBlankEnv_whenCreateBuyer_thenNot200() {
requestEntity.setCompanyName("console connect");
webTestClient.requestAndVerify(
HttpMethod.POST,
uriBuilder -> uriBuilder.path(BASE_URL).build(),
uriBuilder -> uriBuilder.path(BUYER_BASE_URL).build(),
HttpStatus.BAD_REQUEST.value(),
requestEntity,
bodyStr -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.consoleconnect.kraken.operator.controller;

import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;

import com.consoleconnect.kraken.operator.controller.dto.BuyerAssetDto;
import com.consoleconnect.kraken.operator.controller.dto.CreateBuyerRequest;
import com.consoleconnect.kraken.operator.core.model.HttpResponse;
import com.consoleconnect.kraken.operator.core.toolkit.JsonToolkit;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

public interface BuyerCreator {
String PRODUCT_ID = "product.mef.sonata.api";
String BUYER_BASE_URL = String.format("/products/%s/buyers", PRODUCT_ID);
String BUYER_ID = "testing-company";
String COMPANY_NAME = "testing-company-name";

WebTestClientHelper getWebTestClient();

default BuyerAssetDto createBuyer(String buyerId, String envId, String companyName) {
CreateBuyerRequest requestEntity = new CreateBuyerRequest();
requestEntity.setBuyerId(buyerId);
requestEntity.setEnvId(envId);
requestEntity.setCompanyName(companyName);

String resp =
getWebTestClient()
.requestAndVerify(
HttpMethod.POST,
uriBuilder -> uriBuilder.path(BUYER_BASE_URL).build(),
HttpStatus.OK.value(),
requestEntity,
bodyStr -> {
assertThat(bodyStr, hasJsonPath("$.data", notNullValue()));
assertThat(bodyStr, hasJsonPath("$.data.buyerToken", notNullValue()));
assertThat(bodyStr, hasJsonPath("$.data.buyerToken.accessToken", notNullValue()));
});
HttpResponse<BuyerAssetDto> buyerCreatedResp =
JsonToolkit.fromJson(resp, new TypeReference<HttpResponse<BuyerAssetDto>>() {});
return buyerCreatedResp.getData();
}
}
Loading

0 comments on commit 6cccaaf

Please sign in to comment.