Skip to content

Commit

Permalink
MOSIP-32692: created new service and controller for new API (#676)
Browse files Browse the repository at this point in the history
* MOSIP-32692: created new service and controller for new API

Signed-off-by: SwethaKrish4 <[email protected]>

* MOSIP-32692: created new service and controller for new API

Signed-off-by: SwethaKrish4 <[email protected]>

* MOSIP-32692: created new service and controller for new API

Signed-off-by: SwethaKrish4 <[email protected]>

* MOSIP-32692: created new service and controller for new API

Signed-off-by: SwethaKrish4 <[email protected]>

---------

Signed-off-by: SwethaKrish4 <[email protected]>
  • Loading branch information
SwethaKrish4 authored May 21, 2024
1 parent 00f7b56 commit d67bb5c
Show file tree
Hide file tree
Showing 8 changed files with 281 additions and 159 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package io.mosip.pms.partner.controller;

import io.mosip.pms.common.response.dto.ResponseWrapper;
import io.mosip.pms.partner.dto.CertificateDto;
import io.mosip.pms.partner.service.MultiPartnerService;
import io.swagger.annotations.Api;
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.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/partners")
@Api(tags = { "All Partner Service Controller" })
public class MultiPartnerServiceController {

@Autowired
MultiPartnerService allPartnerService;

@GetMapping(value = "/getAllCertificateDetails")
@Operation(summary = "Get partner certificates", description = "fetch partner certificates")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true)))})
public ResponseWrapper<List<CertificateDto>> getAllCertificateDetails() {
ResponseWrapper<List<CertificateDto>> responseWrapper = new ResponseWrapper<>();
responseWrapper.setResponse(allPartnerService.getAllCertificateDetails());
return responseWrapper;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -471,17 +471,4 @@ public ResponseEntity<ResponseWrapper<APIKeyGenerateResponseDto>> generateAPIKey
response.setVersion(request.getVersion());
return new ResponseEntity<>(response, HttpStatus.OK);
}

