diff --git a/.github/workflows/manual_push_trigger.yml b/.github/workflows/manual_push_trigger.yml new file mode 100644 index 00000000..9ff18054 --- /dev/null +++ b/.github/workflows/manual_push_trigger.yml @@ -0,0 +1,75 @@ +name: Cardprinter trigger for maven install + +on: workflow_dispatch + +jobs: + build: + + runs-on: ubuntu-latest + env: + NAMESPACE: ${{ secrets.dev_namespace_docker_hub }} + SERVICE_NAME: msp-print-service + SERVICE_LOCATION: msp-print-service + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + ref: ${{ github.ref }} + java-version: 11 + server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml + settings-path: ${{ github.workspace }} # location for the settings.xml file + - name: Setup branch and env + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + echo "GPG_TTY=$(tty)" >> $GITHUB_ENV + + - name: Setup branch and GPG public key + run: | + # Strip git ref prefix from version + echo ${{ env.BRANCH_NAME }} + echo ${{ env.GPG_TTY }} + sudo apt-get --yes install gnupg2 +# gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg +# gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg + + - uses: actions/cache@v1 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} + + - name: Setup the settings file for ossrh server + run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml + + + - name: Build with Maven + run: | + mvn clean install -U -s $GITHUB_WORKSPACE/settings.xml -DskipTests -Dgpg.skip=true --file pom.xml + + - name: Removing target jars + run: | + rm -rf $(find -name '*.jar' ! -executable -type f) + + - name: Build image + run: | + docker build . --file Dockerfile --tag ${{ env.SERVICE_NAME }} + + - name: Log into registry + run: echo "${{ secrets.release_docker_hub }}" | docker login -u ${{ secrets.actor_docker_hub }} --password-stdin + + - name: Push image + run: | + IMAGE_ID=$NAMESPACE/$SERVICE_NAME + + # Change all uppercase to lowercase + IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]') + echo "push version ${{steps.getPomVersion.outputs.info}}" + VERSION=$BRANCH_NAME + echo IMAGE_ID=$IMAGE_ID + echo VERSION=$VERSION + docker tag $SERVICE_NAME $IMAGE_ID:$VERSION + docker push $IMAGE_ID:$VERSION \ No newline at end of file diff --git a/.github/workflows/release_changes.yml b/.github/workflows/release_changes.yml index cc9c2956..5d8e1a32 100644 --- a/.github/workflows/release_changes.yml +++ b/.github/workflows/release_changes.yml @@ -27,6 +27,11 @@ jobs: echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV echo "GPG_TTY=$(tty)" >> $GITHUB_ENV + - name: update Branch name in badges + run: | + sed -i 's/branch=.*)]/branch=${{ env.BRANCH_NAME }}\)]/g' README.md + sed -i 's/branch=.*\&/branch=${{ env.BRANCH_NAME }}\&/g' README.md + - name: Mannualy changing the pom versions run: find . -type f -name "*pom.xml" -print0 | xargs -0 sed -i "s/${{ github.event.inputs.snapshotTags }}/${{ github.event.inputs.releaseTags }}/g" @@ -48,7 +53,7 @@ jobs: uses: peter-evans/create-pull-request@v3 with: token: ${{ secrets.ACTION_PAT }} - commit-message: Updated Pom versions for release changes + commit-message: Release Bot Pre-release changes title: Release changes body: Automated PR for ${{ github.event.inputs.releaseTags }} release. branch: release-branch diff --git a/.github/workflows/tag.yaml b/.github/workflows/tag.yaml new file mode 100644 index 00000000..e9bba0e6 --- /dev/null +++ b/.github/workflows/tag.yaml @@ -0,0 +1,43 @@ +name: Tagging of repos + +env: + tag: v1.2.3 + +on: + workflow_dispatch: + inputs: + tag: + description: 'Tag to be published' + required: true + default: 'v1.2.3' + type: string + body: + description: 'Release body message' + required: true + default: 'Changes in this Release' + type: string + pre-release: + description: 'Pre-release? True/False' + required: true + default: False + type: string + +jobs: + build: + name: Create Release + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token + with: + tag_name: ${{ github.event.inputs.tag }} + release_name: ${{ github.event.inputs.tag }} + body: | + ${{ github.event.inputs.body }} + draft: false + prerelease: ${{fromJSON(github.event.inputs.pre-release)}} diff --git a/pom.xml b/pom.xml index 46c58152..0749d45f 100644 --- a/pom.xml +++ b/pom.xml @@ -40,6 +40,7 @@ 1.4.2 2.8.4 1.2.0.1-SNAPSHOT + 1.2.0.1-SNAPSHOT 7.1.0 2.0.0 5.5.13 @@ -50,6 +51,7 @@ 1.66 3.8.1 3.3.3 + 42.2.2 @@ -208,7 +210,16 @@ kernel-websubclient-api ${kernel.websub.version} - + + io.mosip.kernel + kernel-auth-adapter + ${project.version} + + + io.mosip.kernel + kernel-dataaccess-hibernate + ${kernel.dataaccess.version} + com.fasterxml.jackson.core jackson-core @@ -234,6 +245,11 @@ ld-signatures-java 0.8.0 + + org.postgresql + postgresql + ${postgresql.version} + @@ -255,6 +271,10 @@ false + + danubetech-maven-public + https://repo.danubetech.com/repository/maven-public/ + diff --git a/src/main/java/io/mosip/print/PrintPDFApplication.java b/src/main/java/io/mosip/print/PrintPDFApplication.java index 31f72703..8cebd3b2 100644 --- a/src/main/java/io/mosip/print/PrintPDFApplication.java +++ b/src/main/java/io/mosip/print/PrintPDFApplication.java @@ -5,6 +5,7 @@ import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.scheduling.annotation.EnableAsync; @@ -14,10 +15,13 @@ import io.mosip.print.service.impl.CbeffImpl; import io.mosip.print.spi.CbeffUtil; - -@SpringBootApplication(scanBasePackages = { "io.mosip.print.*", "${mosip.auth.adapter.impl.basepackage}" }, exclude = { DataSourceAutoConfiguration.class, +@SpringBootApplication(scanBasePackages = { "io.mosip.print.*", "${mosip.auth.adapter.impl.basepackage}" }, exclude = { SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, CacheAutoConfiguration.class }) +// +//@SpringBootApplication(scanBasePackages = { "io.mosip.print.*", "${mosip.auth.adapter.impl.basepackage}" }, exclude = { DataSourceAutoConfiguration.class, +// HibernateJpaAutoConfiguration.class, +// CacheAutoConfiguration.class }) @EnableScheduling @EnableAsync public class PrintPDFApplication { diff --git a/src/main/java/io/mosip/print/constant/ApiName.java b/src/main/java/io/mosip/print/constant/ApiName.java index 13c9c477..2e9673fa 100644 --- a/src/main/java/io/mosip/print/constant/ApiName.java +++ b/src/main/java/io/mosip/print/constant/ApiName.java @@ -100,6 +100,9 @@ public enum ApiName { NGINXDMZURL, IDSCHEMAURL, + CREDENTIALDATAREQUEST, + CREDENTIALDATAREQUESTGENERATOR, + EMAIL_NOTIFICATION } diff --git a/src/main/java/io/mosip/print/controller/Print.java b/src/main/java/io/mosip/print/controller/Print.java index 25ad78de..93174aa2 100644 --- a/src/main/java/io/mosip/print/controller/Print.java +++ b/src/main/java/io/mosip/print/controller/Print.java @@ -38,7 +38,7 @@ public class Print { * @throws Exception */ @PostMapping(path = "/callback/notifyPrint", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - @PreAuthenticateContentAndVerifyIntent(secret = "${mosip.event.secret}", callback = "/v1/print/print/callback/notifyPrint", topic = "${mosip.event.topic}") + @PreAuthenticateContentAndVerifyIntent(secret = "${mosip.event.secret}", callback = "/v1/cardprint/print/callback/notifyPrint", topic = "${mosip.event.topic}") public ResponseEntity handleSubscribeEvent(@RequestBody EventModel eventModel) throws Exception { printLogger.info("event recieved from websub"+", id: {}",eventModel.getEvent().getId()); boolean isPrinted = printService.generateCard(eventModel); diff --git a/src/main/java/io/mosip/print/dto/Errors.java b/src/main/java/io/mosip/print/dto/Errors.java index b3fd2909..cce68093 100644 --- a/src/main/java/io/mosip/print/dto/Errors.java +++ b/src/main/java/io/mosip/print/dto/Errors.java @@ -1,12 +1,12 @@ package io.mosip.print.dto; -import lombok.Data; -import lombok.Getter; -import lombok.Setter; +import lombok.*; @Data @Getter @Setter +@AllArgsConstructor +@NoArgsConstructor public class Errors { String errorCode; String message; diff --git a/src/main/java/io/mosip/print/dto/PDFSignatureRequestDto.java b/src/main/java/io/mosip/print/dto/PDFSignatureRequestDto.java index c64b2636..e92082fb 100644 --- a/src/main/java/io/mosip/print/dto/PDFSignatureRequestDto.java +++ b/src/main/java/io/mosip/print/dto/PDFSignatureRequestDto.java @@ -1,11 +1,6 @@ package io.mosip.print.dto; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; - import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/main/java/io/mosip/print/dto/PrintRequest.java b/src/main/java/io/mosip/print/dto/PrintRequest.java index a36942cc..a91f8c59 100644 --- a/src/main/java/io/mosip/print/dto/PrintRequest.java +++ b/src/main/java/io/mosip/print/dto/PrintRequest.java @@ -1,6 +1,5 @@ package io.mosip.print.dto; -import io.mosip.print.dto.BaseRestRequestDTO; import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/main/java/io/mosip/print/dto/VidResponseDTO.java b/src/main/java/io/mosip/print/dto/VidResponseDTO.java index c6378012..36d57b96 100644 --- a/src/main/java/io/mosip/print/dto/VidResponseDTO.java +++ b/src/main/java/io/mosip/print/dto/VidResponseDTO.java @@ -3,8 +3,6 @@ import java.io.Serializable; import java.util.List; -import io.mosip.print.dto.BaseRestResponseDTO; -import io.mosip.print.dto.ErrorDTO; import lombok.Data; @Data diff --git a/src/main/java/io/mosip/print/entity/BiometricRecord.java b/src/main/java/io/mosip/print/entity/BiometricRecord.java index 87b6b6d2..da3316ed 100644 --- a/src/main/java/io/mosip/print/entity/BiometricRecord.java +++ b/src/main/java/io/mosip/print/entity/BiometricRecord.java @@ -7,12 +7,6 @@ import java.util.ArrayList; import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - import lombok.Data; diff --git a/src/main/java/io/mosip/print/entity/MspCardEntity.java b/src/main/java/io/mosip/print/entity/MspCardEntity.java new file mode 100644 index 00000000..197e8f29 --- /dev/null +++ b/src/main/java/io/mosip/print/entity/MspCardEntity.java @@ -0,0 +1,84 @@ +package io.mosip.print.entity; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.stereotype.Component; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.io.Serializable; +import java.time.LocalDateTime; +import java.util.Date; + +/** + * The persistent class Processed RegPrc print List database table. + * + * @author Thamaraikannan + * @since 1.0.0 + */ + +@Component +@Entity +@NoArgsConstructor +@Getter +@Setter +@Table(name = "msp_card", schema = "print") +public class MspCardEntity implements Serializable { + /** + * The Id. + */ + @Id + @Column(name = "id") + private String id; + + /** + * The Json Data. + */ + @Column(name = "json_data") + private String jsonData; + + /** + * The Province. + */ + @Column(name = "province") + private String province; + + @Column(name = "city") + private String city; + + @Column(name = "zone") + private String zone; + + @Column(name = "agegroup") + private Integer ageGroup; + + @Column(name = "introducer") + private String introducer; + + @Column(name = "resident") + private String resident; + + @Column(name = "registration_center_id") + private String registrationCenterId; + + @Column(name = "registration_date") + private LocalDateTime registrationDate; + + @Column(name = "download_date") + private LocalDateTime downloadDate; + + @Column(name = "request_id") + private String requestId; + + @Column(name = "status") + private Integer status; + + @Column(name = "request_id1") + private String requestId1; + + @Column(name = "birthdate") + private Date birthDate; +} diff --git a/src/main/java/io/mosip/print/entity/SingleAnySubtypeType.java b/src/main/java/io/mosip/print/entity/SingleAnySubtypeType.java index 997a6e19..2c9c8559 100644 --- a/src/main/java/io/mosip/print/entity/SingleAnySubtypeType.java +++ b/src/main/java/io/mosip/print/entity/SingleAnySubtypeType.java @@ -1,6 +1,5 @@ package io.mosip.print.entity; import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; diff --git a/src/main/java/io/mosip/print/exception/PlatformErrorMessages.java b/src/main/java/io/mosip/print/exception/PlatformErrorMessages.java index 3868cfb5..d2f9f67d 100644 --- a/src/main/java/io/mosip/print/exception/PlatformErrorMessages.java +++ b/src/main/java/io/mosip/print/exception/PlatformErrorMessages.java @@ -71,8 +71,12 @@ public enum PlatformErrorMessages { CERTIFICATE_THUMBPRINT_ERROR(PlatformConstants.PRT_PRINT_PREFIX + "026", "certificate thumbprint failure"), PRT_INVALID_KEY_EXCEPTION(PlatformConstants.PRT_PRINT_PREFIX + "027", "invalid key"), PRT_PDF_SIGN_EXCEPTION(PlatformConstants.PRT_PRINT_PREFIX + "028", "error occured while signing pdf"), - PRT_UNKNOWN_DECRYPTION_EXCEPTION(PlatformConstants.PRT_PRINT_PREFIX + "029", "Unknown Error in data decryption."); - + PRT_UNKNOWN_DECRYPTION_EXCEPTION(PlatformConstants.PRT_PRINT_PREFIX + "029", "Unknown Error in data decryption."), + PRT_RID_MISSING_EXCEPTION(PlatformConstants.PRT_PRINT_PREFIX + "029", "RID is mandatory"), + PRT_STATUS_MISSING_EXCEPTION(PlatformConstants.PRT_PRINT_PREFIX + "030", "Printer Status Missing or Invalid"), + PRT_UNKNOWN_EXCEPTION(PlatformConstants.PRT_PRINT_PREFIX + "031", "Unknown Error"), + PRT_PRINT_ID_INVALID_EXCEPTION(PlatformConstants.PRT_PRINT_PREFIX + "032", "Entered Print Request id is invalid"); + /** The error message. */ diff --git a/src/main/java/io/mosip/print/repository/MspCardRepository.java b/src/main/java/io/mosip/print/repository/MspCardRepository.java new file mode 100644 index 00000000..883da03a --- /dev/null +++ b/src/main/java/io/mosip/print/repository/MspCardRepository.java @@ -0,0 +1,10 @@ +package io.mosip.print.repository; + +import io.mosip.kernel.core.dataaccess.spi.repository.BaseRepository; +import io.mosip.print.entity.MspCardEntity; +import org.springframework.stereotype.Repository; + +@Repository("mspCardRepository") +public interface MspCardRepository extends BaseRepository { + +} diff --git a/src/main/java/io/mosip/print/service/impl/PrintRestClientServiceImpl.java b/src/main/java/io/mosip/print/service/impl/PrintRestClientServiceImpl.java index 6269c4be..4f6b356c 100644 --- a/src/main/java/io/mosip/print/service/impl/PrintRestClientServiceImpl.java +++ b/src/main/java/io/mosip/print/service/impl/PrintRestClientServiceImpl.java @@ -12,9 +12,7 @@ import org.springframework.web.util.UriComponentsBuilder; import io.mosip.print.constant.ApiName; -import io.mosip.print.constant.LoggerFileConstant; import io.mosip.print.exception.ApisResourceAccessException; -import io.mosip.print.exception.ExceptionUtils; import io.mosip.print.exception.PlatformErrorMessages; import io.mosip.print.logger.PrintLogger; import io.mosip.print.service.PrintRestClientService; diff --git a/src/main/java/io/mosip/print/service/impl/PrintServiceImpl.java b/src/main/java/io/mosip/print/service/impl/PrintServiceImpl.java index d8ea0a49..a998efa4 100644 --- a/src/main/java/io/mosip/print/service/impl/PrintServiceImpl.java +++ b/src/main/java/io/mosip/print/service/impl/PrintServiceImpl.java @@ -1,96 +1,58 @@ package io.mosip.print.service.impl; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; - -import org.apache.commons.codec.binary.Base64; -import org.joda.time.DateTime; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Service; - -import io.mosip.print.constant.EventId; -import io.mosip.print.constant.EventName; -import io.mosip.print.constant.EventType; -import io.mosip.print.constant.IdType; -import io.mosip.print.constant.ModuleName; -import io.mosip.print.constant.PDFGeneratorExceptionCodeConstant; -import io.mosip.print.constant.PlatformSuccessMessages; -import io.mosip.print.constant.QrVersion; -import io.mosip.print.constant.UinCardType; +import io.mosip.print.constant.*; import io.mosip.print.dto.CryptoWithPinRequestDto; import io.mosip.print.dto.CryptoWithPinResponseDto; import io.mosip.print.dto.DataShare; import io.mosip.print.dto.JsonValue; -import io.mosip.print.exception.ApiNotAccessibleException; -import io.mosip.print.exception.ApisResourceAccessException; -import io.mosip.print.exception.CryptoManagerException; -import io.mosip.print.exception.DataShareException; -import io.mosip.print.exception.ExceptionUtils; -import io.mosip.print.exception.IdRepoAppException; -import io.mosip.print.exception.IdentityNotFoundException; -import io.mosip.print.exception.PDFGeneratorException; -import io.mosip.print.exception.PDFSignatureException; -import io.mosip.print.exception.ParsingException; -import io.mosip.print.exception.PlatformErrorMessages; -import io.mosip.print.exception.QrcodeGenerationException; -import io.mosip.print.exception.TemplateProcessingFailureException; -import io.mosip.print.exception.UINNotFoundInDatabase; +import io.mosip.print.entity.MspCardEntity; +import io.mosip.print.exception.*; +import io.mosip.print.idrepo.dto.IdResponseDTO1; import io.mosip.print.logger.LogDescription; import io.mosip.print.logger.PrintLogger; import io.mosip.print.model.CredentialStatusEvent; import io.mosip.print.model.EventModel; import io.mosip.print.model.StatusEvent; +import io.mosip.print.repository.MspCardRepository; import io.mosip.print.service.PrintService; import io.mosip.print.service.UinCardGenerator; import io.mosip.print.spi.CbeffUtil; import io.mosip.print.spi.QrCodeGenerator; -import io.mosip.print.util.AuditLogRequestBuilder; -import io.mosip.print.util.CbeffToBiometricUtil; -import io.mosip.print.util.CredentialsVerifier; -import io.mosip.print.util.CryptoCoreUtil; -import io.mosip.print.util.CryptoUtil; -import io.mosip.print.util.DataShareUtil; -import io.mosip.print.util.DateUtils; -import io.mosip.print.util.JsonUtil; -import io.mosip.print.util.RestApiClient; -import io.mosip.print.util.TemplateGenerator; -import io.mosip.print.util.Utilities; -import io.mosip.print.util.WebSubSubscriptionHelper; +import io.mosip.print.util.*; +import org.apache.commons.codec.binary.Base64; +import org.joda.time.DateTime; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; @Service public class PrintServiceImpl implements PrintService{ @@ -179,9 +141,6 @@ public class PrintServiceImpl implements PrintService{ @Autowired private Environment env; - @Autowired - private CredentialsVerifier credentialsVerifier; - @Value("${mosip.datashare.partner.id}") private String partnerId; @@ -197,35 +156,81 @@ public class PrintServiceImpl implements PrintService{ @Value("${mosip.print.verify.credentials.flag:true}") private boolean verifyCredentialsFlag; + @Value("${token.request.clientId}") + private String clientId; + + @Value("${mosip.print.default.infant.photo:null}") + private String defaultBabyPhoto; + + @Value("${mosip.print.infant.max.age:5}") + private int defaultBabyAge; + + @Value("${mosip.print.dob.pattern}") + private String dobPattern; + + @Autowired + @Qualifier("mspCardRepository") + MspCardRepository mspCardRepository; public boolean generateCard(EventModel eventModel) { + Map byteMap = new HashMap<>(); + String decodedCrdential = null; String credential = null; - boolean isPrinted = false; - try { - if (eventModel.getEvent().getDataShareUri() == null || eventModel.getEvent().getDataShareUri().isEmpty()) { - credential = eventModel.getEvent().getData().get("credential").toString(); - } else { - String dataShareUrl = eventModel.getEvent().getDataShareUri(); - URI dataShareUri = URI.create(dataShareUrl); - credential = restApiClient.getApi(dataShareUri, String.class); - } - String ecryptionPin = eventModel.getEvent().getData().get("protectionKey").toString(); - String decodedCredential = cryptoCoreUtil.decrypt(credential); - if (verifyCredentialsFlag){ - printLogger.info("Configured received credentials to be verified. Flag {}", verifyCredentialsFlag); - boolean verified = credentialsVerifier.verifyCredentials(decodedCredential); - if (!verified) { - printLogger.error("Received Credentials failed in verifiable credential verify method. So, the credentials will not be printed." + - " Id: {}, Transaction Id: {}", eventModel.getEvent().getId(), eventModel.getEvent().getTransactionId()); - return false; - } - } - Map proofMap = new HashMap(); - proofMap = (Map) eventModel.getEvent().getData().get("proof"); - byte[] pdfbytes = getDocuments(decodedCredential, - eventModel.getEvent().getData().get("credentialType").toString(), ecryptionPin, - eventModel.getEvent().getTransactionId(), "UIN", false).get("uinPdf"); - isPrinted = true; + boolean isPrinted =false; + try{ + if (eventModel.getEvent().getDataShareUri() == null || eventModel.getEvent().getDataShareUri().isEmpty()) { + credential = eventModel.getEvent().getData().get("credential").toString(); + } else { + String dataShareUrl = eventModel.getEvent().getDataShareUri(); + URI dataShareUri = URI.create(dataShareUrl); + credential = restApiClient.getApi(dataShareUri, String.class); + } + + String ecryptionPin = eventModel.getEvent().getData().get("protectionKey").toString(); + decodedCrdential = cryptoCoreUtil.decrypt(credential); + + Map proofMap = new HashMap(); + proofMap = (Map) eventModel.getEvent().getData().get("proof"); + String sign = proofMap.get("signature").toString(); + Map attributes = getDocuments(decodedCrdential, + eventModel.getEvent().getData().get("credentialType").toString(), ecryptionPin, + eventModel.getEvent().getTransactionId(), getSignature(sign, credential), "UIN", false, eventModel.getEvent().getId(), + eventModel.getEvent().getData().get("registrationId").toString()); + + + String printid = (String) eventModel.getEvent().getId(); + + org.json.simple.JSONObject obj = new org.json.simple.JSONObject(); + Object photo = attributes.get(APPLICANT_PHOTO); + if (photo == null && isChildRegistration(attributes)) { + photo = defaultBabyPhoto; + } + obj.put("photo", photo); + obj.put("qrCode", attributes.get(QRCODE)); + String fullAddress = getFullAddress(attributes); + obj.put("address", (fullAddress.length() > 0) ? fullAddress : "N/A"); + obj.put("locality", ((attributes.get("locality") != null && !attributes.get("locality").equals("")) ? attributes.get("locality").toString() : "N/A")); + obj.put("city", ((attributes.get("city") != null && !attributes.get("city").equals("")) ? attributes.get("city").toString() : "N/A")); + obj.put("state", ((attributes.get("state") != null && !attributes.get("state").equals("")) ? attributes.get("state").toString() : "N/A")); + obj.put("postalCode", ((attributes.get("postalCode") != null && !attributes.get("postalCode").equals("")) ? attributes.get("postalCode").toString() : "N/A")); + obj.put("gender", ((attributes.get("gender") != null && !attributes.get("gender").equals("")) ? attributes.get("gender").toString() : "N/A")); + obj.put("fullName", ((attributes.get("fullName") != null && !attributes.get("fullName").equals("")) ? attributes.get("fullName").toString() : "N/A")); + obj.put("dateOfBirth", ((attributes.get("dateOfBirth") != null && !attributes.get("dateOfBirth").equals("")) ? attributes.get("dateOfBirth").toString() : "N/A")); + obj.put("phone", ((attributes.get("phone") != null && !attributes.get("phone").equals("")) ? attributes.get("phone").toString() : "N/A")); + obj.put("vid", ((attributes.get("VID") != null && !attributes.get("VID").equals("")) ? attributes.get("VID").toString() : "N/A")); + obj.put("UIN", ((attributes.get("UIN") != null && !attributes.get("UIN").equals("")) ? attributes.get("UIN").toString() : "N/A")); + obj.put("email", ((attributes.get("email") != null && !attributes.get("email").equals("")) ? attributes.get("email").toString() : "N/A")); + + String woenc = obj.toJSONString(); + + MspCardEntity mspCardEntity = new MspCardEntity(); + mspCardEntity.setJsonData(woenc); + mspCardEntity.setRequestId(printid); + mspCardEntity.setStatus(90); + UUID uuid=UUID.randomUUID(); + mspCardEntity.setId(uuid.toString()); + mspCardRepository.create(mspCardEntity); + isPrinted=true; }catch (Exception e){ printLogger.error(e.getMessage() , e); isPrinted = false; @@ -233,26 +238,48 @@ public boolean generateCard(EventModel eventModel) { return isPrinted; } - /* - * (non-Javadoc) - * - * @see io.mosip.print.service.PrintService# - * getDocuments(io.mosip.registration.processor.core.constant.IdType, - * java.lang.String, java.lang.String, boolean) - */ - private Map getDocuments(String credential, String credentialType, String encryptionPin, - String requestId, - String cardType, - boolean isPasswordProtected) { - printLogger.debug("PrintServiceImpl::getDocuments()::entry"); + private boolean isChildRegistration(Map attributes) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dobPattern); + LocalDate dateOfBirth = LocalDate.parse((String) attributes.get("dateOfBirth"), dateTimeFormatter); + if ((LocalDate.now().getYear() - dateOfBirth.getYear()) <= defaultBabyAge) { + return true; + } + return false; + } + + private String getFullAddress(Map attributes) { + Object fullAddress[] = new Object[]{ attributes.get("addressLine1"), + attributes.get("addressLine2"), attributes.get("addressLine3"), attributes.get("landmark")}; + fullAddress = Arrays.stream(fullAddress) + .filter(s -> (s != null && !s.equals(""))) + .toArray(Object[]::new); + return StringUtils.arrayToCommaDelimitedString(fullAddress); + } + + private String getSignature(String sign, String crdential) { + String signHeader = sign.split("\\.")[0]; + String signData = sign.split("\\.")[2]; + String signature = signHeader + "." + crdential + "." + signData; + return signature; + } + private Map getDocuments(String credential, String credentialType, String encryptionPin, + String requestId, String sign, + String cardType, + boolean isPasswordProtected, String refId, String registrationId) { + printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "PrintServiceImpl::getDocuments()::entry"); + + String credentialSubject; Map byteMap = new HashMap<>(); String uin = null; LogDescription description = new LogDescription(); String password = null; + boolean isPhotoSet=false; String individualBio = null; Map attributes = new LinkedHashMap<>(); boolean isTransactionSuccessful = false; + IdResponseDTO1 response = null; String template = UIN_CARD_TEMPLATE; byte[] pdfbytes = null; try { @@ -260,23 +287,22 @@ private Map getDocuments(String credential, String credentialTyp credentialSubject = getCrdentialSubject(credential); org.json.JSONObject credentialSubjectJson = new org.json.JSONObject(credentialSubject); org.json.JSONObject decryptedJson = decryptAttribute(credentialSubjectJson, encryptionPin, credential); - individualBio = decryptedJson.getString("biometrics"); - String individualBiometric = new String(individualBio); + if(decryptedJson.has("biometrics")){ + individualBio = decryptedJson.getString("biometrics"); + String individualBiometric = new String(individualBio); + isPhotoSet = setApplicantPhoto(individualBiometric, attributes); + attributes.put("isPhotoSet",isPhotoSet); + } + uin = decryptedJson.getString("UIN"); if (isPasswordProtected) { password = getPassword(uin); } - if (credentialType.equalsIgnoreCase("qrcode")) { - boolean isQRcodeSet = setQrCode(decryptedJson.toString(), attributes); - InputStream uinArtifact = templateGenerator.getTemplate(template, attributes, templateLang); - pdfbytes = uinCardGenerator.generateUinCard(uinArtifact, UinCardType.PDF, - password); - - } else { - boolean isPhotoSet = setApplicantPhoto(individualBiometric, attributes); if (!isPhotoSet) { - printLogger.debug(PlatformErrorMessages.PRT_PRT_APPLICANT_PHOTO_NOT_SET.name()); + printLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), uin + + PlatformErrorMessages.PRT_PRT_APPLICANT_PHOTO_NOT_SET.name()); } setTemplateAttributes(decryptedJson.toString(), attributes); attributes.put(IdType.UIN.toString(), uin); @@ -284,68 +310,87 @@ private Map getDocuments(String credential, String credentialTyp byte[] textFileByte = createTextFile(decryptedJson.toString()); byteMap.put(UIN_TEXT_FILE, textFileByte); - boolean isQRcodeSet = setQrCode(decryptedJson.toString(), attributes); + boolean isQRcodeSet = setQrCode(decryptedJson.toString(), attributes, isPhotoSet); if (!isQRcodeSet) { - printLogger.debug(PlatformErrorMessages.PRT_PRT_QRCODE_NOT_SET.name()); - } - // getting template and placing original valuespng - InputStream uinArtifact = templateGenerator.getTemplate(template, attributes, templateLang); - if (uinArtifact == null) { - printLogger.error(PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.name()); - throw new TemplateProcessingFailureException( - PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.getCode()); + printLogger.debug(LoggerFileConstant.SESSIONID.toString(), + LoggerFileConstant.REGISTRATIONID.toString(), uin + + PlatformErrorMessages.PRT_PRT_QRCODE_NOT_SET.name()); } - pdfbytes = uinCardGenerator.generateUinCard(uinArtifact, UinCardType.PDF, password); - } - printStatusUpdate(requestId, pdfbytes, credentialType); + printStatusUpdate(requestId, credentialType, uin, refId, registrationId); isTransactionSuccessful = true; + } catch (VidCreationException e) { + e.printStackTrace(); + description.setMessage(PlatformErrorMessages.PRT_PRT_VID_CREATION_ERROR.getMessage()); + description.setCode(PlatformErrorMessages.PRT_PRT_VID_CREATION_ERROR.getCode()); + printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "UIN", PlatformErrorMessages.PRT_PRT_QRCODE_NOT_GENERATED.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + throw new PDFGeneratorException(e.getErrorCode(), e.getErrorText()); + } + catch (QrcodeGenerationException e) { + e.printStackTrace(); description.setMessage(PlatformErrorMessages.PRT_PRT_QR_CODE_GENERATION_ERROR.getMessage()); description.setCode(PlatformErrorMessages.PRT_PRT_QR_CODE_GENERATION_ERROR.getCode()); - printLogger.error(PlatformErrorMessages.PRT_PRT_QRCODE_NOT_GENERATED.name() , e); + printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "UIN", + PlatformErrorMessages.PRT_PRT_QRCODE_NOT_GENERATED.name() + ExceptionUtils.getStackTrace(e)); throw new PDFGeneratorException(PDFGeneratorExceptionCodeConstant.PDF_EXCEPTION.getErrorCode(), e.getErrorText()); } catch (UINNotFoundInDatabase e) { + e.printStackTrace(); description.setMessage(PlatformErrorMessages.PRT_PRT_UIN_NOT_FOUND_IN_DATABASE.getMessage()); description.setCode(PlatformErrorMessages.PRT_PRT_UIN_NOT_FOUND_IN_DATABASE.getCode()); - printLogger.error( - PlatformErrorMessages.PRT_PRT_UIN_NOT_FOUND_IN_DATABASE.name() ,e); + printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "UIN".toString(), + PlatformErrorMessages.PRT_PRT_UIN_NOT_FOUND_IN_DATABASE.name() + ExceptionUtils.getStackTrace(e)); throw new PDFGeneratorException(PDFGeneratorExceptionCodeConstant.PDF_EXCEPTION.getErrorCode(), e.getErrorText()); } catch (TemplateProcessingFailureException e) { + e.printStackTrace(); description.setMessage(PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.getMessage()); description.setCode(PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.getCode()); - printLogger.error(PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.name() ,e); + printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "UIN", + PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.name() + ExceptionUtils.getStackTrace(e)); throw new TemplateProcessingFailureException(PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.getMessage()); } catch (PDFGeneratorException e) { + e.printStackTrace(); description.setMessage(PlatformErrorMessages.PRT_PRT_PDF_NOT_GENERATED.getMessage()); description.setCode(PlatformErrorMessages.PRT_PRT_PDF_NOT_GENERATED.getCode()); - printLogger.error(PlatformErrorMessages.PRT_PRT_PDF_NOT_GENERATED.name() ,e); + printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "UIN", + PlatformErrorMessages.PRT_PRT_PDF_NOT_GENERATED.name() + ExceptionUtils.getStackTrace(e)); throw new PDFGeneratorException(PDFGeneratorExceptionCodeConstant.PDF_EXCEPTION.getErrorCode(), e.getErrorText()); } catch (PDFSignatureException e) { + e.printStackTrace(); description.setMessage(PlatformErrorMessages.PRT_PRT_PDF_SIGNATURE_EXCEPTION.getMessage()); description.setCode(PlatformErrorMessages.PRT_PRT_PDF_SIGNATURE_EXCEPTION.getCode()); - printLogger.error(PlatformErrorMessages.PRT_PRT_PDF_SIGNATURE_EXCEPTION.name() ,e); + printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "UIN".toString(), + PlatformErrorMessages.PRT_PRT_PDF_SIGNATURE_EXCEPTION.name() + ExceptionUtils.getStackTrace(e)); throw new PDFSignatureException(PlatformErrorMessages.PRT_PRT_PDF_SIGNATURE_EXCEPTION.getMessage()); } catch (Exception ex) { + ex.printStackTrace(); description.setMessage(PlatformErrorMessages.PRT_PRT_PDF_GENERATION_FAILED.getMessage()); description.setCode(PlatformErrorMessages.PRT_PRT_PDF_GENERATION_FAILED.getCode()); - printLogger.error(ex.getMessage() ,ex); + printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + "UIN", description + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); throw new PDFGeneratorException(PDFGeneratorExceptionCodeConstant.PDF_EXCEPTION.getErrorCode(), - ex.getMessage() ,ex); + ex.getMessage() + ExceptionUtils.getStackTrace(ex)); } finally { String eventId = ""; @@ -373,11 +418,13 @@ private Map getDocuments(String credential, String credentialTyp auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, moduleId, moduleName, uin); } - printLogger.debug("PrintServiceImpl::getDocuments()::exit"); + printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", + "PrintServiceImpl::getDocuments()::exit"); - return byteMap; + return attributes; } + /** * Creates the text file. * @@ -445,11 +492,13 @@ private byte[] createTextFile(String jsonString) throws IOException { * occurred. * @throws io.mosip.print.exception.QrcodeGenerationException */ - private boolean setQrCode(String qrString, Map attributes) + private boolean setQrCode(String qrString, Map attributes,boolean isPhotoSet) throws QrcodeGenerationException, IOException, io.mosip.print.exception.QrcodeGenerationException { boolean isQRCodeSet = false; JSONObject qrJsonObj = JsonUtil.objectMapperReadValue(qrString, JSONObject.class); - qrJsonObj.remove("biometrics"); + if(isPhotoSet) { + qrJsonObj.remove("biometrics"); + } byte[] qrCodeBytes = qrCodeGenerator.generateQrCode(qrJsonObj.toString(), QrVersion.V30); if (qrCodeBytes != null) { String imageString = Base64.encodeBase64String(qrCodeBytes); @@ -691,6 +740,25 @@ private void printStatusUpdate(String requestId, byte[] data, String credentialT webSubSubscriptionHelper.printStatusUpdateEvent(topic, creEvent); } + + private void printStatusUpdate(String requestId, String credentialType, String uin, String printRefId, String registrationId) + throws DataShareException, ApiNotAccessibleException, IOException, Exception { + CredentialStatusEvent creEvent = new CredentialStatusEvent(); + LocalDateTime currentDtime = DateUtils.getUTCCurrentDateTime(); + StatusEvent sEvent = new StatusEvent(); + sEvent.setId(UUID.randomUUID().toString()); + sEvent.setRequestId(requestId); + sEvent.setStatus("printing"); + sEvent.setUrl(""); + sEvent.setTimestamp(Timestamp.valueOf(currentDtime).toString()); + creEvent.setPublishedOn(new DateTime().toString()); + creEvent.setPublisher("PRINT_SERVICE"); + creEvent.setTopic(topic); + creEvent.setEvent(sEvent); + webSubSubscriptionHelper.printStatusUpdateEvent(topic, creEvent); + } + + public org.json.JSONObject decryptAttribute(org.json.JSONObject data, String encryptionPin, String credential) throws ParseException { diff --git a/src/main/java/io/mosip/print/service/impl/UinCardGeneratorImpl.java b/src/main/java/io/mosip/print/service/impl/UinCardGeneratorImpl.java index 843010a0..1cfef21c 100644 --- a/src/main/java/io/mosip/print/service/impl/UinCardGeneratorImpl.java +++ b/src/main/java/io/mosip/print/service/impl/UinCardGeneratorImpl.java @@ -7,7 +7,6 @@ import java.time.format.DateTimeFormatter; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -18,7 +17,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.mosip.print.constant.ApiName; -import io.mosip.print.constant.LoggerFileConstant; import io.mosip.print.constant.PDFGeneratorExceptionCodeConstant; import io.mosip.print.constant.UinCardType; import io.mosip.print.core.http.RequestWrapper; diff --git a/src/main/java/io/mosip/print/util/CredentialsVerifier.java b/src/main/java/io/mosip/print/util/CredentialsVerifier.java deleted file mode 100644 index 706f78f9..00000000 --- a/src/main/java/io/mosip/print/util/CredentialsVerifier.java +++ /dev/null @@ -1,147 +0,0 @@ -package io.mosip.print.util; - -import java.io.IOException; -import java.io.StringReader; -import java.net.URI; -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.MGF1ParameterSpec; -import java.security.spec.PSSParameterSpec; -import java.security.spec.X509EncodedKeySpec; -import java.text.ParseException; -import java.util.Objects; - -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.nimbusds.jose.JWSObject; - -import org.bouncycastle.util.io.pem.PemObject; -import org.bouncycastle.util.io.pem.PemReader; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpMethod; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -import foundation.identity.jsonld.ConfigurableDocumentLoader; -import foundation.identity.jsonld.JsonLDException; -import foundation.identity.jsonld.JsonLDObject; -import info.weboftrust.ldsignatures.LdProof; -import info.weboftrust.ldsignatures.canonicalizer.URDNA2015Canonicalizer; -import info.weboftrust.ldsignatures.util.JWSUtil; -import io.mosip.print.constant.CredentialVerifierConstants; -import io.mosip.print.logger.PrintLogger; - -@Component -public class CredentialsVerifier { - - Logger CredVerifierLogger = PrintLogger.getLogger(CredentialsVerifier.class); - - @Autowired - private RestTemplate restTemplate; - - public boolean verifyCredentials(String credentials){ - CredVerifierLogger.info("Received Credentials Verification - Start."); - ConfigurableDocumentLoader confDocumentLoader = new ConfigurableDocumentLoader(); - confDocumentLoader.setEnableHttps(true); - confDocumentLoader.setEnableHttp(true); - confDocumentLoader.setEnableFile(false); - - JsonLDObject vcJsonLdObject = JsonLDObject.fromJson(credentials); - vcJsonLdObject.setDocumentLoader(confDocumentLoader); - - LdProof ldProofWithJWS = LdProof.getFromJsonLDObject(vcJsonLdObject); - if (Objects.isNull(ldProofWithJWS)) { - CredVerifierLogger.error("Proof document is not available in the received credentials."); - return false; - } - - String ldProofTerm = ldProofWithJWS.getType(); - if (!CredentialVerifierConstants.SIGNATURE_SUITE_TERM.equals(ldProofTerm)) { - CredVerifierLogger.error("Proof Type available in received credentials is not matching " + - " with supported proof terms. Recevied Type: {}", ldProofTerm); - return false; - } - - try { - - URDNA2015Canonicalizer canonicalizer = new URDNA2015Canonicalizer(); - byte[] canonicalHashBytes = canonicalizer.canonicalize(ldProofWithJWS, vcJsonLdObject); - CredVerifierLogger.info("Completed Canonicalization for the received credentials."); - String signJWS = ldProofWithJWS.getJws(); - JWSObject jwsObject = JWSObject.parse(signJWS); - byte[] vcSignBytes = jwsObject.getSignature().decode(); - URI publicKeyJsonUri = ldProofWithJWS.getVerificationMethod(); - PublicKey publicKeyObj = getPublicKeyFromVerificationMethod(publicKeyJsonUri); - if (Objects.isNull(publicKeyObj)) { - CredVerifierLogger.error("Public key object is null, returning false."); - return false; - } - CredVerifierLogger.info("Completed downloading public key from the issuer domain and constructed public key object."); - byte[] actualData = JWSUtil.getJwsSigningInput(jwsObject.getHeader(), canonicalHashBytes); - String jwsHeader = jwsObject.getHeader().getAlgorithm().getName(); - CredVerifierLogger.info("Performing signature verification after downloading the public key."); - return verifyCredentialSignature(jwsHeader, publicKeyObj, actualData, vcSignBytes); - } catch (IOException | GeneralSecurityException | JsonLDException | ParseException e) { - CredVerifierLogger.error("Error in doing verifiable credential verification process.", e); - } - return false; - } - - - private PublicKey getPublicKeyFromVerificationMethod(URI publicKeyJsonUri){ - - try { - ObjectNode response = restTemplate.exchange(publicKeyJsonUri, HttpMethod.GET, null, ObjectNode.class).getBody(); - String publicKeyPem = response.get(CredentialVerifierConstants.PUBLIC_KEY_PEM).asText(); - CredVerifierLogger.info("public key download completed."); - StringReader strReader = new StringReader(publicKeyPem); - PemReader pemReader = new PemReader(strReader); - PemObject pemObject = pemReader.readPemObject(); - byte[] pubKeyBytes = pemObject.getContent(); - X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - return keyFactory.generatePublic(pubKeySpec); - } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { - CredVerifierLogger.error("Error Generating public key object.", e); - } - return null; - } - - private boolean verifyCredentialSignature(String algorithm, PublicKey publicKey, byte[] actualData, byte[] signature) { - - if (algorithm.equals(CredentialVerifierConstants.JWS_RS256_SIGN_ALGO_CONST)) { - try { - CredVerifierLogger.info("Validating signature using RS256 algorithm."); - Signature rsSignature = Signature.getInstance(CredentialVerifierConstants.RS256_ALGORITHM); - rsSignature.initVerify(publicKey); - rsSignature.update(actualData); - return rsSignature.verify(signature); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { - CredVerifierLogger.error("Error in Verifying credentials(RS256).", e); - } - } - try { - CredVerifierLogger.info("Validating signature using PS256 algorithm."); - Signature psSignature = Signature.getInstance(CredentialVerifierConstants.PS256_ALGORITHM); - - PSSParameterSpec pssParamSpec = new PSSParameterSpec(CredentialVerifierConstants.PSS_PARAM_SHA_256, CredentialVerifierConstants.PSS_PARAM_MGF1, - MGF1ParameterSpec.SHA256, CredentialVerifierConstants.PSS_PARAM_SALT_LEN, CredentialVerifierConstants.PSS_PARAM_TF); - psSignature.setParameter(pssParamSpec); - - psSignature.initVerify(publicKey); - psSignature.update(actualData); - return psSignature.verify(signature); - } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | InvalidAlgorithmParameterException e) { - CredVerifierLogger.error("Error in Verifying credentials(PS256).", e); - } - return false; - } - -} diff --git a/src/main/java/io/mosip/print/util/RestApiClient.java b/src/main/java/io/mosip/print/util/RestApiClient.java index 636020d7..a026d843 100644 --- a/src/main/java/io/mosip/print/util/RestApiClient.java +++ b/src/main/java/io/mosip/print/util/RestApiClient.java @@ -3,7 +3,7 @@ import java.io.IOException; import java.net.URI; import java.util.Iterator; -import org.apache.commons.lang3.exception.ExceptionUtils; + import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -17,14 +17,6 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; - -import io.mosip.print.constant.LoggerFileConstant; -import io.mosip.print.dto.Metadata; -import io.mosip.print.dto.PasswordRequest; -import io.mosip.print.dto.SecretKeyRequest; -import io.mosip.print.dto.TokenRequestDTO; -import io.mosip.print.exception.TokenGenerationFailedException; import io.mosip.print.logger.PrintLogger; /** diff --git a/src/main/java/io/mosip/print/util/WebSubSubscriptionHelper.java b/src/main/java/io/mosip/print/util/WebSubSubscriptionHelper.java index 7cb4fcb8..feb3a19f 100644 --- a/src/main/java/io/mosip/print/util/WebSubSubscriptionHelper.java +++ b/src/main/java/io/mosip/print/util/WebSubSubscriptionHelper.java @@ -2,9 +2,7 @@ import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; -import org.springframework.cache.annotation.Cacheable; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.scheduling.annotation.Scheduled; @@ -16,13 +14,10 @@ import io.mosip.kernel.websub.api.model.SubscriptionChangeRequest; import io.mosip.kernel.websub.api.model.SubscriptionChangeResponse; import io.mosip.kernel.websub.api.model.UnsubscriptionRequest; -import io.mosip.print.constant.LoggerFileConstant; import io.mosip.print.logger.PrintLogger; import io.mosip.print.model.CredentialStatusEvent; import org.springframework.web.client.RestTemplate; -import javax.annotation.PostConstruct; - @Component public class WebSubSubscriptionHelper { @@ -73,7 +68,7 @@ private void subscribeForPrintServiceEvents() { LOGGER.info("subscription request : {}", subscriptionRequest); sb.subscribe(subscriptionRequest); } catch (WebSubClientException e) { - LOGGER.info("websub subscription error {} {}", WEBSUBSUBSCRIPTIONHEPLER, INITSUBSCRIPTION); + LOGGER.error("websub subscription error {} {}", WEBSUBSUBSCRIPTIONHEPLER, INITSUBSCRIPTION, e); } } diff --git a/src/main/resources/application-local1.properties b/src/main/resources/application-local1.properties index f38023ec..23444a21 100644 --- a/src/main/resources/application-local1.properties +++ b/src/main/resources/application-local1.properties @@ -131,3 +131,15 @@ mosip.print.crypto.p12.password=password@123 mosip.print.crypto.p12.alias=partner mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter mosip.kernel.auth.appids.realm.map={prereg:'preregistration',ida:'mosip',registrationclient:'mosip',regproc:'mosip',partner:'mosip',resident:'mosip',admin:'mosip',crereq:'mosip',creser:'mosip',datsha:'mosip',idrepo:'mosip'} +#-----------------DATABASE Configuration --------------------------# +mosip.database.ip=postgres-postgresql.postgres.svc.cluster.local +mosip.database.port=5432 +hibernate.dialect: org.hibernate.dialect.PostgreSQLDialect +hibernate.hbm2ddl.auto: none +hibernate.jdbc.lob.non_contextual_creation: true +hibernate.show_sql: false +javax.persistence.jdbc.driver: org.postgresql.Driver +javax.persistence.jdbc.password: password +javax.persistence.jdbc.url=jdbc:postgresql://dev2.mosip.net:5432/mosip_print?useSSL=false +javax.persistence.jdbc.user: postgres +mosip.application.id=io.mosip.print diff --git a/src/main/resources/bootstrap.properties b/src/main/resources/bootstrap.properties index 2c439ba6..300a9d68 100644 --- a/src/main/resources/bootstrap.properties +++ b/src/main/resources/bootstrap.properties @@ -1,11 +1,14 @@ #spring.cloud.config.uri=localhost #spring.cloud.config.label=develop spring.profiles.active=local1 -#spring.cloud.config.name=print -spring.application.name=print +spring.cloud.config.name=cardprint +spring.application.name=cardprint management.endpoint.health.show-details=always management.endpoints.web.exposure.include=info,health,refresh -server.port=8088 -server.servlet.context-path=/v1/print -health.config.enabled=false \ No newline at end of file +server.port=8089 +server.servlet.context-path=/v1/cardprint +health.config.enabled=false + + +mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter \ No newline at end of file diff --git a/src/main/resources/partner.p12 b/src/main/resources/partner.p12 index e36aa5d8..64be7808 100644 Binary files a/src/main/resources/partner.p12 and b/src/main/resources/partner.p12 differ diff --git a/src/main/resources/partner_old.p12 b/src/main/resources/partner_old.p12 new file mode 100644 index 00000000..64be7808 Binary files /dev/null and b/src/main/resources/partner_old.p12 differ