@GetMapping(value = "/getAllCertificateDetails")
@Operation(summary = "Get partner certificates", description = "fetch partner certificates")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true)))})
public ResponseWrapper<List<CertificateDto>> getAllCertificateDetails() {
ResponseWrapper<List<CertificateDto>> responseWrapper = new ResponseWrapper<>();
responseWrapper.setResponse(partnerService.getAllCertificateDetails());
return responseWrapper;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package io.mosip.pms.partner.service;

import io.mosip.pms.partner.dto.CertificateDto;

import java.util.List;

public interface MultiPartnerService {

public List<CertificateDto> getAllCertificateDetails();
}
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,4 @@ public interface PartnerService {
*/
public PartnerResponse registerPartner(PartnerRequestDto request);

/**
* @return
*/
public List<CertificateDto> getAllCertificateDetails();

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package io.mosip.pms.partner.service.impl;

import io.mosip.kernel.core.authmanager.authadapter.model.AuthUserDetails;
import io.mosip.kernel.core.logger.spi.Logger;
import io.mosip.pms.common.entity.Partner;
import io.mosip.pms.common.repository.PartnerServiceRepository;
import io.mosip.pms.common.util.PMSLogger;
import io.mosip.pms.partner.constant.ErrorCode;
import io.mosip.pms.partner.dto.CertificateDto;
import io.mosip.pms.partner.exception.PartnerServiceException;
import io.mosip.pms.partner.request.dto.PartnerCertDownloadRequestDto;
import io.mosip.pms.partner.response.dto.PartnerCertDownloadResponeDto;
import io.mosip.pms.partner.service.MultiPartnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

@Service
public class MultiPartnerServiceImpl implements MultiPartnerService {

private static final Logger LOGGER = PMSLogger.getLogger(MultiPartnerServiceImpl.class);
public static final String BLANK_STRING="";
private static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----";
private static final String END_CERTIFICATE = "-----END CERTIFICATE-----";
@Autowired
PartnerServiceRepository partnerRepository;

@Autowired
PartnerServiceImpl partnerServiceImpl;

@Override
public List<CertificateDto> getAllCertificateDetails() {
List<CertificateDto> certificateDtoList = new ArrayList<>();
try {
String userId = getUserId();
List<Partner> partnerList = partnerRepository.findByUserId(userId);
if (!partnerList.isEmpty()) {
for (Partner partner : partnerList) {
CertificateDto certificateDto = new CertificateDto();
try {
if (Objects.isNull(partner.getId()) || partner.getId().equals(BLANK_STRING)) {
LOGGER.info("Partner Id is null or empty for user id : " + userId);
throw new PartnerServiceException(ErrorCode.PARTNER_ID_NOT_EXISTS.getErrorCode(),
ErrorCode.PARTNER_ID_NOT_EXISTS.getErrorMessage());
}
PartnerCertDownloadRequestDto requestDto = new PartnerCertDownloadRequestDto();
requestDto.setPartnerId(partner.getId());
PartnerCertDownloadResponeDto partnerCertDownloadResponeDto = partnerServiceImpl.getPartnerCertificate(requestDto);
String certificateData = partnerCertDownloadResponeDto.getCertificateData();
certificateData = certificateData.replaceAll(BEGIN_CERTIFICATE, "")
.replaceAll(END_CERTIFICATE, "")
.replaceAll("\n", "");

byte[] decodedCertificate = Base64.getDecoder().decode(certificateData);

CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(decodedCertificate));

certificateDto.setIsCertificateAvailable(true);
certificateDto.setCertificateName(getCertificateName(cert.getSubjectDN().getName()));
certificateDto.setCertificateUploadDate(cert.getNotBefore());
certificateDto.setCertificateExpiryDate(cert.getNotAfter());
certificateDto.setPartnerId(partner.getId());
certificateDto.setPartnerType(partner.getPartnerTypeCode());
} catch (PartnerServiceException ex) {
LOGGER.info("Could not fetch partner certificate :" + ex.getMessage());
certificateDto.setIsCertificateAvailable(false);
certificateDto.setPartnerId(partner.getId());
certificateDto.setPartnerType(partner.getPartnerTypeCode());
}
certificateDtoList.add(certificateDto);
}
} else {
LOGGER.info("sessionId", "idType", "id", "User id does not exists.");
throw new PartnerServiceException(ErrorCode.USER_ID_NOT_EXISTS.getErrorCode(),
ErrorCode.USER_ID_NOT_EXISTS.getErrorMessage());
}
} catch (PartnerServiceException ex) {
LOGGER.info("sessionId", "idType", "id", "In getAllCertificateDetails method of AllPartnerServiceImpl - " + ex.getMessage());
throw ex;
} catch (Exception ex) {
LOGGER.debug("sessionId", "idType", "id", ex.getStackTrace());
LOGGER.error("sessionId", "idType", "id",
"In getAllCertificateDetails method of AllPartnerServiceImpl - " + ex.getMessage());
throw new PartnerServiceException(ErrorCode.PARTNER_CERTIFICATES_FETCH_ERROR.getErrorCode(),
ErrorCode.PARTNER_CERTIFICATES_FETCH_ERROR.getErrorMessage());
}
return certificateDtoList;
}

private AuthUserDetails authUserDetails() {
return (AuthUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

private String getUserId() {
String userId = authUserDetails().getUserId();
return userId;
}

public static String getCertificateName(String subjectDN) {
String[] parts = subjectDN.split(",");
for (String part : parts) {
if (part.trim().startsWith("CN=")) {
return part.trim().substring(3);
}
}
return BLANK_STRING;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1630,66 +1630,6 @@ public PartnerResponse updatePartnerDetail(PartnerUpdateRequest partnerUpdateReq
return updatePartnerDetails(updateRequest, partnerId);
}

@Override
public List<CertificateDto> getAllCertificateDetails() {
List<CertificateDto> certificateDtoList = new ArrayList<>();
try {
String userId = getUserId();
List<Partner> partnerList = partnerRepository.findByUserId(userId);
if (!partnerList.isEmpty()) {
for (Partner partner : partnerList) {
CertificateDto certificateDto = new CertificateDto();
try {
if (Objects.isNull(partner.getId()) || partner.getId().equals(BLANK_STRING)) {
LOGGER.info("Partner Id is null or empty for user id : " + userId);
throw new PartnerServiceException(ErrorCode.PARTNER_ID_NOT_EXISTS.getErrorCode(),
ErrorCode.PARTNER_ID_NOT_EXISTS.getErrorMessage());
}
PartnerCertDownloadRequestDto requestDto = new PartnerCertDownloadRequestDto();
requestDto.setPartnerId(partner.getId());
PartnerCertDownloadResponeDto partnerCertDownloadResponeDto = getPartnerCertificate(requestDto);
String certificateData = partnerCertDownloadResponeDto.getCertificateData();
certificateData = certificateData.replaceAll(BEGIN_CERTIFICATE, "")
.replaceAll(END_CERTIFICATE, "")
.replaceAll("\n", "");

byte[] decodedCertificate = Base64.getDecoder().decode(certificateData);

CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(decodedCertificate));

certificateDto.setIsCertificateAvailable(true);
certificateDto.setCertificateName(getCertificateName(cert.getSubjectDN().getName()));
certificateDto.setCertificateUploadDate(cert.getNotBefore());
certificateDto.setCertificateExpiryDate(cert.getNotAfter());
certificateDto.setPartnerId(partner.getId());
certificateDto.setPartnerType(partner.getPartnerTypeCode());
} catch (PartnerServiceException ex) {
LOGGER.info("Could not fetch partner certificate :" + ex.getMessage());
certificateDto.setIsCertificateAvailable(false);
certificateDto.setPartnerId(partner.getId());
certificateDto.setPartnerType(partner.getPartnerTypeCode());
}
certificateDtoList.add(certificateDto);
}
} else {
LOGGER.info("sessionId", "idType", "id", "User id does not exists.");
throw new PartnerServiceException(ErrorCode.USER_ID_NOT_EXISTS.getErrorCode(),
ErrorCode.USER_ID_NOT_EXISTS.getErrorMessage());
}
} catch (PartnerServiceException ex) {
LOGGER.info("sessionId", "idType", "id", "In getAllCertificateDetails method of PartnerServiceImpl - " + ex.getMessage());
throw ex;
} catch (Exception ex) {
LOGGER.debug("sessionId", "idType", "id", ex.getStackTrace());
LOGGER.error("sessionId", "idType", "id",
"In getAllCertificateDetails method of PartnerServiceImpl - " + ex.getMessage());
throw new PartnerServiceException(ErrorCode.PARTNER_CERTIFICATES_FETCH_ERROR.getErrorCode(),
ErrorCode.PARTNER_CERTIFICATES_FETCH_ERROR.getErrorMessage());
}
return certificateDtoList;
}

private AuthUserDetails authUserDetails() {
return (AuthUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package io.mosip.pms.test.partner.service.impl;

import io.mosip.kernel.openid.bridge.model.AuthUserDetails;
import io.mosip.pms.common.entity.Partner;
import io.mosip.pms.common.repository.PartnerServiceRepository;
import io.mosip.pms.common.util.RestUtil;
import io.mosip.pms.partner.exception.PartnerServiceException;
import io.mosip.pms.partner.service.impl.MultiPartnerServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;

import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MultiPartnerServiceImplTest {

@Autowired
MultiPartnerServiceImpl allPartnerServiceImpl;

@MockBean
RestUtil restUtil;

@MockBean
PartnerServiceRepository partnerRepository;

@Mock
Environment environment;
@Mock
Authentication authentication;
@Mock
SecurityContext securityContext;

@Test
public void getPartnerCertificatesTest() throws Exception {

List<Partner> partnerList = new ArrayList<>();
Partner partner = new Partner();
partner.setId("123");
partner.setCertificateAlias("abs");
partnerList.add(partner);
when(partnerRepository.findByUserId(anyString())).thenReturn(partnerList);
when(partnerRepository.findById(anyString())).thenReturn(Optional.of(partner));

io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = getMosipUserDto();
AuthUserDetails authUserDetails = new AuthUserDetails(mosipUserDto, "123");
SecurityContextHolder.setContext(securityContext);
when(authentication.getPrincipal()).thenReturn(authUserDetails);
when(securityContext.getAuthentication()).thenReturn(authentication);

Map<String, Object> apiResponse = new HashMap<>();
Map<String, Object> response = new HashMap<>();
response.put("certificateData", "-----BEGIN CERTIFICATE-----\n" +
"MIIFfTCCA2WgAwIBAgIUOVZNyD46U0OAEhaGC/Y7NXbu+OkwDQYJKoZIhvcNAQEL\n" +
"BQAwTjELMAkGA1UEBhMCSU4xCzAJBgNVBAgMAk1IMQswCQYDVQQHDAJQTjELMAkG\n" +
"A1UECgwCQ0ExCzAJBgNVBAsMAkNBMQswCQYDVQQDDAJDQTAeFw0yNDA1MDkwNzI1\n" +
"MDJaFw0yOTA1MDkwNzI1MDJaME4xCzAJBgNVBAYTAklOMQswCQYDVQQIDAJNSDEL\n" +
"MAkGA1UEBwwCUE4xCzAJBgNVBAoMAkNBMQswCQYDVQQLDAJDQTELMAkGA1UEAwwC\n" +
"Q0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCzdWD2DvhSnmLqU3fX\n" +
"RT3z8ikS6qHxn5Hu/a2ijkuZxAZj0UCUJ83kM20NwocJDHT1qx6+yjdl+BECsgoI\n" +
"ro9MXgFOsHCphyR5KiP4mY95qRlE03h7WBfr4wDn/6f5tCbqC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
"yho1LKRZx5YtSeI4FWs8dzZ0nCCiTe7TrnnhlXThJ6rXeo5AshtM4fGrvizaf4n3\n" +
"7I9mJkqiccp1ml+2EcgsdX7HbnGE/R8VVbh3jUhWHuysLCiVSMbjnktCLWoXjSb9\n" +
"JqOYF3yo6JQslQB0fQMyKmvsn/FplQBbU0PUrg9vpAg9nZlZf3UHO5z072pXD6ky\n" +
"5pKjh+q0JOk00Eln9AoU6YuIyPBQ9mI3X8iYB5UhUBbgAPeg1pwWCWhdt40f0D5t\n" +
"JkVnICy+Gh1ps8QPA6coEaajbIq14Uh6eYEwxFHPsxlbn7pzjoCJG2v7N8VwgfuL\n" +
"DdGs4hFikdUAfBT/Diug/n9/ZgfdN6Ctf4U/SM65vZvfRqtLIoTIs4PcF3YtKK04\n" +
"m0UA3Sxxre0vVWYO4GmmZUY=\n" +
"-----END CERTIFICATE-----");
apiResponse.put("response", response);

when(environment.getProperty("pmp.partner.certificaticate.get.rest.uri")).thenReturn("uri");
when(restUtil.getApi(anyString(), any(), eq(Map.class))).thenReturn(apiResponse);
allPartnerServiceImpl.getAllCertificateDetails();
}

@Test(expected = PartnerServiceException.class)
public void getPartnerCertificatesTestException() throws Exception {
allPartnerServiceImpl.getAllCertificateDetails();
}

private io.mosip.kernel.openid.bridge.model.MosipUserDto getMosipUserDto() {
io.mosip.kernel.openid.bridge.model.MosipUserDto mosipUserDto = new io.mosip.kernel.openid.bridge.model.MosipUserDto();
mosipUserDto.setUserId("123");
mosipUserDto.setMail("[email protected]");
return mosipUserDto;
}
}
Loading

0 comments on commit d67bb5c

Please sign in to comment.