From d58d604a7ba17876e3dc4af1d8b4e91a925f1d71 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 8 Aug 2023 17:26:56 +0530 Subject: [PATCH 01/43] RC-Synch --- java/123.bat | 4 + java/claim/Dockerfile | 2 +- java/claim/pom.xml | 77 +++- .../sunbirdrc/claim/config/EmailConfig.java | 20 + .../controller/CredentialsController.java | 89 ++++ .../claim/controller/EmailController.java | 115 +++++ .../claim/controller/FileController.java | 55 +++ .../java/dev/sunbirdrc/claim/dto/BarCode.java | 28 ++ .../java/dev/sunbirdrc/claim/dto/FileDto.java | 12 + .../java/dev/sunbirdrc/claim/dto/MailDto.java | 45 ++ .../dev/sunbirdrc/claim/dto/StudentDTO.java | 19 + .../dev/sunbirdrc/claim/entity/Candidate.java | 80 ++++ .../dev/sunbirdrc/claim/entity/Claim.java | 7 +- .../dev/sunbirdrc/claim/entity/ClaimUser.java | 32 ++ .../dev/sunbirdrc/claim/entity/Course.java | 59 +++ .../sunbirdrc/claim/entity/Credentials.java | 50 +++ .../dev/sunbirdrc/claim/entity/Learner.java | 33 ++ .../dev/sunbirdrc/claim/entity/Student.java | 27 ++ .../claim/entity/StudentDetails.java | 90 ++++ .../claim/entity/StudentRequest.java | 34 ++ .../dev/sunbirdrc/claim/entity/Subject.java | 40 ++ .../sunbirdrc/claim/entity/YearsOfCourse.java | 48 ++ .../claim/exception/BadRequestException.java | 14 + .../claim/exception/FileWriteException.java | 14 + .../exception/GCPFileUploadException.java | 14 + .../exception/InvalidFileTypeException.java | 14 + .../sunbirdrc/claim/model/ClaimStatus.java | 6 +- .../claim/repository/CandidateRepository.java | 10 + .../claim/repository/ClaimUserRepository.java | 9 + .../claim/repository/CourseRepository.java | 9 + .../repository/CredentialsRepository.java | 10 + .../claim/repository/LearnerRepository.java | 14 + .../repository/YearOfCourseRepository.java | 9 + .../sunbirdrc/claim/service/ClaimService.java | 14 +- .../claim/service/CredentialsService.java | 91 ++++ .../sunbirdrc/claim/service/EmailService.java | 102 +++++ .../sunbirdrc/claim/service/FileService.java | 14 + .../claim/service/FileServiceImpl.java | 57 +++ .../dev/sunbirdrc/claim/status/Status.java | 8 + .../sunbirdrc/claim/utils/GCPBucketUtil.java | 150 +++++++ .../src/main/resources/application.properties | 38 +- .../claim/service/ClaimServiceTest.java | 5 +- .../registry/app/SunbirdRCApplication.java | 1 + .../controller/RegistryEntityController.java | 199 ++++++++- .../sunbirdrc/registry/dao/Credential.java | 11 + .../dev/sunbirdrc/registry/dao/Learner.java | 14 + .../dao/digilocker/pulldoc/DataContent.java | 18 + .../dao/digilocker/pulldoc/DocContent.java | 19 + .../dao/digilocker/pulldoc/DocDetailsRq.java | 31 ++ .../dao/digilocker/pulldoc/DocDetailsRs.java | 31 ++ .../digilocker/pulldoc/DocDetailsType.java | 33 ++ .../registry/dao/digilocker/pulldoc/Main.java | 74 ++++ .../digilocker/pulldoc/PullDocRequest.java | 68 +++ .../digilocker/pulldoc/PullDocResponse.java | 39 ++ .../digilocker/pulldoc/ResponseStatus.java | 41 ++ .../pulluriresponse/DocDetails.java | 47 ++ .../digilocker/pulluriresponse/IssuedTo.java | 21 + .../digilocker/pulluriresponse/Person.java | 51 +++ .../digilocker/pulluriresponse/Persons.java | 21 + .../digilocker/pulluriresponse/PhotoBean.java | 30 ++ .../pulluriresponse/PullURIResponse.java | 30 ++ .../pulluriresponse/ResponseUriStatus.java | 41 ++ .../digilocker/pulldoc/DataContent.java | 18 + .../digilocker/pulldoc/DocContent.java | 19 + .../digilocker/pulldoc/DocDetailsRq.java | 31 ++ .../digilocker/pulldoc/DocDetailsRs.java | 31 ++ .../digilocker/pulldoc/DocDetailsType.java | 33 ++ .../registry/digilocker/pulldoc/Main.java | 74 ++++ .../digilocker/pulldoc/PullDocRequest.java | 68 +++ .../digilocker/pulldoc/PullDocResponse.java | 39 ++ .../digilocker/pulldoc/ResponseStatus.java | 41 ++ .../pulluriresponse/DocDetails.java | 47 ++ .../digilocker/pulluriresponse/IssuedTo.java | 21 + .../digilocker/pulluriresponse/Person.java | 51 +++ .../digilocker/pulluriresponse/Persons.java | 21 + .../digilocker/pulluriresponse/PhotoBean.java | 30 ++ .../pulluriresponse/PullURIResponse.java | 30 ++ .../pulluriresponse/ResponseUriStatus.java | 41 ++ .../registry/helper/RegistryHelper.java | 113 +++++ .../sunbirdrc/registry/model/dto/BarCode.java | 28 ++ .../sunbirdrc/registry/model/dto/MailDto.java | 43 ++ .../sunbirdrc/registry/model/dto/Status.java | 15 + .../registry/service/ISearchService.java | 12 +- .../service/impl/CertificateServiceImpl.java | 64 ++- .../registry/util/ClaimRequestClient.java | 121 ++++- .../registry/util/CredentialConstant.java | 27 ++ .../registry/util/DigiLockerUtils.java | 307 +++++++++++++ .../sunbirdrc/registry/util/DocDetails.java | 94 ++++ .../registry/util/HmacSecretKeyGenerator.java | 27 ++ .../registry/util/PullURIRequest.java | 21 + .../src/main/resources/application.yml | 16 +- .../resources/public/_schemas/regulator.json | 49 +++ .../_schemas/studentForeignVerification.json | 261 +++++++++++ .../public/_schemas/studentFromUP.json | 352 +++++++++++++++ .../public/_schemas/studentGoodStanding.json | 240 ++++++++++ .../public/_schemas/studentNursingArmy.json | 371 ++++++++++++++++ .../public/_schemas/studentOutsideUp.json | 413 ++++++++++++++++++ .../resources/public/_schemas/teacher.json | 49 +++ 98 files changed, 5569 insertions(+), 37 deletions(-) create mode 100644 java/123.bat create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/config/EmailConfig.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/controller/CredentialsController.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/dto/BarCode.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/dto/FileDto.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/dto/MailDto.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/dto/StudentDTO.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Candidate.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/ClaimUser.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Course.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Credentials.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Learner.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Student.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentDetails.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentRequest.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Subject.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/YearsOfCourse.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/exception/BadRequestException.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/exception/FileWriteException.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/exception/GCPFileUploadException.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/exception/InvalidFileTypeException.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/CandidateRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimUserRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/CourseRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/CredentialsRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/LearnerRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/YearOfCourseRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/CredentialsService.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/status/Status.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/utils/GCPBucketUtil.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/Credential.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/Learner.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DataContent.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocContent.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsRq.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsRs.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsType.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/Main.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/PullDocRequest.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/PullDocResponse.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/ResponseStatus.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/DocDetails.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/IssuedTo.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/Person.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/Persons.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/PhotoBean.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/PullURIResponse.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/ResponseUriStatus.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DataContent.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocContent.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRq.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRs.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/Main.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocRequest.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocResponse.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/ResponseStatus.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/DocDetails.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/IssuedTo.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/Person.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/Persons.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/PhotoBean.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/PullURIResponse.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/ResponseUriStatus.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/BarCode.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/MailDto.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/Status.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/HmacSecretKeyGenerator.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/PullURIRequest.java create mode 100644 java/registry/src/main/resources/public/_schemas/regulator.json create mode 100644 java/registry/src/main/resources/public/_schemas/studentForeignVerification.json create mode 100644 java/registry/src/main/resources/public/_schemas/studentFromUP.json create mode 100644 java/registry/src/main/resources/public/_schemas/studentGoodStanding.json create mode 100644 java/registry/src/main/resources/public/_schemas/studentNursingArmy.json create mode 100644 java/registry/src/main/resources/public/_schemas/studentOutsideUp.json create mode 100644 java/registry/src/main/resources/public/_schemas/teacher.json diff --git a/java/123.bat b/java/123.bat new file mode 100644 index 000000000..60da3f3fa --- /dev/null +++ b/java/123.bat @@ -0,0 +1,4 @@ +set MAVEN_HOME=D:\apache-maven-3.9.1\ +set PATH=%PATH%;D:\apache-maven-3.9.1\bin\ +set CLASSPATH=%CLASSPATH%;D:\apache-maven-3.9.1\lib\ +mvn clean install -DskipTests \ No newline at end of file diff --git a/java/claim/Dockerfile b/java/claim/Dockerfile index 4f1f5af6e..a0e02df45 100644 --- a/java/claim/Dockerfile +++ b/java/claim/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:8-jdk-alpine +FROM openjdk:17-oracle ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} app.jar ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/java/claim/pom.xml b/java/claim/pom.xml index 056ac0da1..bb17d8bdc 100644 --- a/java/claim/pom.xml +++ b/java/claim/pom.xml @@ -13,19 +13,74 @@ - 1.8 + 11 + 4.1.1 + 2022.0.1 org.springframework.boot spring-boot-starter + + net.sourceforge.barbecue + barbecue + 1.5-beta1 + + + net.sf.barcode4j + barcode4j + 2.1 + + + com.google.zxing + core + 3.3.0 + + + com.google.zxing + javase + 3.3.0 + + + com.opencsv + opencsv + 5.5.2 + org.springframework.boot spring-boot-starter-data-jpa - + + org.springframework.cloud + spring-cloud-gcp-starter-vision + 1.2.8.RELEASE + + + org.springframework.cloud + spring-cloud-gcp-starter-storage + 1.2.8.RELEASE + + + com.google.cloud + spring-cloud-gcp-starter-storage + 4.3.1 + + + org.springframework.cloud + spring-cloud-dependencies + 2022.0.1 + pom + import + + + com.google.cloud + spring-cloud-gcp-dependencies + 4.1.1 + pom + import + org.postgresql @@ -84,7 +139,21 @@ 2.0.3 compile - + + org.springframework.boot + spring-boot-starter-mail + + + + org.jsoup + jsoup + 1.15.3 + + + org.json + json + 20210307 + @@ -96,4 +165,4 @@ - + \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/config/EmailConfig.java b/java/claim/src/main/java/dev/sunbirdrc/claim/config/EmailConfig.java new file mode 100644 index 000000000..d3d5634d5 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/config/EmailConfig.java @@ -0,0 +1,20 @@ +package dev.sunbirdrc.claim.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.mail.SimpleMailMessage; + +@Configuration +public class EmailConfig +{ + @Bean + public SimpleMailMessage emailTemplate() + { + SimpleMailMessage message = new SimpleMailMessage(); + message.setTo("kumarpawans@gmail.com"); + message.setFrom("shishir.suman@tarento.com"); + message.setSubject("Identity Card link for UPSMF"); + message.setText("FATAL - Application crash. Save your job !!"); + return message; + } +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CredentialsController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CredentialsController.java new file mode 100644 index 000000000..fb0ba994a --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CredentialsController.java @@ -0,0 +1,89 @@ +package dev.sunbirdrc.claim.controller; + +import dev.sunbirdrc.claim.entity.Learner; +import dev.sunbirdrc.claim.service.CredentialsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/credentials") +public class CredentialsController { + @Autowired + private CredentialsService credentialService; + + public CredentialsController(CredentialsService credentialService) { + this.credentialService = credentialService; + } + + + @PostMapping("/save") + public ResponseEntity saveLearnerWithCredentials(@RequestBody Learner learner) { + credentialService.saveLearnerWithCredentials(learner); + return ResponseEntity.ok("Learner with credentials saved successfully"); + } + + + @GetMapping("/get") + public ResponseEntity> getAllLearnerWithCredentials() { + List learner = credentialService.getAllLearnerWithCredentials(); + return ResponseEntity.ok(learner); + } + + @GetMapping("/get/{learnerId}") + public ResponseEntity getLearnerWithCredentialsById(@PathVariable Long learnerId) { + Learner learner = credentialService.getLearnerWithCredentialsById(learnerId); + if (learner != null) { + return ResponseEntity.ok(learner); + } else { + return ResponseEntity.notFound().build(); + } + } + @GetMapping("/getByName/{learnerName}") + public ResponseEntity> getLearnerWithCredentialsByName(@PathVariable String learnerName) { + List learners = credentialService.getLearnerWithCredentialsByName(learnerName); + if (!learners.isEmpty()) { + return ResponseEntity.ok(learners); + } else { + return ResponseEntity.notFound().build(); + } + } + @GetMapping("/getByRollNumber/{rollNumber}") + public ResponseEntity getLearnerWithCredentialsByRollNumber(@PathVariable String rollNumber) { + Learner learner = credentialService.getLearnerWithCredentialsByRollNumber(rollNumber); + if (learner != null) { + return ResponseEntity.ok(learner); + } else { + return ResponseEntity.notFound().build(); + } + } + + + @PutMapping("/update/{learnerId}") + public ResponseEntity updateLearnerWithCredentials(@PathVariable Long learnerId, @RequestBody Learner learner) { + Learner existinglearner = credentialService.getLearnerWithCredentialsById(learnerId); + if (existinglearner != null) { + learner.setId(existinglearner.getId()); + Learner updatedLearner = credentialService.updateLearnerWithCredentials(learner); + return ResponseEntity.ok(updatedLearner); + } else { + return ResponseEntity.notFound().build(); + } + } + + @DeleteMapping("/delete/{learnerId}") + public ResponseEntity deleteLearnerWithCredentials(@PathVariable Long learnerId) { + Learner existinglearner = credentialService.getLearnerWithCredentialsById(learnerId); + if (existinglearner != null) { + credentialService.deleteLearnerWithCredentials(learnerId); + return ResponseEntity.ok("Learner with credentials deleted successfully"); + } else { + return ResponseEntity.notFound().build(); + } + } + + +} + diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java new file mode 100644 index 000000000..4016b1b7d --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java @@ -0,0 +1,115 @@ +package dev.sunbirdrc.claim.controller; + +import dev.sunbirdrc.claim.dto.BarCode; +import dev.sunbirdrc.claim.dto.MailDto; +import dev.sunbirdrc.claim.service.EmailService; +import net.sourceforge.barbecue.Barcode; +import net.sourceforge.barbecue.BarcodeFactory; +import net.sourceforge.barbecue.BarcodeImageHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.imageio.ImageIO; +import javax.xml.bind.DatatypeConverter; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.util.Map; + + +@Controller +public class EmailController { + + @Autowired + private EmailService emailService; + private static final Logger logger = LoggerFactory.getLogger(EmailController.class); + private static final Font BARCODE_TEXT_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 8); + @Autowired + public EmailController(EmailService emailService) { + this.emailService = emailService; + } + + @RequestMapping(value = "/api/v1/sendMail", method = RequestMethod.POST) + public ResponseEntity> sendMail(@RequestHeader HttpHeaders headers, + @RequestBody MailDto requestBody) { + String email = requestBody.getEmailAddress(); + String idLink = requestBody.getCertificate(); + String name = requestBody.getName(); + String credType = requestBody.getCredentialsType(); + String body = prepareBody(idLink, name, credType); + emailService.sendMail(email, credType + " for Student", body); + return new ResponseEntity<>(HttpStatus.OK); + } + + @RequestMapping(value = "/api/v1/barcode", method = RequestMethod.POST) + public ResponseEntity getBarCode(@RequestHeader HttpHeaders headers, + @RequestBody BarCode requestBody) { + BarCode code = new BarCode(); + String barCode = requestBody.getBarCodeText(); + logger.info("In Controller::"+barCode); + String text = null; + try { + text = generateBarcodeImage(barCode); + code.setBarCodeText(barCode); + code.setBarCodeValue(text); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return new ResponseEntity<>(code, HttpStatus.OK); + } + + public static String generateBarcodeImage(String barcodeText) throws Exception { + Barcode barcode = BarcodeFactory.createCode128(barcodeText); + logger.info(barcodeText); + barcode.setFont(BARCODE_TEXT_FONT); + barcode.setResolution(200); + BufferedImage image = BarcodeImageHandler.getImage(barcode); + Graphics2D g = image.createGraphics(); + g.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_OFF); + g.dispose(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageIO.write(image, "png", baos); + String data = DatatypeConverter.printBase64Binary(baos.toByteArray()); + data = data.replaceAll("&","\'&\'"); + data = data.replaceAll("&","\'&\'"); + String imageString = "data:image/png;base64," + data; + + // String html = ""; + //html = Pattern.quote(html); + logger.info(imageString); + return imageString; + } + private String prepareBody(String idLink, String name, String credType) { + + String body = "Hi "+ name + ","+ + "\n" + + " \n" + + "\n" + + "We are pleased to inform you that a " +credType + + + " has been issued to you. You can view and download the credential by using the following link. \n" + + "\n" + + "\n" + + idLink + + " \n" + + "\n" + + "Thank you, \n" + + "\n" + + " "; + return body; + } + + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java new file mode 100644 index 000000000..184edefcb --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java @@ -0,0 +1,55 @@ +package dev.sunbirdrc.claim.controller; + +import dev.sunbirdrc.claim.dto.FileDto; +import dev.sunbirdrc.claim.service.FileService; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +@RestController +@RequestMapping("/api/v1/files/") +@RequiredArgsConstructor +public class FileController { + + @Autowired + FileService fileService; + + + @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) + @RequestMapping("upload") + public ResponseEntity uploadFile( + @RequestParam MultipartFile file) throws IOException { + String fileUrl = null; + FileDto fileDto = fileService.uploadFile(file); + if (fileDto != null) { + fileUrl = fileDto.getFileUrl(); + return ResponseEntity.ok(fileUrl); + } + return (ResponseEntity) ResponseEntity.status(HttpStatus.EXPECTATION_FAILED); + } + + @RequestMapping("download") + @PostMapping(produces = {MediaType.APPLICATION_PDF_VALUE}) + public ResponseEntity downloadFile( + @RequestParam(value = "fileName", required = false) String fileName) { + ByteArrayResource resource = fileService.downloadFile(fileName); + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_DISPOSITION, "filename=\"" + fileName + "\""); + return ResponseEntity.ok(). + contentType(MediaType.APPLICATION_PDF). + headers(headers).body(resource); + } +} + diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/BarCode.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/BarCode.java new file mode 100644 index 000000000..8851494c3 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/BarCode.java @@ -0,0 +1,28 @@ +package dev.sunbirdrc.claim.dto; + +public class BarCode { + String barCodeText; + String barCodeValue; + + public String getBarCodeText() { + return barCodeText; + } + + public void setBarCodeText(String barCodeText) { + this.barCodeText = barCodeText; + } + + + + public String getBarCodeValue() { + return barCodeValue; + } + + public void setBarCodeValue(String barCodeValue) { + this.barCodeValue = barCodeValue; + } + + + + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/FileDto.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/FileDto.java new file mode 100644 index 000000000..7544b64ff --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/FileDto.java @@ -0,0 +1,12 @@ +package dev.sunbirdrc.claim.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class FileDto { + + private String fileName; + private String fileUrl; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/MailDto.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/MailDto.java new file mode 100644 index 000000000..b9fdb2c5a --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/MailDto.java @@ -0,0 +1,45 @@ +package dev.sunbirdrc.claim.dto; + + +public class MailDto { + private String name; + private String certificate; + private String emailAddress; + + private String credentialsType; + + public String getCredentialsType() { + return credentialsType; + } + + public void setCredentialsType(String credentialsType) { + this.credentialsType = credentialsType; + } + + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCertificate() { + return certificate; + } + + public void setCertificate(String certificate) { + this.certificate = certificate; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/StudentDTO.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/StudentDTO.java new file mode 100644 index 000000000..376388d2e --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/StudentDTO.java @@ -0,0 +1,19 @@ +package dev.sunbirdrc.claim.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class StudentDTO { + @JsonProperty("rollNo") + private String rollNo; + + @JsonProperty("dob") + private String dob; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Candidate.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Candidate.java new file mode 100644 index 000000000..8838f8d20 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Candidate.java @@ -0,0 +1,80 @@ +package dev.sunbirdrc.claim.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import dev.sunbirdrc.claim.status.Status; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.Date; +import java.util.List; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Candidate { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="title") + private String title; + + @Column(name="firstName") + private String firstName; + + @Column(name="middleName") + private String middleName; + + @Column(name="lastName") + private String lastName; + + @Column(name="motherName") + private String motherName; + + @Column(name="fatherName") + private String fatherName; + + @Column(name="dob") + @JsonFormat(pattern = "dd-MM-yyyy") + private Date dob; + + @Column(name="gender") + private String gender; + + @Column(name="address") + private String address; + + @Column(name="district") + private String district; + + @Column(name="state") + private String state; + + @Column(name="country") + private String country; + + @Column(name="pinCode") + private String pinCode; + + @Column(name="mobileNumber") + private String mobileNumber; + + @Column(name="emailId") + private String emailId; + + @Column(name="aadharNumber") + private String aadharNumber; + + @OneToMany(mappedBy = "candidate", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private List courses; + + @Column(name="status") + @Enumerated(EnumType.STRING) + private Status status; + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java index 175088a50..a16d9a875 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java @@ -131,7 +131,10 @@ public String toString() { } public boolean isClosed() { - return status != null && status.equals(ClaimStatus.CLOSED.name()); + + boolean closed = status != null && status.equals(ClaimStatus.REJECTED.name()) || status.equals(ClaimStatus.APPROVED.name()); + + return closed; } public String getConditions() { @@ -212,4 +215,4 @@ public String getAttestorUserId() { public void setAttestorUserId(String attestorUserId) { this.attestorUserId = attestorUserId; } -} +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/ClaimUser.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/ClaimUser.java new file mode 100644 index 000000000..faa99f74f --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/ClaimUser.java @@ -0,0 +1,32 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.Builder; +import lombok.Data; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; + +@Builder +@Data +@Entity +@Table(name = "claim_kc_user") +public class ClaimUser { + @Id + @GeneratedValue(generator = "UUID") + @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") + @Column(updatable = false, nullable = false) + private String id; + + @Column + private String userId; + @Column + private String userName; + @Column + private String firstName; + @Column + private String lastName; + @Column + private String email; + @Column + private Boolean enabled; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Course.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Course.java new file mode 100644 index 000000000..9e518501d --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Course.java @@ -0,0 +1,59 @@ +package dev.sunbirdrc.claim.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.Date; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Course { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="courseName") + private String courseName; + + @Column(name="collegeName") + private String collegeName; + + @Column(name="examiningBody") + private String examiningBody; + + @Column(name="finalYearRollNo") + private String finalYearRollNo; + + @Column(name="joiningMonth") + private String joiningMonth; + + @Column(name="joiningYear") + private String joiningYear; + + @Column(name="passingMonth") + private String passingMonth; + + @Column(name="passingYear") + private String passingYear; + + @Column(name="armyRegdNo") + private String armyRegdNo; + + @Column(name="date") + @JsonFormat(pattern = "dd-MM-yyyy") + private Date date; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "candidate_id") + @JsonIgnore + private Candidate candidate; + +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Credentials.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Credentials.java new file mode 100644 index 000000000..3405dbd57 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Credentials.java @@ -0,0 +1,50 @@ +package dev.sunbirdrc.claim.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.beans.factory.annotation.Value; + +import javax.persistence.*; +import java.util.Date; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Credentials { + @Value("${gcs.api.url}") + public static String HTTP_LOCALHOST_8080_API_V_1_FILES_DOWNLOAD_FILE_NAME = "http://localhost:8082/api/v1/files/download?fileName="; + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + private Long id; + + @Column(name = "course",unique=true) + private String course; + + @Column(name = "credentialName",unique=true) + private String credentialName; + + @Column(name = "issueDate") + @JsonFormat(pattern = "dd-MM-yyyy") + private Date issueDate; + + @Column(name = "credentialURL") + private String credentialURL; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "learner_id") + @JsonIgnore + private Learner learner; + @PrePersist + public void addPrefixAndPostfix() { + if (credentialURL != null) { + credentialURL = HTTP_LOCALHOST_8080_API_V_1_FILES_DOWNLOAD_FILE_NAME + credentialURL + ".PDF"; + } + } + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Learner.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Learner.java new file mode 100644 index 000000000..62ae0cdb3 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Learner.java @@ -0,0 +1,33 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.List; +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +@Table(name = "learner") +public class Learner { + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "rollNumber") + private String rollNumber; + + @Column(name = "registrationNumber") + private String registrationNumber; + + @OneToMany(mappedBy = "learner", cascade = CascadeType.ALL ,fetch = FetchType.LAZY) + private List credentialsList; +} + diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Student.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Student.java new file mode 100644 index 000000000..a9061b128 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Student.java @@ -0,0 +1,27 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.Date; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + private Long id; + + @Column(unique=true) + private String rollNo; + + @Column(name="dob") + private Date dob; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentDetails.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentDetails.java new file mode 100644 index 000000000..379dc4a43 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentDetails.java @@ -0,0 +1,90 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.List; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class StudentDetails { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column (name="name") + private String name; + + @Column (name="fatherName") + private String fatherName; + + @Column (name="motherName") + private String motherName; + + @Column(unique=true) + private String rollNumber; + + @Column(unique=true) + private String regNumber; + + @Column (name="course") + private String course; + + @Column (name="trainingCenter") + private String trainingCenter; + + @Column (name="trainingPeriod") + private String trainingPeriod; + + @Column (name="examBody") + private String examBody; + + @Column (name="examYear") + private String examYear; + + @Column (name="examMonth") + private String examMonth; + + @Column (name="enrollNo") + private String enrollNo; + + @Column (name="orgLogo") + private String orgLogo; + + @Column (name="barCode") + private String barcode; + + @Column (name="candidatePic") + private String candidatePic; + + @Column (name="signaturePic") + private String signaturePic; + + @Column (name="trainingCenterCode") + private String trainingCenterCode; + + @Column (name="dated") + private String dated; + + @Column (name="trainingTitle") + private String trainingTitle; + + @Column (name="trainingCode") + private String trainingCode; + + @Column (name="credType") + private String credType; + + @OneToMany(mappedBy = "studentDetails", cascade = CascadeType.ALL) + private List yearsOfCourseList; + + @OneToMany(mappedBy = "studentDetails", cascade = CascadeType.ALL) + private List subjectList; + +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentRequest.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentRequest.java new file mode 100644 index 000000000..03871014f --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentRequest.java @@ -0,0 +1,34 @@ +package dev.sunbirdrc.claim.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.Date; +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class StudentRequest { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="rollNumber") + private String rollNumber; + + @Column(name="regNumber") + private String regNumber; + + @Column(name="dob") + @JsonFormat(pattern = "dd-MM-yyyy") + private Date dob; + + @Column(name="email") + private String email; + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Subject.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Subject.java new file mode 100644 index 000000000..c3200a7bf --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Subject.java @@ -0,0 +1,40 @@ +package dev.sunbirdrc.claim.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Subject { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="name") + private String name; + + @Column (name="maxExt") + private String maxExt; + + @Column (name="maxInt") + private String maxInt; + + @Column (name="obtExt") + private String obtExt; + + @Column (name="obtInt") + private String obtInt; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "student_details_id") + @JsonIgnore + private StudentDetails studentDetails; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/YearsOfCourse.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/YearsOfCourse.java new file mode 100644 index 000000000..da3b98450 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/YearsOfCourse.java @@ -0,0 +1,48 @@ +package dev.sunbirdrc.claim.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class YearsOfCourse { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name="courseYear") + private String courseYear; + + @Column (name="examYear") + private String examYear; + + @Column (name="examMonth") + private String examMonth; + + @Column (name="result") + private String result; + + @Column (name="totalMarksObtained") + private String totalMarksObtained; + + @Column (name="totalMarksObtainedInWord") + private String totalMarksObtainedInWord; + + @Column (name="maxTotal") + private String maxTotal; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "student_details_id") + @JsonIgnore + private StudentDetails studentDetails; + + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/exception/BadRequestException.java b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/BadRequestException.java new file mode 100644 index 000000000..45f57a8f9 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/BadRequestException.java @@ -0,0 +1,14 @@ +package dev.sunbirdrc.claim.exception; + +import lombok.Data; + +@Data +public class BadRequestException extends RuntimeException{ + + private final String message; + + public BadRequestException(String message) { + super(message); + this.message = message; + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/exception/FileWriteException.java b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/FileWriteException.java new file mode 100644 index 000000000..3e6276332 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/FileWriteException.java @@ -0,0 +1,14 @@ +package dev.sunbirdrc.claim.exception; + +import lombok.Data; + +@Data +public class FileWriteException extends RuntimeException{ + + private final String message; + + public FileWriteException(String message) { + super(message); + this.message = message; + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/exception/GCPFileUploadException.java b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/GCPFileUploadException.java new file mode 100644 index 000000000..0f849d675 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/GCPFileUploadException.java @@ -0,0 +1,14 @@ +package dev.sunbirdrc.claim.exception; + +import lombok.Data; + +@Data +public class GCPFileUploadException extends RuntimeException{ + + private final String message; + + public GCPFileUploadException(String message) { + super(message); + this.message = message; + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/exception/InvalidFileTypeException.java b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/InvalidFileTypeException.java new file mode 100644 index 000000000..5d1dbfc42 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/InvalidFileTypeException.java @@ -0,0 +1,14 @@ +package dev.sunbirdrc.claim.exception; + +import lombok.Data; + +@Data +public class InvalidFileTypeException extends RuntimeException{ + + private final String message; + + public InvalidFileTypeException(String message) { + super(message); + this.message = message; + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/model/ClaimStatus.java b/java/claim/src/main/java/dev/sunbirdrc/claim/model/ClaimStatus.java index 3269e3278..76a179652 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/model/ClaimStatus.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/model/ClaimStatus.java @@ -2,5 +2,7 @@ public enum ClaimStatus { OPEN, - CLOSED; -} + APPROVED, + NEW, + REJECTED; +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CandidateRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CandidateRepository.java new file mode 100644 index 000000000..6a701c631 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CandidateRepository.java @@ -0,0 +1,10 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.Candidate; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CandidateRepository extends JpaRepository { + boolean existsByEmailId(String emailId); +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimUserRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimUserRepository.java new file mode 100644 index 000000000..6fb845d91 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimUserRepository.java @@ -0,0 +1,9 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.ClaimUser; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ClaimUserRepository extends JpaRepository { +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CourseRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CourseRepository.java new file mode 100644 index 000000000..3ddceba5d --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CourseRepository.java @@ -0,0 +1,9 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.Course; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CourseRepository extends JpaRepository { +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CredentialsRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CredentialsRepository.java new file mode 100644 index 000000000..7f999b507 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CredentialsRepository.java @@ -0,0 +1,10 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.Credentials; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CredentialsRepository extends JpaRepository { + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/LearnerRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/LearnerRepository.java new file mode 100644 index 000000000..80f3c4b1f --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/LearnerRepository.java @@ -0,0 +1,14 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.Learner; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface LearnerRepository extends JpaRepository { + List findByName(String name); + List findByRollNumber(String rollNumber); + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/YearOfCourseRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/YearOfCourseRepository.java new file mode 100644 index 000000000..0681b5a3d --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/YearOfCourseRepository.java @@ -0,0 +1,9 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.YearsOfCourse; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface YearOfCourseRepository extends JpaRepository { +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java index 02cd33b13..3101bbfd2 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java @@ -10,6 +10,7 @@ import dev.sunbirdrc.claim.model.ClaimStatus; import dev.sunbirdrc.claim.repository.ClaimNoteRepository; import dev.sunbirdrc.claim.repository.ClaimRepository; +import dev.sunbirdrc.pojos.attestation.Action; import dev.sunbirdrc.registry.middleware.util.EntityUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -94,7 +95,16 @@ private Claim updateClaim(JsonNode requestBody, Claim claim) { addNotes(requestBody.get(NOTES).asText(), claim, EntityUtil.getFullNameOfTheEntity(attestorNode)); } claim.setAttestedOn(new Date()); - claim.setStatus(ClaimStatus.CLOSED.name()); + String action = requestBody.get("action").asText(); + if(Action.REJECT_CLAIM.toString().equals(action)){ + claim.setStatus(ClaimStatus.REJECTED.name()); + } else if (Action.GRANT_CLAIM.toString().equals(action)) { + claim.setStatus(ClaimStatus.APPROVED.name()); + }else if (Action.RAISE_CLAIM.toString().equals(action)) { + claim.setStatus(ClaimStatus.NEW.name()); + }else + claim.setStatus(ClaimStatus.OPEN.name()); + claim.setAttestorUserId(requestBody.get(USER_ID).asText()); return claimRepository.save(claim); } @@ -120,4 +130,4 @@ public ClaimWithNotesDTO generateNotesForTheClaim(Claim claim) { claimWithNotesDTO.setClaim(claim); return claimWithNotesDTO; } -} +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/CredentialsService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CredentialsService.java new file mode 100644 index 000000000..3cec0f5c2 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CredentialsService.java @@ -0,0 +1,91 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.entity.Credentials; +import dev.sunbirdrc.claim.entity.Learner; +import dev.sunbirdrc.claim.repository.CredentialsRepository; +import dev.sunbirdrc.claim.repository.LearnerRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class CredentialsService { + @Autowired + private CredentialsRepository credentialsRepository; + @Autowired + private LearnerRepository learnerRepository; + private static final Logger logger = LoggerFactory.getLogger(CredentialsService.class); + + public CredentialsService(LearnerRepository learnerRepository, CredentialsRepository credentialsRepository) { + this.learnerRepository = learnerRepository; + this.credentialsRepository = credentialsRepository; + } + + public void saveLearnerWithCredentials(Learner learner) { + String rollNumber = learner.getRollNumber(); + List learnersWithSameRollNumber = learnerRepository.findByRollNumber(rollNumber); + Learner existingLearner = null; + if (!learnersWithSameRollNumber.isEmpty()) { + existingLearner = learnersWithSameRollNumber.get(0); + logger.warn("Roll number " + rollNumber + " already exists."); + } + + if (existingLearner != null) { + List credentialsList = learner.getCredentialsList(); + for (Credentials credentials : credentialsList) { + credentials.setLearner(existingLearner); + credentialsRepository.save(credentials); + } + + logger.info("Credentials saved successfully for the learner with existing roll number"); + } else { + learnerRepository.save(learner); + logger.info("Learner saved successfully"); + + List credentialsList = learner.getCredentialsList(); + for (Credentials credentials : credentialsList) { + credentials.setLearner(learner); + credentialsRepository.save(credentials); + } + + logger.info("Credentials saved successfully for the learner"); + } + } + + + + public List getAllLearnerWithCredentials() { + return learnerRepository.findAll(); + } + + public Learner getLearnerWithCredentialsById(Long learnerId) { + return learnerRepository.findById(learnerId).orElse(null); + } + + + public Learner updateLearnerWithCredentials(Learner learner) { + return learnerRepository.save(learner); + } + + public void deleteLearnerWithCredentials(Long learnerId) { + learnerRepository.deleteById(learnerId); + } + + public List getLearnerWithCredentialsByName(String learnerName) { + return learnerRepository.findByName(learnerName); + } + public Learner getLearnerWithCredentialsByRollNumber(String rollNumber) { + List learners = learnerRepository.findByRollNumber(rollNumber); + if (!learners.isEmpty()) { + return learners.get(0); + } else { + return null; + } + } + + + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java new file mode 100644 index 000000000..a40f8dcd3 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java @@ -0,0 +1,102 @@ +package dev.sunbirdrc.claim.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mail.MailException; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.mail.javamail.MimeMessagePreparator; +import org.springframework.stereotype.Service; + +import javax.mail.Message; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; +import java.io.File; + +@Service("emailService") +public class EmailService +{ + @Autowired + private JavaMailSender mailSender; + + @Autowired + private SimpleMailMessage preConfiguredMessage; + + /** + * This method will send compose and send the message + * */ + public void sendMail(String to, String subject, String body) + { + SimpleMailMessage message = new SimpleMailMessage(); + message.setTo(to); + message.setFrom("shishir.suman@tarento.com"); + message.setSubject(subject); + message.setText(body); + mailSender.send(message); + } + + /** + * This method will send a pre-configured message + * */ + public void sendPreConfiguredMail(String message) + { + SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage); + mailMessage.setText(message); + mailSender.send(mailMessage); + } + + public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach) + { + MimeMessagePreparator preparator = new MimeMessagePreparator() + { + public void prepare(MimeMessage mimeMessage) throws Exception + { + mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); + mimeMessage.setFrom(new InternetAddress("admin@gmail.com")); + mimeMessage.setSubject(subject); + mimeMessage.setText(body); + + FileSystemResource file = new FileSystemResource(new File(fileToAttach)); + MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); + helper.addAttachment("logo.jpg", file); + } + }; + + try { + mailSender.send(preparator); + } + catch (MailException ex) { + // simply log it and go on... + System.err.println(ex.getMessage()); + } + } + + public void sendMailWithInlineResources(String to, String subject, String fileToAttach) + { + MimeMessagePreparator preparator = new MimeMessagePreparator() + { + public void prepare(MimeMessage mimeMessage) throws Exception + { + mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); + mimeMessage.setFrom(new InternetAddress("admin@gmail.com")); + mimeMessage.setSubject(subject); + + MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); + + helper.setText("", true); + + FileSystemResource res = new FileSystemResource(new File(fileToAttach)); + helper.addInline("identifier1234", res); + } + }; + + try { + mailSender.send(preparator); + } + catch (MailException ex) { + // simply log it and go on... + System.err.println(ex.getMessage()); + } + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java new file mode 100644 index 000000000..2e9c26b59 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java @@ -0,0 +1,14 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.dto.FileDto; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +public interface FileService { + + ByteArrayResource downloadFile(String fileName); + + FileDto uploadFile(MultipartFile file) throws IOException; +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java new file mode 100644 index 000000000..8ae6d67bd --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java @@ -0,0 +1,57 @@ +package dev.sunbirdrc.claim.service; + +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import dev.sunbirdrc.claim.dto.FileDto; +import dev.sunbirdrc.claim.exception.GCPFileUploadException; +import dev.sunbirdrc.claim.utils.GCPBucketUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + + +@Service +@RequiredArgsConstructor +public class FileServiceImpl implements FileService { + + @Value("dev-public-upsmf") + private String bucketName; + @Value("${gcp.dir.name}") + private String gcpDirectoryName; + @Autowired + Storage storage; + private final GCPBucketUtil dataBucketUtil; + + @Override + public ByteArrayResource downloadFile(String fileName) { + ByteArrayResource resource = null; + Blob blob = dataBucketUtil.DownloadFile(fileName); + if(blob!=null){ + resource = new ByteArrayResource(blob.getContent()); + } + return resource; + } + + + @Override + public FileDto uploadFile(MultipartFile file) throws IOException { + String originalFileName = file.getOriginalFilename(); + FileDto fileDto = null; + Path path = new File(originalFileName).toPath(); + try { + String contentType = Files.probeContentType(path); + fileDto = dataBucketUtil.uploadFile(file, originalFileName, contentType); + } catch (Exception e) { + throw new GCPFileUploadException("Error occurred while uploading"); + } + return fileDto; + } +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/status/Status.java b/java/claim/src/main/java/dev/sunbirdrc/claim/status/Status.java new file mode 100644 index 000000000..376637b49 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/status/Status.java @@ -0,0 +1,8 @@ +package dev.sunbirdrc.claim.status; + +public enum Status { + Pending, + Approved, + Rejected, + +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/utils/GCPBucketUtil.java b/java/claim/src/main/java/dev/sunbirdrc/claim/utils/GCPBucketUtil.java new file mode 100644 index 000000000..a53d53c8b --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/utils/GCPBucketUtil.java @@ -0,0 +1,150 @@ + +package dev.sunbirdrc.claim.utils; + +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Bucket; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import dev.sunbirdrc.claim.dto.FileDto; +import dev.sunbirdrc.claim.exception.BadRequestException; +import dev.sunbirdrc.claim.exception.FileWriteException; +import dev.sunbirdrc.claim.exception.GCPFileUploadException; +import dev.sunbirdrc.claim.exception.InvalidFileTypeException; +import net.bytebuddy.utility.RandomString; +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.concurrent.TimeUnit; + +@Component +public class GCPBucketUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(GCPBucketUtil.class); + + @Value("${gcp.config.file}") + private String gcpConfigFile; + + @Value("${gcp.project.id}") + private String gcpProjectId; + + @Value("${gcp.bucket.id}") + private String gcpBucketId; + + @Value("${gcp.dir.name}") + private String gcpDirectoryName; + + @Value("${gcp.file.validity}") + private Integer validity; + + + public FileDto uploadFile(MultipartFile multipartFile, String fileName, String contentType) { + + try{ + + LOGGER.debug("Start file uploading process on GCS"); + byte[] fileData = FileUtils.readFileToByteArray(convertFile(multipartFile)); + + InputStream inputStream = new ClassPathResource(gcpConfigFile).getInputStream(); + + StorageOptions options = StorageOptions.newBuilder().setProjectId(gcpProjectId) + .setCredentials(GoogleCredentials.fromStream(inputStream)).build(); + Storage storage = options.getService(); + + Bucket bucket = storage.get(gcpBucketId,Storage.BucketGetOption.fields()); + + Blob blob = bucket.create(gcpDirectoryName + "/" + fileName, fileData, contentType); + LOGGER.debug("Storing GCS file:"+fileName); + validity=validity > 10 ? 10 : validity; + URL url = blob.signUrl(validity, TimeUnit.HOURS,Storage.SignUrlOption.withV4Signature()); + String fileUrl = url.toString(); + LOGGER.debug("File url of GCS: "+fileUrl); + + if(blob != null){ + LOGGER.debug("File successfully uploaded to GCS"); + return new FileDto(blob.getName(), fileUrl); + } + + }catch (GCPFileUploadException e){ + LOGGER.error("An error occurred while uploading data. Exception: ", e); + throw new GCPFileUploadException("An error occurred while storing data to GCS"); + } catch (IOException e) { + throw new RuntimeException(e); + } + throw new GCPFileUploadException("An error occurred while storing data to GCS"); + } + + public Blob DownloadFile(String fileName) { + try{ + LOGGER.debug("Start file Download process on GCS"); + InputStream inputStream = new ClassPathResource(gcpConfigFile).getInputStream(); + + StorageOptions options = StorageOptions.newBuilder().setProjectId(gcpProjectId) + .setCredentials(GoogleCredentials.fromStream(inputStream)).build(); + + Storage storage = options.getService(); + Bucket bucket = storage.get(gcpBucketId,Storage.BucketGetOption.fields()); + + RandomString id = new RandomString(); + Blob blob = bucket.get(gcpDirectoryName+"/" + fileName); + return blob; + }catch (GCPFileUploadException e){ + LOGGER.error("An error occurred while Downloading data. Exception: ", e); + throw new GCPFileUploadException("An error occurred while Downloading from GCS"); + } catch (IOException e) { + throw new RuntimeException(e); + } + + } + + private File convertFile(MultipartFile file) { + FileOutputStream outputStream = null; + try{ + if(file.getOriginalFilename() == null){ + throw new BadRequestException("Original file name is null"); + } + File convertedFile = new File(file.getOriginalFilename()); + outputStream = new FileOutputStream(convertedFile); + outputStream.write(file.getBytes()); + LOGGER.debug("Converting multipart file : {}", convertedFile); + return convertedFile; + }catch (Exception e){ + throw new FileWriteException("An error has occurred while converting the file"); + }finally { + if(outputStream!=null) + try { + outputStream.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + } + + private String checkFileExtension(String fileName) { + if(fileName != null && fileName.contains(".")){ + String[] extensionList = {".png", ".jpeg", ".pdf",".PDF", ".doc", ".mp3"}; + + for(String extension: extensionList) { + if (fileName.endsWith(extension)) { + LOGGER.debug("Accepted file type : {}", extension); + return extension; + } + } + } + LOGGER.error("Not a permitted file type"); + throw new InvalidFileTypeException("Not a permitted file type"); + } + +} + diff --git a/java/claim/src/main/resources/application.properties b/java/claim/src/main/resources/application.properties index 51a497d85..cada3cd1e 100644 --- a/java/claim/src/main/resources/application.properties +++ b/java/claim/src/main/resources/application.properties @@ -1,6 +1,6 @@ server.port=8082 -spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://0.0.0.0:5432/registry} +spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry} spring.datasource.username=${connectionInfo_username:postgres} spring.datasource.password=${connectionInfo_password:postgres} @@ -8,4 +8,38 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true -sunbirdrc.url=${sunbirdrc_url:http://localhost:8081} \ No newline at end of file +sunbirdrc.url=${sunbirdrc_url:http://localhost:8081} +spring.mail.host=smtp.sendgrid.net +spring.mail.port=587 +spring.mail.username=apikey + +spring.mail.password= + + +# Other properties +spring.mail.properties.mail.debug=true +spring.mail.properties.mail.transport.protocol=smtp +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.connectiontimeout=50000000 +spring.mail.properties.mail.smtp.timeout=15000000 +spring.mail.properties.mail.smtp.writetimeout=150000000 + +# TLS , port 587 +spring.mail.properties.mail.smtp.starttls.enable=true + +### GCP file storage configuration +spring.cloud.gcp.project-id=upsmf-368011 +gcp.project-id=upsmf-368011 +gcp.project.id=upsmf-368011 +spring.cloud.gcp.credentials.location=classpath:claim-ms.json +gcp.credentials.location=claim-ms.json +gcp.config.file=claim-ms.json +gcp.bucket.name=dev-public-upsmf +gcp.bucket.id=dev-public-upsmf +gcp.dir.name=issuance +gcp.file.validity=2 + +spring.servlet.multipart.max-file-size=10MB +spring.servlet.multipart.max-request-size=10MB + + diff --git a/java/claim/src/test/java/dev/sunbirdrc/claim/service/ClaimServiceTest.java b/java/claim/src/test/java/dev/sunbirdrc/claim/service/ClaimServiceTest.java index 76012d617..764627354 100644 --- a/java/claim/src/test/java/dev/sunbirdrc/claim/service/ClaimServiceTest.java +++ b/java/claim/src/test/java/dev/sunbirdrc/claim/service/ClaimServiceTest.java @@ -24,8 +24,7 @@ import java.util.*; import static dev.sunbirdrc.claim.contants.AttributeNames.*; -import static dev.sunbirdrc.claim.model.ClaimStatus.CLOSED; -import static dev.sunbirdrc.claim.model.ClaimStatus.OPEN; +import static dev.sunbirdrc.claim.model.ClaimStatus.*; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -122,7 +121,7 @@ public void attestClaimShouldThrowExceptionIfTheClaimIsNotFound() { public void attestClaimShouldThrowExceptionIfTheClaimIsAlreadyProcessed() { String id = "1"; Claim claim = getClaim(id); - claim.setStatus(CLOSED.name()); + claim.setStatus(APPROVED.name()); when(claimRepository.findById(id)).thenReturn(Optional.of(claim)); JsonNode dummyNode = new ObjectMapper().nullNode(); claimService.attestClaim(id, dummyNode); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java index bf28e1cb2..7984ad3c6 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java @@ -59,6 +59,7 @@ public FilterRegistrationBean corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin(corsAllowedOrigin); + config.addAllowedOrigin("http://localhost:4200"); config.addAllowedHeader("*"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 5b29c2af9..74050ad42 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -10,6 +10,10 @@ import dev.sunbirdrc.pojos.PluginResponseMessage; import dev.sunbirdrc.pojos.Response; import dev.sunbirdrc.pojos.ResponseParams; +import dev.sunbirdrc.registry.digilocker.pulldoc.PullDocRequest; +import dev.sunbirdrc.registry.digilocker.pulldoc.PullDocResponse; +import dev.sunbirdrc.registry.digilocker.pulluriresponse.Person; +import dev.sunbirdrc.registry.digilocker.pulluriresponse.PullURIResponse; import dev.sunbirdrc.registry.entities.AttestationPolicy; import dev.sunbirdrc.registry.exception.AttestationNotFoundException; import dev.sunbirdrc.registry.exception.ErrorMessages; @@ -20,13 +24,15 @@ import dev.sunbirdrc.registry.middleware.util.JSONUtil; import dev.sunbirdrc.registry.middleware.util.OSSystemFields; import dev.sunbirdrc.registry.service.FileStorageService; -import dev.sunbirdrc.registry.service.ICertificateService; +import dev.sunbirdrc.registry.service.impl.CertificateServiceImpl; import dev.sunbirdrc.registry.transform.Configuration; import dev.sunbirdrc.registry.transform.Data; import dev.sunbirdrc.registry.transform.ITransformer; +import org.agrona.Strings; +import dev.sunbirdrc.registry.util.DigiLockerUtils; +import dev.sunbirdrc.registry.util.DocDetails; import dev.sunbirdrc.registry.util.ViewTemplateManager; import dev.sunbirdrc.validators.ValidationException; -import org.agrona.Strings; import org.apache.commons.lang3.StringUtils; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.jetbrains.annotations.NotNull; @@ -44,6 +50,7 @@ import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; +import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.*; @@ -55,9 +62,12 @@ public class RegistryEntityController extends AbstractController { private static final String TRANSACTION_ID = "transactionId"; private static Logger logger = LoggerFactory.getLogger(RegistryEntityController.class); - + @Value("${GCS_SERVICE_URL:https://casa.upsmfac.org/UploadedFiles/Student/}") + public static final String GCS_SERVICE_URL = "http://34.100.212.156:8082/"; + @Value("${digilocker_hmackey:}") + public static final String DIGILOCKER_KEY = "vTV3Jl81kXDOca70TT2+P/YAb5DXnS+DDr/ArlFhow0="; @Autowired - private ICertificateService certificateService; + private CertificateServiceImpl certificateService; @Autowired private FileStorageService fileStorageService; @@ -470,6 +480,37 @@ public ResponseEntity getEntityWithConsent( } } + @RequestMapping(value = "/api/v2/{entityName}", method = RequestMethod.GET) + public ResponseEntity getUserDetails( + @PathVariable String entityName, + HttpServletRequest request) { + ResponseParams responseParams = new ResponseParams(); + try { + checkEntityNameInDefinitionManager(entityName); + ArrayList fields = getConsentFields(request); + JsonNode userInfoFromRegistry = registryHelper.getRequestedUserDetailsSearch(request, entityName); + JsonNode jsonNode = userInfoFromRegistry.get(entityName); + if (jsonNode instanceof ArrayNode) { + ArrayNode values = (ArrayNode) jsonNode; + if (values.size() > 0) { + JsonNode node = values.get(0); + if (node instanceof ObjectNode) { + ObjectNode entityNode = copyWhiteListedFields(fields, node); + return new ResponseEntity<>(entityNode, HttpStatus.OK); + } + } + } + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + Response response = new Response(Response.API_ID.GET, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + logger.error("Error in partner api access", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + private ObjectNode copyWhiteListedFields(ArrayList fields, JsonNode dataNode) { ObjectNode node = JsonNodeFactory.instance.objectNode(); for (String key : fields) { @@ -900,4 +941,154 @@ public ResponseEntity revokeACredential ( return new ResponseEntity<>(response,HttpStatus.INTERNAL_SERVER_ERROR); } } + + /** + * PULL-URI-Request API for DigiLocker + * @param request + * @param entityName + * @return + */ + @RequestMapping(value = "/api/v1/pullUriRequest/{entityName}", method = RequestMethod.POST, produces = + {MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_PDF_VALUE, MediaType.TEXT_HTML_VALUE, Constants.SVG_MEDIA_TYPE}) + public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest request, @PathVariable String entityName) { + + //String entityName = "RegCertificate"; - take entity name from input - TODO + // call template TODO + + String templateurl = null; + + String statusCode = "1"; + Scanner scanner = null; + try { + scanner = new Scanner(request.getInputStream(), "UTF-8"); + } catch (IOException e) { + throw new RuntimeException(e); + } + String xmlString = null; + if(scanner!=null){ + Scanner scanner1 = scanner.useDelimiter("\\A"); + if(scanner1.hasNext()) + xmlString = scanner1.next(); + } + DocDetails docDetails = null; + // Map to JAXB + xmlString = DigiLockerUtils.getXmlString(xmlString); + //request.set + ResponseParams responseParams = new ResponseParams(); + Response response = new Response(Response.API_ID.SEARCH, "OK", responseParams); + String osid = null; + JsonNode result = null; + try { + result = registryHelper.getRequestedUserDetailsCustom(request, entityName, xmlString); + if (result != null && result.get(entityName) != null && result.get(entityName).size() > 0) { + ArrayNode responseFromDb = registryHelper.fetchFromDBUsingEsResponse(entityName, (ArrayNode) result.get(entityName)); + if(responseFromDb!=null && responseFromDb.size() > 0){ + osid = responseFromDb.get(0).get("osid").asText(); + } + } + } catch (Exception e) { + statusCode = "0"; + e.printStackTrace(); + return new ResponseEntity<>(statusCode, HttpStatus.INTERNAL_SERVER_ERROR); + } + + if(osid!=null) { + try { + String readerUserId = getUserId(entityName, request); + JsonNode node = registryHelper.readEntity(readerUserId, entityName, osid, false, null, false) + .get(entityName); + String fileName = DigiLockerUtils.getDocUri(); + JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); + Object certificate = certificateService.getCertificateForDGL(signedNode, + entityName, + osid, + MediaType.APPLICATION_PDF_VALUE, + getTemplateUrlFromRequest(request, entityName), + JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)), fileName + ); + // Push to DGS - verify that storage required or not - TODO + certificateService.saveToGCS(certificate, fileName+".PDF"); + // get Uri + String uri = GCS_SERVICE_URL + fileName + ".PDF"; + + Person person = DigiLockerUtils.getPersonDetail(result, entityName); + PullURIResponse pullResponse = DigiLockerUtils.getPullUriResponse(uri, statusCode, osid, certificate, person); + String responseString = DigiLockerUtils.convertJaxbToString(pullResponse); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_XML); + return new ResponseEntity<>(responseString, headers, HttpStatus.OK); + } catch (Exception exception) { + statusCode = "0"; + exception.printStackTrace(); + return new ResponseEntity<>(statusCode, HttpStatus.BAD_REQUEST); + } + } + else{ + return new ResponseEntity<>(statusCode, HttpStatus.FORBIDDEN); + } + } + + /** + * PULL-URI-Request API for DigiLocker + * @param request + * @param + * @return + */ + + @RequestMapping(value = "/api/v1/pullDocUriRequest/{entityName}", method = RequestMethod.POST, produces = + {MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_XML_VALUE}) + public ResponseEntity pullDocURI(HttpServletRequest request) { + + String entityName = "RegCertificate"; //- take entity name from input - TODO + String statusCode = "1"; + Scanner scanner = null; + String hmac = request.getHeader("x-digilocker-hmac"); + + try { + scanner = new Scanner(request.getInputStream(), "UTF-8"); + } catch (IOException e) { + throw new RuntimeException(e); + } + String xmlString = null; + if(scanner!=null){ + Scanner scanner1 = scanner.useDelimiter("\\A"); + if(scanner1.hasNext()) + xmlString = scanner1.next(); + } + + // GET Request xml and create object + PullDocRequest pullDocRequest = null; + try { + pullDocRequest = DigiLockerUtils.processPullDocRequest(xmlString); + } catch (Exception e) { + throw new RuntimeException(e); + } + boolean isValidReq = DigiLockerUtils.verifyHmac(pullDocRequest.getTs(), DIGILOCKER_KEY, hmac); + if(!isValidReq){ + statusCode = "0"; + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_XML); + return new ResponseEntity<>(statusCode, HttpStatus.FORBIDDEN); + } + String credName = pullDocRequest.getDocDetails().getUri(); + byte[] cred = certificateService.getCred(credName); + JsonNode result = null; + // get stident by osid + String osid = pullDocRequest.getTxn(); + try { + result = registryHelper.getUserInfoFromRegistryByOsId(request, entityName, osid); + Person person = DigiLockerUtils.getPersonDetail(result, entityName); + PullDocResponse pullDocResponse = DigiLockerUtils.getDocPullUriResponse(osid,statusCode, cred,person); + Object responseString = DigiLockerUtils.convertJaxbToPullDoc(pullDocResponse); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_XML); + return new ResponseEntity<>(responseString, headers, HttpStatus.OK); + } catch (Exception e) { + statusCode = "0"; + e.printStackTrace(); + return new ResponseEntity<>(statusCode, HttpStatus.FORBIDDEN); + } + + } + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/Credential.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/Credential.java new file mode 100644 index 000000000..59c8fe1f7 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/Credential.java @@ -0,0 +1,11 @@ +package dev.sunbirdrc.registry.dao; + +import lombok.Data; + +@Data +public class Credential { + private String course; + private String credentialName; + private String credentialURL; + private String issueDate; +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/Learner.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/Learner.java new file mode 100644 index 000000000..14b081c17 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/Learner.java @@ -0,0 +1,14 @@ +package dev.sunbirdrc.registry.dao; + +import lombok.Data; + +import java.util.List; + +@Data +public class Learner { + private String name; + private String rollNumber; + private String enrollmentNumber; + private List credentialsList; + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DataContent.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DataContent.java new file mode 100644 index 000000000..a6517d03d --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DataContent.java @@ -0,0 +1,18 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlValue; + +public class DataContent { + + private Object content; + + @XmlValue + public Object getContent() { + return content; + } + + public void setContent(Object content) { + this.content = content; + } + +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocContent.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocContent.java new file mode 100644 index 000000000..e7cb75d9f --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocContent.java @@ -0,0 +1,19 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlValue; + +public class DocContent { + + private Object content; + + @XmlValue + public Object getContent() { + return content; + } + + public void setContent(Object content) { + this.content = content; + } + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsRq.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsRq.java new file mode 100644 index 000000000..9737c9d5a --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsRq.java @@ -0,0 +1,31 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc;//package dev.sunbirdrc.registry.digilocker.pulldoc; +// +//import javax.xml.bind.annotation.XmlElement; +//import javax.xml.bind.annotation.XmlRootElement; +// +//@XmlRootElement(name = "DocDetails") +//static class DocDetails { +// +// private String uri; +// private String DigiLockerId; +// +// // @XmlElement(name = "URI") +// public String getURI() { +// return uri; +// } +// +// public void setURI(String URI) { +// this.uri = uri; +// } +// +// //@XmlElement(name = "DigiLockerId") +// public String getDigiLockerId() { +// return DigiLockerId; +// } +// +// public void setDigiLockerId(String DigiLockerId) { +// this.DigiLockerId = DigiLockerId; +// } +// +// +//} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsRs.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsRs.java new file mode 100644 index 000000000..0f2575291 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsRs.java @@ -0,0 +1,31 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "DocDetails") +public class DocDetailsRs { + + private Object docContent; + private Object dataContent; + + @XmlElement(name = "DocContent") + public Object getDocContent() { + return docContent; + } + + public void setDocContent(Object docContent) { + this.docContent = docContent; + } + + @XmlElement(name = "DataContent") + public Object getDataContent() { + return dataContent; + } + + public void setDataContent(Object dataContent) { + this.dataContent = dataContent; + } + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsType.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsType.java new file mode 100644 index 000000000..0e7ee6119 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/DocDetailsType.java @@ -0,0 +1,33 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DocDetailsType", propOrder = { + "uri", + "digiLockerId" +}) +public class DocDetailsType { + + protected String uri; + + protected String digiLockerId; + + public String getUri() { + return uri; + } + + public void setUri(String value) { + this.uri = value; + } + + public String getDigiLockerId() { + return digiLockerId; + } + + public void setDigiLockerId(String value) { + this.digiLockerId = value; + } +} + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/Main.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/Main.java new file mode 100644 index 000000000..99b52eb9f --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/Main.java @@ -0,0 +1,74 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.ByteArrayInputStream; +public class Main { + public static void main(String[] args) { + + String xml = "\n" + + "\n" + + " \n" + + " in.gov.kerala.edistrict-INCER-123456\n" + + " 123e4567-e89b-12d3-a456-426655440000\n" + + " \n" + + ""; + + PullDocRequest request = processPullDocRequest(xml); + System.out.println(request.getTxn()); + + } + + public static PullDocRequest processPullDocRequest(String xml) { + PullDocRequest request = new PullDocRequest(); + DocDetailsType docDetails = new DocDetailsType(); + try { + // Create a DocumentBuilderFactory and DocumentBuilder to parse the XML + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + + // Parse the XML string into a Document object + Document document = builder.parse(new ByteArrayInputStream(xml.getBytes())); + Element rootElement = document.getDocumentElement(); + Element docDetailsElement = (Element) rootElement.getElementsByTagName("DocDetails").item(0); + // Get the values of URI and DigiLockerId elements + String uri = docDetailsElement.getElementsByTagName("URI").item(0).getTextContent(); + String digiLockerId = docDetailsElement.getElementsByTagName("DigiLockerId").item(0).getTextContent(); + docDetails.setUri(uri); + docDetails.setDigiLockerId(digiLockerId); + request.setDocDetails(docDetails); + // Print the values + System.out.println("URI: " + uri); + System.out.println("DigiLockerId: " + digiLockerId); + NamedNodeMap attributes = rootElement.getAttributes(); + for (int i = 0; i < attributes.getLength(); i++) { + String attributeName = attributes.item(i).getNodeName(); + String attributeValue = attributes.item(i).getNodeValue(); + switch (attributeName.toLowerCase()) { + case "txn": + request.setTxn(attributeValue); + break; + case "orgid": + request.setOrgId(attributeValue); + break; + case "ts": + request.setTs(attributeValue); + break; + case "format": + request.setFormat(attributeValue); + break; + default: + break; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return request; + } +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/PullDocRequest.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/PullDocRequest.java new file mode 100644 index 000000000..df33b8578 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/PullDocRequest.java @@ -0,0 +1,68 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement +public class PullDocRequest { + @XmlElement(name = "DocDetails", required = true) + protected DocDetailsType docDetails; + protected String ver; + protected String ts; + protected String txn; + protected String orgId; + protected String format; + + public DocDetailsType getDocDetails() { + return docDetails; + } + + public void setDocDetails(DocDetailsType value) { + this.docDetails = value; + } + + public String getVer() { + return ver; + } + + public void setVer(String value) { + this.ver = value; + } + + public String getTs() { + return ts; + } + + public void setTs(String value) { + this.ts = value; + } + + public String getTxn() { + return txn; + } + + public void setTxn(String value) { + this.txn = value; + } + + public String getOrgId() { + return orgId; + } + + public void setOrgId(String value) { + this.orgId = value; + } + + public String getFormat() { + return format; + } + + public void setFormat(String value) { + this.format = value; + } +} + + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/PullDocResponse.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/PullDocResponse.java new file mode 100644 index 000000000..5635c068f --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/PullDocResponse.java @@ -0,0 +1,39 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +@XmlRootElement +public class PullDocResponse implements Serializable { + + private ResponseStatus responseStatus; + private DocDetailsRs docDetails; + + @XmlElement(name = "ResponseStatus") + public ResponseStatus getResponseStatus() { + return responseStatus; + } + + public void setResponseStatus(ResponseStatus responseStatus) { + this.responseStatus = responseStatus; + } + + @XmlElement(name = "DocDetails") + public DocDetailsRs getDocDetails() { + return docDetails; + } + + public void setDocDetails(DocDetailsRs docDetails) { + this.docDetails = docDetails; + } + +} + + + + + + + + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/ResponseStatus.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/ResponseStatus.java new file mode 100644 index 000000000..d7af05cbf --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulldoc/ResponseStatus.java @@ -0,0 +1,41 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name="ResponseStatus") +public class ResponseStatus { + + private String status; + private String ts; + private String txn; + + @XmlAttribute(name = "Status") + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @XmlAttribute(name = "ts") + public String getTs() { + return ts; + } + + public void setTs(String ts) { + this.ts = ts; + } + + @XmlAttribute(name = "txn") + public String getTxn() { + return txn; + } + + public void setTxn(String txn) { + this.txn = txn; + } + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/DocDetails.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/DocDetails.java new file mode 100644 index 000000000..facca870d --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/DocDetails.java @@ -0,0 +1,47 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulluriresponse; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class DocDetails { + private IssuedTo issuedTo; + private String uri; + private Object docContent; + private Object dataContent; + public IssuedTo getIssuedTo() { + return issuedTo; + } + + public void setIssuedTo(IssuedTo issuedTo) { + this.issuedTo = issuedTo; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public Object getDocContent() { + return docContent; + } + + public void setDocContent(Object docContent) { + this.docContent = docContent; + } + + public Object getDataContent() { + return dataContent; + } + + public void setDataContent(Object dataContent) { + this.dataContent = dataContent; + } + + + + + +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/IssuedTo.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/IssuedTo.java new file mode 100644 index 000000000..c376d5c79 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/IssuedTo.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulluriresponse; + + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class IssuedTo { + + private Persons persons; + + @XmlElement(name = "persons") + public Persons getPersons() { + return persons; + } + + public void setPersons(Persons persons) { + this.persons = persons; + } + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/Person.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/Person.java new file mode 100644 index 000000000..af1c644c4 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/Person.java @@ -0,0 +1,51 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulluriresponse; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Person { + + private String name; + private String dob; + private String gender; + private String phone; + + + @XmlAttribute(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlAttribute(name = "dob") + public String getDob() { + return dob; + } + + public void setDob(String dob) { + this.dob = dob; + } + + @XmlAttribute(name = "gender") + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + @XmlAttribute(name = "phone") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/Persons.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/Persons.java new file mode 100644 index 000000000..4624e0bf3 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/Persons.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulluriresponse; + + +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.List; +@XmlRootElement +public class Persons { + + public List getPerson() { + return person; + } + + + public void setPerson(List person) { + this.person = person; + } + + List person = new ArrayList<>(); + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/PhotoBean.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/PhotoBean.java new file mode 100644 index 000000000..07bc3bad0 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/PhotoBean.java @@ -0,0 +1,30 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulluriresponse; + + +import javax.xml.bind.annotation.XmlAttribute; + + +public class PhotoBean { + String format = ""; + String textContent = ""; + + @XmlAttribute(name = "format") + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + @XmlAttribute(name = "TextContent") + public String getTextContent() { + return textContent; + } + + public void setTextContent(String textContent) { + this.textContent = textContent; + } + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/PullURIResponse.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/PullURIResponse.java new file mode 100644 index 000000000..93d101c13 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/PullURIResponse.java @@ -0,0 +1,30 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulluriresponse; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "PullURIResponse", namespace = "http://tempuri.org/") +public class PullURIResponse { + + private ResponseUriStatus responseStatus; + private DocDetails docDetails; + + @XmlElement(name = "ResponseStatus") + public ResponseUriStatus getResponseStatus() { + return responseStatus; + } + + public void setResponseStatus(ResponseUriStatus responseStatus) { + this.responseStatus = responseStatus; + } + + @XmlElement(name = "DocDetails") + public DocDetails getDocDetails() { + return docDetails; + } + + public void setDocDetails(DocDetails docDetails) { + this.docDetails = docDetails; + } + +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/ResponseUriStatus.java b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/ResponseUriStatus.java new file mode 100644 index 000000000..5cc9ac1eb --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/dao/digilocker/pulluriresponse/ResponseUriStatus.java @@ -0,0 +1,41 @@ +package dev.sunbirdrc.registry.dao.digilocker.pulluriresponse; + + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class ResponseUriStatus { + + private String status; + private String ts; + private String txn; + + @XmlAttribute(name = "Status") + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @XmlAttribute(name = "ts") + public String getTs() { + return ts; + } + + public void setTs(String ts) { + this.ts = ts; + } + + @XmlAttribute(name = "txn") + public String getTxn() { + return txn; + } + + public void setTxn(String txn) { + this.txn = txn; + } + + } \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DataContent.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DataContent.java new file mode 100644 index 000000000..999caee7d --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DataContent.java @@ -0,0 +1,18 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlValue; + +public class DataContent { + + private Object content; + + @XmlValue + public Object getContent() { + return content; + } + + public void setContent(Object content) { + this.content = content; + } + +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocContent.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocContent.java new file mode 100644 index 000000000..a004ddce2 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocContent.java @@ -0,0 +1,19 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlValue; + +public class DocContent { + + private Object content; + + @XmlValue + public Object getContent() { + return content; + } + + public void setContent(Object content) { + this.content = content; + } + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRq.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRq.java new file mode 100644 index 000000000..0b36e1936 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRq.java @@ -0,0 +1,31 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc;//package dev.sunbirdrc.registry.digilocker.pulldoc; +// +//import javax.xml.bind.annotation.XmlElement; +//import javax.xml.bind.annotation.XmlRootElement; +// +//@XmlRootElement(name = "DocDetails") +//static class DocDetails { +// +// private String uri; +// private String DigiLockerId; +// +// // @XmlElement(name = "URI") +// public String getURI() { +// return uri; +// } +// +// public void setURI(String URI) { +// this.uri = uri; +// } +// +// //@XmlElement(name = "DigiLockerId") +// public String getDigiLockerId() { +// return DigiLockerId; +// } +// +// public void setDigiLockerId(String DigiLockerId) { +// this.DigiLockerId = DigiLockerId; +// } +// +// +//} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRs.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRs.java new file mode 100644 index 000000000..4758d1dac --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRs.java @@ -0,0 +1,31 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "DocDetails") +public class DocDetailsRs { + + private Object docContent; + private Object dataContent; + + @XmlElement(name = "DocContent") + public Object getDocContent() { + return docContent; + } + + public void setDocContent(Object docContent) { + this.docContent = docContent; + } + + @XmlElement(name = "DataContent") + public Object getDataContent() { + return dataContent; + } + + public void setDataContent(Object dataContent) { + this.dataContent = dataContent; + } + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java new file mode 100644 index 000000000..a31c2e8dc --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java @@ -0,0 +1,33 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DocDetailsType", propOrder = { + "uri", + "digiLockerId" +}) +public class DocDetailsType { + + protected String uri; + + protected String digiLockerId; + + public String getUri() { + return uri; + } + + public void setUri(String value) { + this.uri = value; + } + + public String getDigiLockerId() { + return digiLockerId; + } + + public void setDigiLockerId(String value) { + this.digiLockerId = value; + } +} + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/Main.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/Main.java new file mode 100644 index 000000000..ad6c4c366 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/Main.java @@ -0,0 +1,74 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.ByteArrayInputStream; +public class Main { + public static void main(String[] args) { + + String xml = "\n" + + "\n" + + " \n" + + " in.gov.kerala.edistrict-INCER-123456\n" + + " 123e4567-e89b-12d3-a456-426655440000\n" + + " \n" + + ""; + + PullDocRequest request = processPullDocRequest(xml); + System.out.println(request.getTxn()); + + } + + public static PullDocRequest processPullDocRequest(String xml) { + PullDocRequest request = new PullDocRequest(); + DocDetailsType docDetails = new DocDetailsType(); + try { + // Create a DocumentBuilderFactory and DocumentBuilder to parse the XML + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + + // Parse the XML string into a Document object + Document document = builder.parse(new ByteArrayInputStream(xml.getBytes())); + Element rootElement = document.getDocumentElement(); + Element docDetailsElement = (Element) rootElement.getElementsByTagName("DocDetails").item(0); + // Get the values of URI and DigiLockerId elements + String uri = docDetailsElement.getElementsByTagName("URI").item(0).getTextContent(); + String digiLockerId = docDetailsElement.getElementsByTagName("DigiLockerId").item(0).getTextContent(); + docDetails.setUri(uri); + docDetails.setDigiLockerId(digiLockerId); + request.setDocDetails(docDetails); + // Print the values + System.out.println("URI: " + uri); + System.out.println("DigiLockerId: " + digiLockerId); + NamedNodeMap attributes = rootElement.getAttributes(); + for (int i = 0; i < attributes.getLength(); i++) { + String attributeName = attributes.item(i).getNodeName(); + String attributeValue = attributes.item(i).getNodeValue(); + switch (attributeName.toLowerCase()) { + case "txn": + request.setTxn(attributeValue); + break; + case "orgid": + request.setOrgId(attributeValue); + break; + case "ts": + request.setTs(attributeValue); + break; + case "format": + request.setFormat(attributeValue); + break; + default: + break; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return request; + } +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocRequest.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocRequest.java new file mode 100644 index 000000000..2cfc76d67 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocRequest.java @@ -0,0 +1,68 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement +public class PullDocRequest { + @XmlElement(name = "DocDetails", required = true) + protected DocDetailsType docDetails; + protected String ver; + protected String ts; + protected String txn; + protected String orgId; + protected String format; + + public DocDetailsType getDocDetails() { + return docDetails; + } + + public void setDocDetails(DocDetailsType value) { + this.docDetails = value; + } + + public String getVer() { + return ver; + } + + public void setVer(String value) { + this.ver = value; + } + + public String getTs() { + return ts; + } + + public void setTs(String value) { + this.ts = value; + } + + public String getTxn() { + return txn; + } + + public void setTxn(String value) { + this.txn = value; + } + + public String getOrgId() { + return orgId; + } + + public void setOrgId(String value) { + this.orgId = value; + } + + public String getFormat() { + return format; + } + + public void setFormat(String value) { + this.format = value; + } +} + + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocResponse.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocResponse.java new file mode 100644 index 000000000..434a127c4 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocResponse.java @@ -0,0 +1,39 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +@XmlRootElement +public class PullDocResponse implements Serializable { + + private ResponseStatus responseStatus; + private DocDetailsRs docDetails; + + @XmlElement(name = "ResponseStatus") + public ResponseStatus getResponseStatus() { + return responseStatus; + } + + public void setResponseStatus(ResponseStatus responseStatus) { + this.responseStatus = responseStatus; + } + + @XmlElement(name = "DocDetails") + public DocDetailsRs getDocDetails() { + return docDetails; + } + + public void setDocDetails(DocDetailsRs docDetails) { + this.docDetails = docDetails; + } + +} + + + + + + + + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/ResponseStatus.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/ResponseStatus.java new file mode 100644 index 000000000..b365c0b23 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/ResponseStatus.java @@ -0,0 +1,41 @@ +package dev.sunbirdrc.registry.digilocker.pulldoc; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name="ResponseStatus") +public class ResponseStatus { + + private String status; + private String ts; + private String txn; + + @XmlAttribute(name = "Status") + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @XmlAttribute(name = "ts") + public String getTs() { + return ts; + } + + public void setTs(String ts) { + this.ts = ts; + } + + @XmlAttribute(name = "txn") + public String getTxn() { + return txn; + } + + public void setTxn(String txn) { + this.txn = txn; + } + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/DocDetails.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/DocDetails.java new file mode 100644 index 000000000..40917beee --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/DocDetails.java @@ -0,0 +1,47 @@ +package dev.sunbirdrc.registry.digilocker.pulluriresponse; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class DocDetails { + private IssuedTo issuedTo; + private String uri; + private Object docContent; + private Object dataContent; + public IssuedTo getIssuedTo() { + return issuedTo; + } + + public void setIssuedTo(IssuedTo issuedTo) { + this.issuedTo = issuedTo; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public Object getDocContent() { + return docContent; + } + + public void setDocContent(Object docContent) { + this.docContent = docContent; + } + + public Object getDataContent() { + return dataContent; + } + + public void setDataContent(Object dataContent) { + this.dataContent = dataContent; + } + + + + + +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/IssuedTo.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/IssuedTo.java new file mode 100644 index 000000000..e6e298247 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/IssuedTo.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.registry.digilocker.pulluriresponse; + + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class IssuedTo { + + private Persons persons; + + @XmlElement(name = "persons") + public Persons getPersons() { + return persons; + } + + public void setPersons(Persons persons) { + this.persons = persons; + } + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/Person.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/Person.java new file mode 100644 index 000000000..10040eeb6 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/Person.java @@ -0,0 +1,51 @@ +package dev.sunbirdrc.registry.digilocker.pulluriresponse; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Person { + + private String name; + private String dob; + private String gender; + private String phone; + + + @XmlAttribute(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlAttribute(name = "dob") + public String getDob() { + return dob; + } + + public void setDob(String dob) { + this.dob = dob; + } + + @XmlAttribute(name = "gender") + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + @XmlAttribute(name = "phone") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/Persons.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/Persons.java new file mode 100644 index 000000000..0c20afb80 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/Persons.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.registry.digilocker.pulluriresponse; + + +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.List; +@XmlRootElement +public class Persons { + + public List getPerson() { + return person; + } + + + public void setPerson(List person) { + this.person = person; + } + + List person = new ArrayList<>(); + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/PhotoBean.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/PhotoBean.java new file mode 100644 index 000000000..d50a23272 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/PhotoBean.java @@ -0,0 +1,30 @@ +package dev.sunbirdrc.registry.digilocker.pulluriresponse; + + +import javax.xml.bind.annotation.XmlAttribute; + + +public class PhotoBean { + String format = ""; + String textContent = ""; + + @XmlAttribute(name = "format") + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + @XmlAttribute(name = "TextContent") + public String getTextContent() { + return textContent; + } + + public void setTextContent(String textContent) { + this.textContent = textContent; + } + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/PullURIResponse.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/PullURIResponse.java new file mode 100644 index 000000000..dd867cace --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/PullURIResponse.java @@ -0,0 +1,30 @@ +package dev.sunbirdrc.registry.digilocker.pulluriresponse; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "PullURIResponse", namespace = "http://tempuri.org/") +public class PullURIResponse { + + private ResponseUriStatus responseStatus; + private DocDetails docDetails; + + @XmlElement(name = "ResponseStatus") + public ResponseUriStatus getResponseStatus() { + return responseStatus; + } + + public void setResponseStatus(ResponseUriStatus responseStatus) { + this.responseStatus = responseStatus; + } + + @XmlElement(name = "DocDetails") + public DocDetails getDocDetails() { + return docDetails; + } + + public void setDocDetails(DocDetails docDetails) { + this.docDetails = docDetails; + } + +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/ResponseUriStatus.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/ResponseUriStatus.java new file mode 100644 index 000000000..2a377051a --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulluriresponse/ResponseUriStatus.java @@ -0,0 +1,41 @@ +package dev.sunbirdrc.registry.digilocker.pulluriresponse; + + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class ResponseUriStatus { + + private String status; + private String ts; + private String txn; + + @XmlAttribute(name = "Status") + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @XmlAttribute(name = "ts") + public String getTs() { + return ts; + } + + public void setTs(String ts) { + this.ts = ts; + } + + @XmlAttribute(name = "txn") + public String getTxn() { + return txn; + } + + public void setTxn(String txn) { + this.txn = txn; + } + + } \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index 51327ae9b..49937a6cb 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -762,6 +762,14 @@ public JsonNode getRequestedUserDetails(HttpServletRequest request, String entit throw new Exception(NOT_PART_OF_THE_SYSTEM_EXCEPTION); } + public JsonNode getRequestedUserDetailsSearch(HttpServletRequest request, String entityName) throws Exception { + if (isInternalRegistry(entityName)) { + return getUserInfoFromRegistryByEntity(request, entityName); + } else if (entityTypeHandler.isExternalRegistry(entityName)) { + return getUserInfoFromKeyCloak(request, entityName); + } + throw new Exception(NOT_PART_OF_THE_SYSTEM_EXCEPTION); + } private boolean isInternalRegistry(String entityName) { return definitionsManager.getAllKnownDefinitions().contains(entityName); } @@ -790,6 +798,46 @@ private JsonNode getUserInfoFromRegistry(HttpServletRequest request, String enti throw new Exception("Forbidden"); } + private JsonNode getUserInfoFromRegistryByEntity(HttpServletRequest request, String entityName) throws Exception { + String userId = getUserId(request,entityName); + Scanner scanner = new Scanner(request.getInputStream(), "UTF-8"); + String filterString = null; + if(scanner!=null){ + Scanner scanner1 = scanner.useDelimiter("\\A"); + if(scanner1.hasNext()) + filterString = scanner1.next(); + } + + if (userId != null) { + ObjectNode payload = JsonNodeFactory.instance.objectNode(); + payload.set(ENTITY_TYPE, JsonNodeFactory.instance.arrayNode().add(entityName)); + ObjectNode filters = JsonNodeFactory.instance.objectNode(); + if(filterString!=null) { + ObjectNode customFilter = (ObjectNode) new ObjectMapper().readTree(filterString); + if(customFilter!=null){ + Iterator fieldNames = customFilter.fieldNames(); + while (fieldNames.hasNext()) { + String key = fieldNames.next(); + String value = String.valueOf(customFilter.get(key)); + JsonNode contains = JsonNodeFactory.instance.objectNode().put("contains", value); + filters.set(key, contains); + } + } + } + ObjectNode contains = JsonNodeFactory.instance.objectNode().put("contains", userId); + filters.set(OSSystemFields.osOwner.toString(), contains); + + //payload.set(FILTERS, filters.get("filters")); + payload.set(FILTERS, filters); + watch.start("RegistryController.searchEntity"); + JsonNode result = searchEntity(payload); + watch.stop("RegistryController.searchEntity"); + return result; + } + throw new Exception("Forbidden"); + } + + @NotNull private ObjectNode getSearchByOwnerQuery(String entityName, String userId) { ObjectNode payload = JsonNodeFactory.instance.objectNode(); @@ -1215,4 +1263,69 @@ public boolean checkIfCredentialIsRevoked(String signedData) throws Exception { JsonNode searchResponse = searchEntity(searchNode); return searchResponse.get(REVOKED_CREDENTIAL) != null && searchResponse.get(REVOKED_CREDENTIAL).size() > 0; } + + public JsonNode getRequestedUserDetailsCustom(HttpServletRequest request, String entityName, String filter) throws Exception { + if (isInternalRegistry(entityName)) { + return getUserInfoFromRegistryCustomQuery(request, entityName, filter); + } else if (entityTypeHandler.isExternalRegistry(entityName)) { + return getUserInfoFromKeyCloak(request, entityName); + } + throw new Exception(NOT_PART_OF_THE_SYSTEM_EXCEPTION); + } + + public JsonNode getUserInfoFromRegistryCustomQuery(HttpServletRequest request, String entityName, String filterString) throws Exception { + String userId = getUserId(request,entityName); + + if (userId != null) { + ObjectNode payload = JsonNodeFactory.instance.objectNode(); + payload.set(ENTITY_TYPE, JsonNodeFactory.instance.arrayNode().add(entityName)); + ObjectNode filters = JsonNodeFactory.instance.objectNode(); + if(filterString!=null) { + ObjectNode customFilter = (ObjectNode) new ObjectMapper().readTree(filterString); + if(customFilter!=null){ + Iterator fieldNames = customFilter.fieldNames(); + while (fieldNames.hasNext()) { + String key = fieldNames.next(); + String value = String.valueOf(customFilter.get(key)); + JsonNode contains = JsonNodeFactory.instance.objectNode().put("contains", value); + filters.set(key, contains); + } + } + } + ObjectNode contains = JsonNodeFactory.instance.objectNode().put("contains", userId); + filters.set(OSSystemFields.osOwner.toString(), contains); + + //payload.set(FILTERS, filters.get("filters")); + payload.set(FILTERS, filters); + watch.start("RegistryController.searchEntity"); + JsonNode result = searchEntity(payload); + watch.stop("RegistryController.searchEntity"); + return result; + } + throw new Exception("Forbidden"); + } + + public JsonNode getUserInfoFromRegistryByOsId(HttpServletRequest request, String entityName, String osid) throws Exception { + String userId = getUserId(request,entityName); + if (userId != null) { + ObjectNode payload = JsonNodeFactory.instance.objectNode(); + payload.set(ENTITY_TYPE, JsonNodeFactory.instance.arrayNode().add(entityName)); + ObjectNode filters = JsonNodeFactory.instance.objectNode(); + if(osid != null) { + JsonNode contains = JsonNodeFactory.instance.objectNode().put("contains", osid); + filters.set("osid", contains); + } + ObjectNode contains = JsonNodeFactory.instance.objectNode().put("contains", userId); + filters.set(OSSystemFields.osOwner.toString(), contains); + + //payload.set(FILTERS, filters.get("filters")); + payload.set(FILTERS, filters); + watch.start("RegistryController.searchEntity"); + JsonNode result = searchEntity(payload); + watch.stop("RegistryController.searchEntity"); + return result; + } + throw new Exception("Forbidden"); + } + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/BarCode.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/BarCode.java new file mode 100644 index 000000000..bddbccebd --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/BarCode.java @@ -0,0 +1,28 @@ +package dev.sunbirdrc.registry.model.dto; + +public class BarCode { + String barCodeText; + String barCodeValue; + + public String getBarCodeText() { + return barCodeText; + } + + public void setBarCodeText(String barCodeText) { + this.barCodeText = barCodeText; + } + + + + public String getBarCodeValue() { + return barCodeValue; + } + + public void setBarCodeValue(String barCodeValue) { + this.barCodeValue = barCodeValue; + } + + + + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/MailDto.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/MailDto.java new file mode 100644 index 000000000..d5c97bbb7 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/MailDto.java @@ -0,0 +1,43 @@ +package dev.sunbirdrc.registry.model.dto; + + +public class MailDto { + private String name; + private String certificate; + private String emailAddress; + + public String getCredentialsType() { + return credentialsType; + } + + public void setCredentialsType(String credentialsType) { + this.credentialsType = credentialsType; + } + + private String credentialsType; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCertificate() { + return certificate; + } + + public void setCertificate(String certificate) { + this.certificate = certificate; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/Status.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/Status.java new file mode 100644 index 000000000..bd77c0f31 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/Status.java @@ -0,0 +1,15 @@ +package dev.sunbirdrc.registry.model.dto; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +@Data +@NoArgsConstructor +public class Status implements Serializable { + + String mailStatus; + String certStatus; + String certUrl; +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ISearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ISearchService.java index 220c660b4..fcb7096de 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ISearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ISearchService.java @@ -62,12 +62,12 @@ default SearchQuery getSearchQuery(JsonNode inputQueryNode, int offset, int limi filterList.add(freeTextFilter); } - try { - searchQuery.setLimit(inputQueryNode.get("limit").asInt()); - searchQuery.setOffset(inputQueryNode.get("offset").asInt()); - } catch (Exception e) { - logger.warn("Populates SearchQuery for limit/offset(optional): {}", e.getMessage()); - } +// try { +// searchQuery.setLimit(inputQueryNode.get("limit").asInt()); +// searchQuery.setOffset(inputQueryNode.get("offset").asInt()); +// } catch (Exception e) { +// logger.warn("Populates SearchQuery for limit/offset(optional): {}", e.getMessage()); +// } searchQuery.setFilters(filterList); return searchQuery; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java index 09ba766f7..8d9e863cf 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java @@ -3,7 +3,9 @@ import com.fasterxml.jackson.databind.JsonNode; import dev.sunbirdrc.pojos.ComponentHealthInfo; import dev.sunbirdrc.registry.middleware.util.Constants; +import dev.sunbirdrc.registry.model.dto.BarCode; import dev.sunbirdrc.registry.service.ICertificateService; +import dev.sunbirdrc.registry.util.ClaimRequestClient; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,16 +36,18 @@ public class CertificateServiceImpl implements ICertificateService { private boolean signatureEnabled; private static Logger logger = LoggerFactory.getLogger(CertificateServiceImpl.class); + private final ClaimRequestClient claimRequestClient; public CertificateServiceImpl(@Value("${certificate.templateBaseUrl}") String templateBaseUrl, @Value("${certificate.apiUrl}") String certificateUrl, @Value("${signature.enabled}") boolean signatureEnabled, @Value("${certificate.healthCheckURL}") String certificateHealthCheckURL, - RestTemplate restTemplate) { + RestTemplate restTemplate,ClaimRequestClient claimRequestClient) { this.templateBaseUrl = templateBaseUrl; this.certificateUrl = certificateUrl; this.restTemplate = restTemplate; this.certificateHealthCheckURL = certificateHealthCheckURL; this.signatureEnabled = signatureEnabled; + this.claimRequestClient = claimRequestClient; } @Override @@ -68,6 +72,28 @@ public Object getCertificate(JsonNode certificateData, String entityName, String return null; } + public Object getCertificateForDGL(JsonNode certificateData, String entityName, String entityId, String mediaType, String templateUrl, JsonNode entity, String fileName) { + try { + String finalTemplateUrl = inferTemplateUrl(entityName, mediaType, templateUrl); + + Map requestBody = new HashMap(){{ + put("templateUrl", finalTemplateUrl); + put("certificate", certificateData.toString()); + put("entityId", entityId); + put("entityName", entityName); + put("entity", entity); + put("credentialsFileName",fileName); + }}; + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", mediaType); + HttpEntity> httpEntity = new HttpEntity<>(requestBody, headers); + return restTemplate.postForObject(certificateUrl, httpEntity, byte[].class); + } catch (Exception e) { + logger.error("Get certificate failed", e); + } + return null; + } + @NotNull private String inferTemplateUrl(String entityName, String mediaType, String templateUrl) { if (templateUrl == null) { @@ -109,4 +135,40 @@ public ComponentHealthInfo getHealthInfo() { } } + + public String saveToGCS(Object certificate, String entityId) { + String url = null; + logger.info("Uploading File GCP."); + url = claimRequestClient.saveFileToGCS(certificate, entityId); + logger.info("Uploading File GCP complete"); + return url; + } + + public BarCode getBarCode(BarCode barCode) { + BarCode node = null; + try { + logger.debug("BarCode start"); + node = claimRequestClient.getBarCode(barCode); + logger.debug("BarCode end"); + return node; + } catch (Exception e) { + logger.error("Get BarCode failed", e); + } + return node; + } + + + public byte[] getCred(String fileName) { + byte[] bytes = null; + try { + logger.info("Track Certificate start"); + bytes = claimRequestClient.getCredentials(fileName); + logger.info("Track Certificate end"); + } catch (Exception e) { + logger.error("Track certificate failed", e); + } + + return bytes; + + } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index b18e4b7b0..f1a165435 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -5,16 +5,24 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.pojos.dto.ClaimDTO; import dev.sunbirdrc.registry.controller.RegistryController; +import dev.sunbirdrc.registry.dao.Learner; +import dev.sunbirdrc.registry.model.dto.BarCode; +import dev.sunbirdrc.registry.model.dto.MailDto; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpEntity; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.*; import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import java.io.ByteArrayOutputStream; +import java.io.ObjectOutputStream; import java.util.HashMap; @Component @@ -25,6 +33,14 @@ public class ClaimRequestClient { private static final String CLAIMS_PATH = "/api/v1/claims"; private static final String FETCH_CLAIMS_PATH = "/api/v1/getClaims"; + private static final String MAIL_SEND_URL = "/api/v1/sendMail"; + private static final String BAR_CODE_API = "/api/v1/barcode"; + private static final String SAVE_CRED_API = "/api/v1/credentials/save"; + private static final String GET_CRED_URL = "/api/v1/files/download?"; + private static final String PDF = ".PDF"; + private static final String GCS_CODE_API = "/api/v1/files/upload"; + + ClaimRequestClient(@Value("${claims.url}") String claimRequestUrl, RestTemplate restTemplate) { this.claimRequestUrl = claimRequestUrl; this.restTemplate = restTemplate; @@ -59,4 +75,103 @@ public ResponseEntity attestClaim(JsonNode attestationRequest, String cl Object.class ); } + + public void sendMail(MailDto mail) { + restTemplate.postForObject(claimRequestUrl + MAIL_SEND_URL, mail, HashMap.class); + logger.info("Mail has successfully sent ..."); + } + + public String saveFileToGCS(Object certificate, String entityId) { + String fileName = entityId + PDF; + logger.info("Credentials File Name."+fileName); + String url = null; + byte[] bytes = convertObtToByte(certificate); + HttpHeaders headers = new HttpHeaders(); + if(bytes!=null){ + ByteArrayResource resource = new ByteArrayResource(bytes) { + @Override + public String getFilename() { + return fileName; + } + }; + ResponseEntity response = uploadFileToGCS(headers, resource); + switch (response.getStatusCode()){ + case OK: + url=response.getBody(); // TODO - handle http status + break; + default: + break; + + } + } + logger.debug("Save to GCS successfully ..."+url); + return url; + } + + @Nullable + private ResponseEntity uploadFileToGCS(HttpHeaders headers, ByteArrayResource resource) { + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + headers.set("accept", MediaType.MULTIPART_FORM_DATA_VALUE); + String serviceUrl = claimRequestUrl + GCS_CODE_API; + HttpMethod method = HttpMethod.POST; + + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("file", resource); + + // Create the HTTP entity with headers and body + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + + // Make the POST request to the service + RestTemplate restTemplate = new RestTemplate(); + logger.debug("Claim Service url for GCS upload:"+ serviceUrl); + ResponseEntity response = restTemplate.postForEntity(serviceUrl, requestEntity, String.class); + + return response; + } + + private byte[] convertObtToByte(Object certificate) { + byte[] bytes = null; + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + try (ObjectOutputStream objOutStream = new ObjectOutputStream(bos)) { + objOutStream.writeObject(certificate); + objOutStream.flush(); + bytes = bos.toByteArray(); + } + } catch (Exception e){ + logger.error("Converting certificate file to stream failed.",e); + } + + return bytes; + } + + public BarCode getBarCode(BarCode barCode) { + logger.debug("in getBarCode text::"+barCode.getBarCodeText()); + BarCode node = restTemplate.postForObject(claimRequestUrl + BAR_CODE_API, barCode, BarCode.class); + logger.debug("BarCode generated ..."); + return node; + } + + public void saveCredentials(Learner learner) { + logger.info("in Client::"+"Track certificate"); + String node = restTemplate.postForObject(claimRequestUrl + SAVE_CRED_API, learner, String.class); + logger.info("in Client certificate saved ..."); + } + + public byte[] getCredentials(String fileName) { + String requestUrl = claimRequestUrl + GET_CRED_URL; + MultiValueMap queryParams = new LinkedMultiValueMap<>(); + queryParams.add("fileName", fileName); + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestUrl) + .queryParam("fileName", fileName); + // Set request headers if needed + HttpHeaders headers = new HttpHeaders(); + // Add any required headers here + headers.set("accept", "*/*"); + ResponseEntity response = restTemplate.exchange( + builder.toUriString(), HttpMethod.GET, null, byte[].class, queryParams, headers + ); logger.info("end getCredentials ..."); + return response.getBody(); + } + + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java new file mode 100644 index 000000000..d61348aef --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java @@ -0,0 +1,27 @@ +package dev.sunbirdrc.registry.util; + +public class CredentialConstant { + public static final String credential1 = "REGISTRATION_CERTIFICATE"; + public static final String REGISTRATION_CERTIFICATE_ANM = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing-ANM.html"; + public static final String credential2 = "REGISTRATION_CERTIFICATE"; + public static final String link2 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing-BScNursing.html"; + public static final String credential3 = "REGISTRATION_CERTIFICATE"; + public static final String link3 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing-GNM.html"; + public static final String credential4 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; + public static final String link4 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-Babynursing.html"; + public static final String credential5 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; + public static final String link5 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-BloodTransfusion.html"; + public static final String credential6 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; + public static final String link6 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-Cardiology.html"; + public static final String credential7 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; + public static final String link7 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-TraumaAssistance.html"; + public static final String credential8 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; + public static final String link8 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-TraumaTechnician.html"; + public static final String credential9 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; + public static final String link9 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-Optpmetry.html"; + public static final String credential10 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; + public static final String link10 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-OTtechnician.html"; + public static final String credential11 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; + public static final String link11 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-Sanitation.html"; +} + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java new file mode 100644 index 000000000..ea8953c2c --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java @@ -0,0 +1,307 @@ +package dev.sunbirdrc.registry.util; + +import com.fasterxml.jackson.databind.JsonNode; +import dev.sunbirdrc.registry.digilocker.pulldoc.*; +import dev.sunbirdrc.registry.digilocker.pulluriresponse.*; +import dev.sunbirdrc.registry.digilocker.pulluriresponse.DocDetails; +import dev.sunbirdrc.registry.middleware.util.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; + +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.bind.*; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; + +public class DigiLockerUtils { + + public static final String HMAC_SHA_256 = "HmacSHA256"; + private static Logger logger = LoggerFactory.getLogger(DigiLockerUtils.class); + + public static Person getPersonDetail(JsonNode result, String entityName) { + Person person = new Person(); + JsonNode jsonNode = result.get(entityName); + if (jsonNode != null && jsonNode.size() > 0) { + JsonNode regCertificate = jsonNode.get(0); + JsonNode name = regCertificate.get("name"); + if (name != null) + person.setName(name.asText()); + JsonNode gender = regCertificate.get("gender"); + if (gender != null) + person.setGender(gender.asText()); + JsonNode dateOfBirth = regCertificate.get("dob"); + if (dateOfBirth != null) + person.setDob(dateOfBirth.asText()); + JsonNode mobile = regCertificate.get("contact"); + if (mobile != null) + person.setPhone(mobile.asText()); + } + return person; + } + + public static String getDocUri() { + String issuerId = "org.upsmfac"; + String doctype = "REGCR"; + int n = 10; + double docId = Math.floor(Math.random() * (9 * Math.pow(10, n - 1))) + Math.pow(10, (n - 1)); + String docUri = issuerId + "-" + doctype + "-" + docId; + return docUri; + } + + public static PullDocRequest processPullDocRequest(String xml) throws Exception{ + PullDocRequest request = new PullDocRequest(); + DocDetailsType docDetails = new DocDetailsType(); + + // Create a DocumentBuilderFactory and DocumentBuilder to parse the XML + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + + // Parse the XML string into a Document object + Document document = builder.parse(new ByteArrayInputStream(xml.getBytes())); + Element rootElement = document.getDocumentElement(); + Element docDetailsElement = (Element) rootElement.getElementsByTagName("DocDetails").item(0); + // Get the values of URI and DigiLockerId elements + String uri = docDetailsElement.getElementsByTagName("URI").item(0).getTextContent(); + String digiLockerId = docDetailsElement.getElementsByTagName("DigiLockerId").item(0).getTextContent(); + docDetails.setUri(uri); + docDetails.setDigiLockerId(digiLockerId); + request.setDocDetails(docDetails); + // Print the values + logger.info("URI: " + uri); + logger.info("DigiLockerId: " + digiLockerId); + NamedNodeMap attributes = rootElement.getAttributes(); + for (int i = 0; i < attributes.getLength(); i++) { + String attributeName = attributes.item(i).getNodeName(); + String attributeValue = attributes.item(i).getNodeValue(); + switch (attributeName.toLowerCase()) { + case "txn": + request.setTxn(attributeValue); + break; + case "orgid": + request.setOrgId(attributeValue); + break; + case "ts": + request.setTs(attributeValue); + break; + case "format": + request.setFormat(attributeValue); + break; + case "keyhash": + request.setFormat(attributeValue); + break; + case "x-digilocker-hmac": + request.setFormat(attributeValue); + break; + default: + break; + } + } + + return request; + } + + public static byte[] decryptWithHashKey(byte[] inputData, String hashKey) throws Exception { + String algorithm = "AES"; + SecretKeySpec secretKey = new SecretKeySpec(hashKey.getBytes(), algorithm); + + Cipher cipher = Cipher.getInstance(algorithm); + cipher.init(Cipher.DECRYPT_MODE, secretKey); + + return cipher.doFinal(inputData); + } + + + private static byte[] convertObtToByte(Object certificate) { + byte[] bytes = null; + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + try (ObjectOutputStream objOutStream = new ObjectOutputStream(bos)) { + objOutStream.writeObject(certificate); + objOutStream.flush(); + bytes = bos.toByteArray(); + } + } catch (Exception e) { + logger.error("Converting certificate file to stream failed.", e); + } + + return bytes; + } + + public static String getXmlString(String xmlString) { + dev.sunbirdrc.registry.util.DocDetails docDetails; + try { + JAXBContext jaxbContext = JAXBContext.newInstance(PullURIRequest.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + PullURIRequest pullUriRequest = (PullURIRequest) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); + // Access DocDetails using getDocDetails() + docDetails = pullUriRequest.getDocDetails(); + StringBuffer sb = new StringBuffer(); + sb.append("{"); + if(docDetails.getName()!=null) + sb.append("\"name\""+":"+"\""+docDetails.getName()+"\""+","); + if(docDetails.getMobile()!=null) + sb.append("\"mobile\""+":"+"\""+docDetails.getMobile()+"\""+","); + if(docDetails.getDateOfBirth()!=null) + sb.append("\"dob\""+":"+"\""+docDetails.getDateOfBirth()+"\""+","); + if(docDetails.getRollNumber()!=null) + sb.append("\"rollNumber\""+":"+"\""+docDetails.getRollNumber()+"\""); + else if (docDetails.getEnrollmentNumber() != null) { + sb.append("\"enrollmentNumber\""+":"+"\""+docDetails.getEnrollmentNumber()+"\""); + } + sb.append("}"); + xmlString = sb.toString(); + } catch (JAXBException e) { + e.printStackTrace(); + } + return xmlString; + } + public static PullURIResponse getPullUriResponse(String certUri, String status, String txn, Object certificate, Person person) { + List personList = new ArrayList(); + personList.add(person); + Persons persons = new Persons(); + persons.setPerson(personList); + PullURIResponse resp = new PullURIResponse(); + ResponseUriStatus responseStatus = new ResponseUriStatus(); + responseStatus.setStatus(status); + responseStatus.setTxn(txn); + byte[] bytes = convertObtToByte(certificate); + responseStatus.setTs(DateUtil.getTimeStamp()); + DocDetails details = new DocDetails(); + IssuedTo issuedTo = new IssuedTo(); + issuedTo.setPersons(persons); + Object docContent = Base64.getEncoder().encodeToString(bytes); + + details.setDocContent(docContent); + details.setDataContent(convertJaxbToBase64XmlString(person)); + details.setIssuedTo(issuedTo); + details.setUri(certUri); + resp.setResponseStatus(responseStatus); + resp.setDocDetails(details); + return resp; + } + + + public static PullDocResponse getDocPullUriResponse(String osId, String status, byte[] bytes, Person person) { + Object content = convertJaxbToBase64XmlString(person); + //ResponseStatus + PullDocResponse resp = new PullDocResponse(); + ResponseStatus responseStatus = new ResponseStatus(); + responseStatus.setStatus(status); + responseStatus.setTxn(osId); + responseStatus.setTs(DateUtil.getTimeStamp()); + resp.setResponseStatus(responseStatus); + + DocDetailsRs docDetails = new DocDetailsRs(); + docDetails.setDataContent(content); + //dataCont.setContent(content); + + docDetails.setDocContent(Base64.getEncoder().encodeToString(bytes)); + resp.setDocDetails(docDetails); + return resp; + } + public static String convertJaxbToString(Object jaxbObject) { + try { + JAXBContext jaxbContext = JAXBContext.newInstance(jaxbObject.getClass()); + Marshaller marshaller = jaxbContext.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + StringWriter writer = new StringWriter(); + marshaller.marshal(jaxbObject, writer); + String objString = writer.toString(); + return objString; + } catch (JAXBException e) { + e.printStackTrace(); + return null; + } + } + + public static Object convertJaxbToPullDoc(PullDocResponse jaxbObject) { + try { + StringWriter writer = new StringWriter(); + JAXB.marshal(jaxbObject, writer); + Object objString = writer.toString(); + return objString; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static String convertJaxbToBase64XmlString(Object jaxbObject) { + try { + JAXBContext jaxbContext = JAXBContext.newInstance(jaxbObject.getClass()); + Marshaller marshaller = jaxbContext.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + StringWriter writer = new StringWriter(); + marshaller.marshal(jaxbObject, writer); + String objString = writer.toString(); + String base64 = convertXmlToBase64(objString); + return base64; + } catch (JAXBException e) { + e.printStackTrace(); + return null; + } + } + + public static String convertXmlToBase64(String xmlData) { + byte[] bytes = xmlData.getBytes(StandardCharsets.UTF_8); + return Base64.getEncoder().encodeToString(bytes); + } + + public byte[] generateHMAC(byte[] rawData, String key) throws NoSuchAlgorithmException, InvalidKeyException { + Mac sha256Hmac = Mac.getInstance(HMAC_SHA_256); + SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); + sha256Hmac.init(secretKey); + byte[] hmacData = sha256Hmac.doFinal(rawData); + return hexEncode(hmacData); + } + + public static boolean isValidHmac(String receivedHashValue, String secretKey,String data) { + // Verify the hash value + return verifyHmac(data, secretKey, receivedHashValue); + + } + + public static boolean verifyHmac(String data, String secretKey, String hmacKey) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"); + mac.init(secretKeySpec); + byte[] calculatedHash = mac.doFinal(data.getBytes()); + // Decode the received hash value from Base64 + byte[] receivedHashBytes = Base64.getDecoder().decode(hmacKey); + // Compare the calculated hash with the received hash + return MessageDigest.isEqual(calculatedHash, receivedHashBytes); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + private byte[] hexEncode(byte[] data) { + char[] hexChars = new char[data.length * 2]; + for (int i = 0; i < data.length; i++) { + int v = data[i] & 0xFF; + hexChars[i * 2] = Character.forDigit(v >>> 4, 16); + hexChars[i * 2 + 1] = Character.forDigit(v & 0x0F, 16); + } + return new String(hexChars).getBytes(StandardCharsets.UTF_8); + } + + public boolean validateHMAC(byte[] actualHMAC, byte[] expectedHMAC) { + return Arrays.equals(actualHMAC, expectedHMAC); + } + +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java new file mode 100644 index 000000000..d3feb9134 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java @@ -0,0 +1,94 @@ +package dev.sunbirdrc.registry.util; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "DocDetails") +public class DocDetails { + private String uID; + private String digiLockerId; + private String mobile; + private String name; + private String rollNumber; + private String dateOfBirth; + private String docType; + private String enrollmentNumber; + + + + private String entityName; + + public String getEnrollmentNumber() { + return enrollmentNumber; + } + + public void setEnrollmentNumber(String enrollmentNumber) { + this.enrollmentNumber = enrollmentNumber; + } + + public String getuID() { + return uID; + } + + public void setuID(String uID) { + this.uID = uID; + } + + public String getDigiLockerId() { + return digiLockerId; + } + + public void setDigiLockerId(String digiLockerId) { + this.digiLockerId = digiLockerId; + } + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRollNumber() { + return rollNumber; + } + + public void setRollNumber(String rollNumber) { + this.rollNumber = rollNumber; + } + + public String getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(String dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public String getDocType() { + return docType; + } + + public void setDocType(String docType) { + this.docType = docType; + } + + public String getEntityName() { + return entityName; + } + + public void setEntityName(String entityName) { + this.entityName = entityName; + } + +} + + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/HmacSecretKeyGenerator.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/HmacSecretKeyGenerator.java new file mode 100644 index 000000000..107d02806 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/HmacSecretKeyGenerator.java @@ -0,0 +1,27 @@ +package dev.sunbirdrc.registry.util; + +import java.security.SecureRandom; +import java.util.Base64; + +public class HmacSecretKeyGenerator { + + public static void main(String[] args) { + // Choose the length of the secret key in bytes + int keyLengthBytes = 32; // Adjust the length as needed + // y+a/tzfzB3fJrpmT3OlwimIIE31Ns+N6rHOI2mCGoQQ= + // Generate a secure random key + byte[] secretKey = generateSecureRandomKey(keyLengthBytes); + + // Convert the byte array to a Base64-encoded string + String base64SecretKey = Base64.getEncoder().encodeToString(secretKey); + + System.out.println("Generated HMAC Secret Key: " + base64SecretKey); + } + + public static byte[] generateSecureRandomKey(int keyLengthBytes) { + byte[] key = new byte[keyLengthBytes]; + SecureRandom secureRandom = new SecureRandom(); + secureRandom.nextBytes(key); + return key; + } +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/PullURIRequest.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/PullURIRequest.java new file mode 100644 index 000000000..893cdf935 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/PullURIRequest.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.registry.util; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + + +@XmlRootElement(name = "PullURIRequest") +public class PullURIRequest { + // Add other fields as needed + private DocDetails docDetails; + + @XmlElement(name = "DocDetails") + public void setDocDetails( DocDetails docDetails) { + this.docDetails = docDetails; + } + + public DocDetails getDocDetails() { + return docDetails; + } +} + diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index aefd99c47..770443e95 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -53,11 +53,11 @@ registry: context: base: ${registry_context_base:http://localhost:8081/} system: - base: ${registry_system_base:http://localhost:8081/sunbirdrc/} + base: ${registry_system_base:http://localhost:8081/} rootEntity: - type: ${registry_rootentity_type:Teacher} + type: ${registry_rootentity_type:Regulator} schema: - url: ${registry_schema_url:http://localhost:8081/_schemas/} + url: ${registry_schema_url:D:/Registry/sunbird-rc-core/java/registry/src/main/resources/public/_schemas} attestationPolicy: createAccess: ${create_attestation_access_entities:User} manager: @@ -65,6 +65,8 @@ registry: redis: host: ${redis_host:localhost} port: ${redis_port:6379} + digilocker: + hkey: ${hmackey:vTV3Jl81kXDOca70TT2+P/YAb5DXnS+DDr/ArlFhow0=} workflow: enabled: ${workflow.enable:true} @@ -154,7 +156,7 @@ database: # ** Example - Postgres - jdbc:postgresql://localhost:5432/yourdb # * 3. NoSQL databases (Cassandra) # ** Example - cassandra - jdbc:cassandra://localhost:9160/yourdb - uri: ${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry} + uri: ${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry10} username: ${connectionInfo_username:postgres} password: ${connectionInfo_password:postgres} @@ -237,9 +239,9 @@ keycloak: resource: ${sunbird_sso_client_id:client} keycloak-admin: client-id: ${sunbird_sso_admin_client_id:admin-api} - client-secret: ${sunbird_sso_admin_client_secret:client_secret} + client-secret: ${sunbird_sso_admin_client_secret:19013b22-82b2-4a7b-a0ef-10ced3ef36f7} keycloak-user: - set-default-password: ${sunbird_keycloak_user_set_password:false} + set-default-password: ${sunbird_keycloak_user_set_password:true} default-password: ${sunbird_keycloak_user_password:abcd@123} # email actions which will be trigger by keycloak # example email actions: VERIFY_EMAIL, UPDATE_PROFILE, UPDATE_PASSWORD, TERMS_AND_CONDITIONS etc. @@ -251,7 +253,7 @@ authentication: enabled: ${authentication_enabled:true} publicKey: ${authentication_publickey:} realm: ${authentication_realm:sunbird-rc} - url: ${authentication_url:localhost:8443/auth} + url: ${authentication_url:localhost:8080/auth} validation: diff --git a/java/registry/src/main/resources/public/_schemas/regulator.json b/java/registry/src/main/resources/public/_schemas/regulator.json new file mode 100644 index 000000000..a59f6f161 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/regulator.json @@ -0,0 +1,49 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "Regulator": { + "$ref": "#/definitions/Regulator" + } + }, + "required": ["Regulator"], + "title": "Regulator", + "definitions": { + "Regulator": { + "$id": "#/properties/Regulator", + "type": "object", + "title": "Regulatorschema", + "required": ["name", "phoneNumber", "email"], + "uniqueIndexFields": ["phoneNumber"], + "properties": { + "name": { "type": "string" }, + "phoneNumber": { "type": "string" }, + "email": { "type": "string" }, + "council": { "type": "string" }, + "subject": { + "type": "string", + "enum": [ + "Math", + "Hindi", + "English", + "History", + "Geography", + "Physics", + "Chemistry", + "Biology" + ] + } + } + } + }, + "_osConfig": { + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/phoneNumber", + "userId": "/phoneNumber" + } + ], + "inviteRoles": ["anonymous"] + } +} diff --git a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json new file mode 100644 index 000000000..65082c411 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json @@ -0,0 +1,261 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "StudentForeignVerification": { + "$ref": "#/definitions/StudentForeignVerification" + } + }, + "required": [ + "StudentForeignVerification" + ], + "title": "StudentForeignVerification", + "definitions": { + "StudentForeignVerification": { + "$id": "#/properties/StudentForeignVerification", + "type": "object", + "title": "StudentForeignVerification", + "required": [ + "name", + "phoneNumber", + "email", + "council" + ], + "uniqueIndexFields": [ + "phoneNumber" + ], + "properties": { + "name": { + "$id": "#/properties/name", + "type": "string", + "title": "name" + }, + "fathersName": { + "$id": "#/properties/fathersName", + "type": "string", + "title": "fathersName" + }, + "address": { + "$id": "#/properties/address", + "type": "string", + "title": "address" + }, + "phoneNumber": { + "$id": "#/properties/phoneNumber", + "type": "string", + "title": "phoneNumber" + }, + "email": { + "$id": "#/properties/email", + "type": "string", + "title": "email" + }, + "trainingCenter": { + "$id": "#/properties/trainingCenter", + "type": "string", + "title": "trainingCenter" + }, + "registrationNumber": { + "$id": "#/properties/registrationNumber", + "type": "string", + "title": "registrationNumber" + }, + "council": { + "$id": "#/properties/council", + "type": "string", + "title": "council" + }, + "workPlace": { + "$id": "#/properties/workPlace", + "type": "string", + "title": "workPlace" + }, + "date": { + "$id": "#/properties/date", + "type": "string", + "title": "date" + }, + "refNo": { + "$id": "#/properties/refNo", + "type": "string", + "title": "refNo" + }, + "validityOfRegistration": { + "$id": "#/properties/validityOfRegistration", + "type": "string", + "title": "validityOfRegistration" + }, + "dob": { + "$id": "#/properties/dob", + "type": "string", + "title": "dob" + } + } + } + }, + "_osConfig": { + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/phoneNumber", + "userId": "/phoneNumber" + } + ], + "inviteRoles": [ + "anonymous" + ], + "roles": [ + "StudentForeignVerification" + ], + "attestationPolicies": [ + { + "name": "StudentForeignVerify", + "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", + "attestationProperties": { + "name": "$.name", + "fathersName": "$.fathersName", + "address": "$.address", + "phoneNumber": "$.phoneNumber", + "email": "$.email", + "trainingCenter": "$.trainingCenter", + "registrationNumber": "$.registrationNumber", + "workPlace": "$.workPlace", + "council": "$.council", + "refNo": "$.refNo", + "date": "$.date", + "validityOfRegistration": "$.validityOfRegistration", + "dob": "$.dob" + }, + "credentialTemplate": { + "@context": [ + "https://www.w3.org/2018/credentials/v1", + { + "@version": 1.1, + "@protected": true, + "SkillCertificate": { + "@id": "https://github.com/sunbird-specs/vc-specs#SkillCertificate", + "@context": { + "id": "@id", + "@version": 1.1, + "@protected": true, + "skills": "schema:Text" + } + }, + "Person": { + "@id": "https://github.com/sunbird-specs/vc-specs#Person", + "@context": { + "name": "schema:Text" + } + }, + "trainedOn": { + "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", + "@context": { + "name": "schema:Text" + } + }, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + } + }, + "address": { + "@id": "https://github.com/sunbird-specs/vc-specs#address", + "@context": { + "name": "schema:Text" + } + }, + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@context": { + "name": "schema:Text" + } + }, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + } + }, + "trainingCenter": { + "@id": "https://github.com/sunbird-specs/vc-specs#trainingCenter", + "@context": { + "name": "schema:Text" + } + }, + "registrationNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#registrationNumber", + "@context": { + "name": "schema:Text" + } + }, + "validityOfRegistration": { + "@id": "https://github.com/sunbird-specs/vc-specs#validityOfRegistration", + "@context": { + "name": "schema:Text" + } + }, + "council": { + "@id": "https://github.com/sunbird-specs/vc-specs#council", + "@context": { + "name": "schema:Text" + } + }, + "dob": { + "@id": "https://github.com/sunbird-specs/vc-specs#dob", + "@context": { + "name": "schema:Text" + } + }, + "workPlace": { + "@id": "https://github.com/sunbird-specs/vc-specs#workPlace", + "@context": { + "name": "schema:Text" + } + }, + "refNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#refNo", + "@context": { + "name": "schema:Text" + } + }, + "date": { + "@id": "https://github.com/sunbird-specs/vc-specs#date", + "@context": { + "name": "schema:Text" + } + } + } + ], + "type": [ + "VerifiableCredential" + ], + "issuanceDate": "2021-08-27T10:57:57.237Z", + "credentialSubject": { + "type": "Person", + "name": "{{name}}", + "marriedName": "{{marriedName}}", + "maidenName": "{{maidenName}}", + "fathersName": "{{fathersName}}", + "presentAddress": "{{presentAddress}}", + "phoneNumber": "{{phoneNumber}}", + "email": "{{email}}", + "professionalQualification": "{{professionalQualification}}", + "trainingCenter": "{{trainingCenter}}", + "refNo": "{{refNo}}", + "date": "{{date}}", + "registrationNumber": "{{registrationNumber}}", + "workPlace": "{{workPlace}}" + }, + "issuer": "did:web:sunbirdrc.dev/vc/skill" + } + } + ], + "certificateTemplates": { + "StudentForeignVerificationTemp": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html" + } + } +} + diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json new file mode 100644 index 000000000..3af4fa592 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -0,0 +1,352 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "StudentFromUP": { + "$ref": "#/definitions/StudentFromUP" + } + }, + "required": ["StudentFromUP"], + "title": "StudentFromUP", + "definitions": { + "StudentFromUP": { + "$id": "#/properties/StudentFromUP", + "type": "object", + "title": "StudentFromUP", + "properties": { + "registrationType": { + "$id": "#/properties/registrationType", + "type": "string", + "title": "registrationType", + "required": [ + "name", + "phoneNumber", + "email", + "council" + ], + "uniqueIndexFields": [ + "phoneNumber" + ], + "properties": { + "name": { + "type": "string" + }, + "phoneNumber": { + "type": "string" + }, + "email": { + "type": "string" + }, + "council": { + "type": "string" + }, + "mothersName": { + "$id": "#/properties/mothersName", + "type": "string", + "title": "motherName" + }, + "fathersName": { + "$id": "#/properties/fathersName", + "type": "string", + "title": "fatherName" + }, + "dateOfBirth": { + "$id": "#/properties/dateOfBirth", + "type": "string", + "title": "dateOfBirth" + }, + "aadhaarNo": { + "$id": "#/properties/aadhaarNo", + "type": "string", + "title": "aadhaarNo" + }, + "barCode": { + "$id": "#/properties/barCode", + "type": "string", + "title": "barCode" + }, + "candidatePic": { + "$id": "#/properties/candidatePic", + "type": "string", + "title": "candidatePic" + }, + "gender": { + "$id": "#/properties/gender", + "type": "string", + "title": "gender", + "enum": ["male", "female"] + }, + "address": { + "$id": "#/properties/address", + "type": "object", + "title": "address", + "required": [], + "properties": { + "address-text": { + "type": "string", + "title": "Plot" + }, + "state": { + "$id": "#/properties/state", + "type": "string", + "title": "State", + "enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] + }, + "district": { + "$id": "#/properties/district", + "type": "string", + "title": "district" + }, + "country": { + "$id": "#/properties/country", + "type": "string", + "title": "country" + }, + "pincode": { + "$id": "#/properties/pincode", + "type": "string", + "title": "pincode" + } + } + }, + "courseName": { + "$id": "#/properties/courseName", + "type": "string", + "title": "courseName" + }, + "nursingCollage": { + "$id": "#/properties/nursingCollage", + "type": "string", + "title": "nursingCollage" + }, + "joiningMonth": { + "$id": "#/properties/joiningMonth", + "type": "string", + "title": "joiningMonth" + }, + "joiningYear": { + "$id": "#/properties/joiningYear", + "type": "string", + "title": "joiningYear" + }, + "passingMonth": { + "$id": "#/properties/passingMonth", + "type": "string", + "title": "passingMonth" + }, + "passingYear": { + "$id": "#/properties/passingYear", + "type": "string", + "title": "passingYear" + }, + "finalYearRollNo": { + "$id": "#/properties/finalYearRollNo", + "type": "string", + "title": "finalYearRollNo" + }, + "examBody": { + "$id": "#/properties/examBody", + "type": "string", + "title": "examBody" + } + } + } + } + } + }, + "_osConfig": { + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/phoneNumber", + "userId": "/phoneNumber" + } + ], + "inviteRoles": ["anonymous"], + "roles": ["StudentFromUP"], + "attestationPolicies": [ + { + "name": "studentUPVerification", + "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", + "attestationProperties": { + "name": "$.name", + "mothersName": "$.mothersName", + "fathersName": "$.fathersName", + "council": "$.council", + "courseName": "$.courseName", + "joiningMonth": "$.joiningMonth", + "joiningYear": "$.joiningYear", + "passingMonth": "$.passingMonth", + "passingYear": "$.passingYear", + "examBody": "$.examBody", + "finalYearRollNo": "$.finalYearRollNo", + "date": "$.date" + }, + "credentialTemplate": { + "@context": [ + "https://www.w3.org/2018/credentials/v1", + { + "@version": 1.1, + "@protected": true, + "SkillCertificate": { + "@id": "https://github.com/sunbird-specs/vc-specs#SkillCertificate", + "@context": { + "id": "@id", + "@version": 1.1, + "@protected": true, + "skills": "schema:Text" + } + }, + "Person": { + "@id": "https://github.com/sunbird-specs/vc-specs#Person", + "@context": { + "name": "schema:Text" + } + }, + "trainedOn": { + "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", + "@context": { + "name": "schema:Text" + } + }, + "mothersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", + "@context": { + "name": "schema:Text" + } + }, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + } + }, + "address": { + "@id": "https://github.com/sunbird-specs/vc-specs#address", + "@context": { + "name": "schema:Text" + } + }, + "courseName": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseName", + "@context": { + "name": "schema:Text" + } + }, + "council": { + "@id": "https://github.com/sunbird-specs/vc-specs#council", + "@context": { + "name": "schema:Text" + } + }, + "joiningMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningMonth", + "@context": { + "name": "schema:Text" + } + }, + "joiningYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningYear", + "@context": { + "name": "schema:Text" + } + }, + "passingMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingMonth", + "@context": { + "name": "schema:Text" + } + }, + "passingYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingYear", + "@context": { + "name": "schema:Text" + } + }, + "examBody": { + "@id": "https://github.com/sunbird-specs/vc-specs#examBody", + "@context": { + "name": "schema:Text" + } + }, + "finalYearRollNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#finalYearRollNo", + "@context": { + "name": "schema:Text" + } + }, + "date": { + "@id": "https://github.com/sunbird-specs/vc-specs#date", + "@context": { + "name": "schema:Text" + } + } + } + ], + "type": ["VerifiableCredential"], + "issuanceDate": "2021-08-27T10:57:57.237Z", + "credentialSubject": { + "type": "Person", + "name": "{{name}}", + "mothersName": "{{mothersName}}", + "fathersName": "{{fathersName}}", + "address": "{{address}}", + "courseName": "{{courseName}}", + "joiningMonth": "{{joiningMonth}}", + "joiningYear": "{{joiningYear}}", + "passingMonth": "{{passingMonth}}", + "passingYear": "{{passingYear}}", + "examBody": "{{examBody}}", + "finalYearRollNo": "{{finalYearRollNo}}", + "date": "{{date}}" + }, + "issuer": "did:web:sunbirdrc.dev/vc/skill" + } + } + ], + "certificateTemplates": { + "StudentFromUPTemp": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html" + } + } +} + diff --git a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json new file mode 100644 index 000000000..de46ee797 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json @@ -0,0 +1,240 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "StudentGoodstanding": { + "$ref": "#/definitions/StudentGoodstanding" + } + }, + "required": ["StudentGoodstanding"], + "title": "StudentGoodstanding", + "definitions": { + "StudentGoodstanding": { + "$id": "#/properties/StudentGoodstanding", + "type": "object", + "title": "StudentGoodstanding", + "required": [ + "name", + "phoneNumber", + "email", + "council" + ], + "uniqueIndexFields": [ + "phoneNumber" + ], + "properties": { + "name": { + "$id": "#/properties/name", + "type": "string", + "title": "name" + }, + "marriedName": { + "$id": "#/properties/marriedName", + "type": "string", + "title": "marriedName" + }, + "maidenName": { + "$id": "#/properties/maidenName", + "type": "string", + "title": "maidenName" + }, + "fathersName": { + "$id": "#/properties/fathersName", + "type": "string", + "title": "fathersName" + }, + "presentAddress": { + "$id": "#/properties/presentAddress", + "type": "string", + "title": "presentAddress" + }, + "phoneNumber": { + "$id": "#/properties/phoneNumber", + "type": "string", + "title": "phoneNumber" + }, + "email": { + "$id": "#/properties/email", + "type": "string", + "title": "email" + }, + "professionalQualification": { + "$id": "#/properties/professionalQualification", + "type": "string", + "enum": [ + "A.N.M", + "Midwife", + "H.W", + "Nurse", + "B.SC.Nursing" + ], + "title": "professionalQualification" + }, + "trainingCenter": { + "$id": "#/properties/trainingCenter", + "type": "string", + "title": "trainingCenter" + }, + "registrationNumber": { + "$id": "#/properties/registrationNumber", + "type": "string", + "title": "registrationNumber" + }, + "council": { + "$id": "#/properties/council", + "type": "string", + "title": "council" + }, + "workPlace": { + "$id": "#/properties/workPlace", + "type": "string", + "title": "workPlace" + } + } + } + }, + "_osConfig": { + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/phoneNumber", + "userId": "/phoneNumber" + } + ], + "inviteRoles": ["anonymous"], + "roles": ["StudentGoodstanding"], + "attestationPolicies": [ + { + "name": "StudentGoodStandingVerification", + "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", + "attestationProperties": { + "name": "$.name", + "marriedName": "$.marriedName", + "maidenName": "$.maidenName", + "fathersName": "$.fathersName", + "presentAddress": "$.presentAddress", + "phoneNumber": "$.phoneNumber", + "email": "$.email", + "professionalQualification": "$.professionalQualification", + "trainingCenter": "$.trainingCenter", + "registrationNumber": "$.registrationNumber", + "workPlace": "$.workPlace", + "council":"$.council" + }, + "credentialTemplate": { + "@context": [ + "https://www.w3.org/2018/credentials/v1", + { + "@version": 1.1, + "@protected": true, + "SkillCertificate": { + "@id": "https://github.com/sunbird-specs/vc-specs#SkillCertificate", + "@context": { + "id": "@id", + "@version": 1.1, + "@protected": true, + "skills": "schema:Text" + } + }, + "Person": { + "@id": "https://github.com/sunbird-specs/vc-specs#Person", + "@context": { + "name": "schema:Text" + } + }, + "trainedOn": { + "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", + "@context": { + "name": "schema:Text" + } + }, + "maidenName": { + "@id": "https://github.com/sunbird-specs/vc-specs#maidenName", + "@context": { + "name": "schema:Text" + } + }, + "marriedName": { + "@id": "https://github.com/sunbird-specs/vc-specs#marriedName", + "@context": { + "name": "schema:Text" + } + }, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#marriedName", + "@context": { + "name": "schema:Text" + } + }, + "trainingCenter": { + "@id": "https://github.com/sunbird-specs/vc-specs#trainingCenter", + "@context": { + "name": "schema:Text" + } + }, + "presentAddress": { + "@id": "https://github.com/sunbird-specs/vc-specs#marriedName", + "@context": { + "name": "schema:Text" + } + }, + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@context": { + "name": "schema:Text" + } + }, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + } + }, + "professionalQualification": { + "@id": "https://github.com/sunbird-specs/vc-specs#professionalQualification", + "@context": { + "name": "schema:Text" + } + }, + "registrationNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#registrationNumber", + "@context": { + "name": "schema:Text" + } + }, + "workPlace": { + "@id": "https://github.com/sunbird-specs/vc-specs#workPlace", + "@context": { + "name": "schema:Text" + } + } + } + ], + "type": ["VerifiableCredential"], + "issuanceDate": "2021-08-27T10:57:57.237Z", + "credentialSubject": { + "type": "Person", + "name": "{{name}}", + "marriedName": "{{marriedName}}", + "maidenName": "{{maidenName}}", + "fathersName": "{{fathersName}}", + "presentAddress": "{{presentAddress}}", + "phoneNumber": "{{phoneNumber}}", + "email": "{{email}}", + "professionalQualification": "{{professionalQualification}}", + "trainingCenter": "{{trainingCenter}}", + "registrationNumber": "{{registrationNumber}}", + "workPlace": "{{workPlace}}" + }, + "issuer": "did:web:sunbirdrc.dev/vc/skill" + } + } + ], + "certificateTemplates": { + "StudentGoodStandingTemp": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html" + } + } +} + diff --git a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json new file mode 100644 index 000000000..6acb1c39b --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json @@ -0,0 +1,371 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "StudentNursingArmy": { + "$ref": "#/definitions/StudentNursingArmy" + } + }, + "required": ["StudentNursingArmy"], + "title": "StudentNursingArmy", + "definitions": { + "StudentNursingArmy": { + "$id": "#/properties/StudentNursingArmy", + "type": "object", + "title": "StudentNursingArmy", + "properties": { + "registrationType": { + "$id": "#/properties/registrationType", + "type": "string", + "title": "registrationType", + "required": [ + "name", + "phoneNumber", + "email", + "council" + ], + "uniqueIndexFields": [ + "phoneNumber" + ], + "properties": { + "name": { + "type": "string" + }, + "phoneNumber": { + "type": "string" + }, + "email": { + "type": "string" + }, + "council": { + "type": "string" + }, + "mothersName": { + "$id": "#/properties/mothersName", + "type": "string", + "title": "motherName" + }, + "fathersName": { + "$id": "#/properties/fathersName", + "type": "string", + "title": "fatherName" + }, + "dateOfBirth": { + "$id": "#/properties/dateOfBirth", + "type": "string", + "title": "dateOfBirth" + }, + "aadhaarNo": { + "$id": "#/properties/aadhaarNo", + "type": "string", + "title": "aadhaarNo" + }, + "barCode": { + "$id": "#/properties/barCode", + "type": "string", + "title": "barCode" + }, + "candidatePic": { + "$id": "#/properties/candidatePic", + "type": "string", + "title": "candidatePic" + }, + "gender": { + "$id": "#/properties/gender", + "type": "string", + "title": "gender", + "enum": ["male", "female"] + }, + "address": { + "$id": "#/properties/address", + "type": "object", + "title": "address", + "required": [], + "properties": { + "address-text": { + "type": "string", + "title": "Plot" + }, + "state": { + "$id": "#/properties/state", + "type": "string", + "title": "State", + "enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] + }, + "district": { + "$id": "#/properties/district", + "type": "string", + "title": "district" + }, + "country": { + "$id": "#/properties/country", + "type": "string", + "title": "country" + }, + "pincode": { + "$id": "#/properties/pincode", + "type": "string", + "title": "pincode" + } + } + }, + "courseName": { + "$id": "#/properties/courseName", + "type": "string", + "title": "courseName" + }, + "nursingCollage": { + "$id": "#/properties/nursingCollage", + "type": "string", + "title": "nursingCollage" + }, + "joiningMonth": { + "$id": "#/properties/joiningMonth", + "type": "string", + "title": "joiningMonth" + }, + "joiningYear": { + "$id": "#/properties/joiningYear", + "type": "string", + "title": "joiningYear" + }, + "passingMonth": { + "$id": "#/properties/passingMonth", + "type": "string", + "title": "passingMonth" + }, + "passingYear": { + "$id": "#/properties/passingYear", + "type": "string", + "title": "passingYear" + }, + "finalYearRollNo": { + "$id": "#/properties/finalYearRollNo", + "type": "string", + "title": "finalYearRollNo" + }, + "armyRegNo": { + "$id": "#/properties/armyRegNo", + "type": "string", + "title": "armyRegNo" + }, + "date": { + "$id": "#/properties/date", + "type": "string", + "title": "date" + }, + "examBody": { + "$id": "#/properties/examBody", + "type": "string", + "title": "examBody" + } + } + } + } + } + }, + "_osConfig": { + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/phoneNumber", + "userId": "/phoneNumber" + } + ], + "inviteRoles": ["anonymous"], + "roles": ["StudentNursingArmy"], + "attestationPolicies": [ + { + "name": "studentArmyVerification", + "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", + "attestationProperties": { + "name": "$.name", + "mothersName": "$.mothersName", + "fathersName": "$.fathersName", + "address": "$.address", + "courseName": "$.courseName", + "joiningMonth": "$.joiningMonth", + "joiningYear": "$.joiningYear", + "passingMonth": "$.passingMonth", + "passingYear": "$.passingYear", + "council":"$.council", + "finalYearRollNo": "$.finalYearRollNo", + "examBody": "$.examBody", + "armyRegNo": "$.armyRegNo", + "date": "$.date" + }, + "credentialTemplate": { + "@context": [ + "https://www.w3.org/2018/credentials/v1", + { + "@version": 1.1, + "@protected": true, + "SkillCertificate": { + "@id": "https://github.com/sunbird-specs/vc-specs#SkillCertificate", + "@context": { + "id": "@id", + "@version": 1.1, + "@protected": true, + "skills": "schema:Text" + } + }, + "Person": { + "@id": "https://github.com/sunbird-specs/vc-specs#Person", + "@context": { + "name": "schema:Text" + } + }, + "trainedOn": { + "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", + "@context": { + "name": "schema:Text" + } + }, + "name": { + "@id": "https://github.com/sunbird-specs/vc-specs#name", + "@context": { + "name": "schema:Text" + } + }, + "mothersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", + "@context": { + "name": "schema:Text" + } + }, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + } + }, + "address": { + "@id": "https://github.com/sunbird-specs/vc-specs#address", + "@context": { + "name": "schema:Text" + } + }, + "courseName": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseName", + "@context": { + "name": "schema:Text" + } + }, + "joiningMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningMonth", + "@context": { + "name": "schema:Text" + } + }, + "joiningYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningYear", + "@context": { + "name": "schema:Text" + } + }, + "passingMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingMonth", + "@context": { + "name": "schema:Text" + } + }, + "passingYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingYear", + "@context": { + "name": "schema:Text" + } + }, + "examBody": { + "@id": "https://github.com/sunbird-specs/vc-specs#examBody", + "@context": { + "name": "schema:Text" + } + }, + "finalYearRollNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#finalYearRollNo", + "@context": { + "name": "schema:Text" + } + }, + "armyRegNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#armyRegNo", + "@context": { + "name": "schema:Text" + } + }, + "date": { + "@id": "https://github.com/sunbird-specs/vc-specs#date", + "@context": { + "name": "schema:Text" + } + } + } + ], + "type": ["VerifiableCredential"], + "issuanceDate": "2021-08-27T10:57:57.237Z", + "credentialSubject": { + "type": "Person", + "name": "{{name}}", + "mothersName": "{{mothersName}}", + "fathersName": "{{fathersName}}", + "address": "{{address}}", + "courseName": "{{courseName}}", + "joiningMonth": "{{joiningMonth}}", + "joiningYear": "{{joiningYear}}", + "passingMonth": "{{passingMonth}}", + "passingYear": "{{passingYear}}", + "examBody": "{{examBody}}", + "finalYearRollNo": "{{finalYearRollNo}}", + "armyRegNo": "{{armyRegNo}}", + "date": "{{date}}" + }, + "issuer": "did:web:sunbirdrc.dev/vc/skill" + } + } + ], + "certificateTemplates": { + "StudentArmyRegTemp": "https://raw.githubusercontent.com/aniket-aditya/sunbird-rc/main/rc-demo-template.svg" + } + } +} + diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json new file mode 100644 index 000000000..870710d5e --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -0,0 +1,413 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "StudentOutsideUP": { + "$ref": "#/definitions/StudentOutsideUP" + } + }, + "required": ["StudentOutsideUP"], + "title": "StudentOutsideUP", + "definitions": { + "StudentOutsideUP": { + "$id": "#/properties/StudentOutsideUP", + "type": "object", + "title": "StudentOutsideUP", + "required": ["name", "phoneNumber", "email", "council"], + "properties": { + "registrationType": { + "$id": "#/properties/registrationType", + "type": "string", + "title": "registrationType" + }, + "name": { + "type": "string" + }, + "phoneNumber": { + "type": "string" + }, + "email": { + "type": "string" + }, + "mothersName": { + "$id": "#/properties/mothersName", + "type": "string", + "title": "motherName" + }, + "fathersName": { + "$id": "#/properties/fathersName", + "type": "string", + "title": "fatherName" + }, + "dateOfBirth": { + "$id": "#/properties/dateOfBirth", + "type": "string", + "title": "dateOfBirth" + }, + "aadhaarNo": { + "$id": "#/properties/aadhaarNo", + "type": "string", + "title": "aadhaarNo" + }, + "barCode": { + "$id": "#/properties/barCode", + "type": "string", + "title": "barCode" + }, + "candidatePic": { + "$id": "#/properties/candidatePic", + "type": "string", + "title": "candidatePic" + }, + "gender": { + "$id": "#/properties/gender", + "type": "string", + "title": "gender", + "enum": ["male", "female"] + }, + "address": { + "type": "object", + "title": "address", + "required": [], + "properties": { + "address-text": { + "type": "string", + "title": "Plot" + }, + "state": { + "$id": "#/properties/state", + "type": "string", + "title": "State", + "enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] + }, + "district": { + "$id": "#/properties/district", + "type": "string", + "title": "district" + }, + "country": { + "$id": "#/properties/country", + "type": "string", + "title": "country" + }, + "pincode": { + "$id": "#/properties/pincode", + "type": "string", + "title": "pincode" + } + } + }, + "courseName": { + "$id": "#/properties/courseName", + "type": "string", + "title": "courseName" + }, + "nursingCollage": { + "$id": "#/properties/nursingCollage", + "type": "string", + "title": "nursingCollage" + }, + "joiningMonth": { + "$id": "#/properties/joiningMonth", + "type": "string", + "title": "joiningMonth" + }, + "joiningYear": { + "$id": "#/properties/joiningYear", + "type": "string", + "title": "joiningYear" + }, + "passingMonth": { + "$id": "#/properties/passingMonth", + "type": "string", + "title": "passingMonth" + }, + "passingYear": { + "$id": "#/properties/passingYear", + "type": "string", + "title": "passingYear" + }, + "finalYearRollNo": { + "$id": "#/properties/finalYearRollNo", + "type": "string", + "title": "finalYearRollNo" + }, + "examBody": { + "$id": "#/properties/examBody", + "type": "string", + "title": "examBody" + }, + "courseState": { + "$id": "#/properties/courseState", + "type": "string", + "title": "courseState" + }, + "council": { + "$id": "#/properties/council", + "type": "string", + "title": "council" + }, + "registrationNo": { + "$id": "#/properties/registrationNo", + "type": "string", + "title": "registrationNo" + }, + "date": { + "$id": "#/properties/date", + "type": "string", + "title": "date" + } + } + }, + "nurseRegistration": { + "type": "object", + "properties": { + "nurseRegNo": { + "$id": "#/properties/nurseRegNo", + "type": "string", + "title": "nurseRegNo" + }, + "nurseRegDate": { + "$id": "#/properties/nurseRegDate", + "type": "string", + "title": "nurseRegDate" + }, + "date": { + "$id": "#/properties/date", + "type": "string", + "title": "date" + } + } + }, + "file1": { + "type": "object", + "properties": { + "fileName": { + "type": "string", + "format": "file" + } + } + } + }, + + "_osConfig": { + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/phoneNumber", + "userId": "/phoneNumber" + } + ], + "inviteRoles": ["anonymous"], + "roles": ["StudentOutsideUP"], + "attestationPolicies": [ + { + "name": "studentOutsideUPVerification", + "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", + "attestationProperties": { + "name": "$.name", + "mothersName": "$.mothersName", + "fathersName": "$.fathersName", + "courseName": "$.courseName", + "joiningMonth": "$.joiningMonth", + "joiningYear": "$.joiningYear", + "passingMonth": "$.passingMonth", + "passingYear": "$.passingYear", + "examBody": "$.examBody", + "finalYearRollNo": "$.finalYearRollNo", + "courseState": "$.courseState", + "council": "$.council", + "registrationNo": "$.registrationNo", + "nurseRegNo": "$.nurseRegNo", + "nurseRegDate": "$.nurseRegDate", + "date": "$.date" + }, + "credentialTemplate": { + "@context": [ + "https://www.w3.org/2018/credentials/v1", + { + "@version": 1.1, + "@protected": true, + "SkillCertificate": { + "@id": "https://github.com/sunbird-specs/vc-specs#SkillCertificate", + "@context": { + "id": "@id", + "@version": 1.1, + "@protected": true, + "skills": "schema:Text" + } + }, + "Person": { + "@id": "https://github.com/sunbird-specs/vc-specs#Person", + "@context": { + "name": "schema:Text" + } + }, + "trainedOn": { + "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", + "@context": { + "name": "schema:Text" + } + }, + "mothersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", + "@context": { + "name": "schema:Text" + } + }, + "passingMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingMonth", + "@context": { + "name": "schema:Text" + } + }, + "passingYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingYear", + "@context": { + "name": "schema:Text" + } + }, + "joiningMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningMonth", + "@context": { + "name": "schema:Text" + } + }, + "joiningYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningYear", + "@context": { + "name": "schema:Text" + } + }, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + } + }, + "courseName": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseName", + "@context": { + "name": "schema:Text" + } + }, + "examBody": { + "@id": "https://github.com/sunbird-specs/vc-specs#examBody", + "@context": { + "name": "schema:Text" + } + }, + "finalYearRollNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#finalYearRollNo", + "@context": { + "name": "schema:Text" + } + }, + "date": { + "@id": "https://github.com/sunbird-specs/vc-specs#date", + "@context": { + "name": "schema:Text" + } + }, + "courseState": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseState", + "@context": { + "name": "schema:Text" + } + }, + "council": { + "@id": "https://github.com/sunbird-specs/vc-specs#council", + "@context": { + "name": "schema:Text" + } + }, + "registrationNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#registrationNo", + "@context": { + "name": "schema:Text" + } + }, + "nurseRegNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#registrationNo", + "@context": { + "name": "schema:Text" + } + }, + "nurseRegDate": { + "@id": "https://github.com/sunbird-specs/vc-specs#registrationNo", + "@context": { + "name": "schema:Text" + } + } + } + ], + "type": ["VerifiableCredential"], + "issuanceDate": "2021-08-27T10:57:57.237Z", + "credentialSubject": { + "type": "Person", + "name": "{{name}}", + "mothersName": "{{mothersName}}", + "fathersName": "{{fathersName}}", + "courseName": "{{courseName}}", + "joiningMonth": "{{joiningMonth}}", + "joiningYear": "{{joiningYear}}", + "passingMonth": "{{passingMonth}}", + "passingYear": "{{passingYear}}", + "examBody": "{{examBody}}", + "finalYearRollNo": "{{finalYearRollNo}}", + "date": "{{date}}", + "courseState": "{{courseState}}", + "council": "{{council}}", + "registrationNo": "{{registrationNo}}", + "nurseRegNo": "{{nurseRegNo}}", + "nurseRegDate": "{{nurseRegDate}}" + }, + "issuer": "did:web:sunbirdrc.dev/vc/skill" + } + } + ], + "certificateTemplates": { + "StudentOutsideUPTemp": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html" + } + } +} \ No newline at end of file diff --git a/java/registry/src/main/resources/public/_schemas/teacher.json b/java/registry/src/main/resources/public/_schemas/teacher.json new file mode 100644 index 000000000..70b78de91 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/teacher.json @@ -0,0 +1,49 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "Teacher": { + "$ref": "#/definitions/Teacher" + } + }, + "required": ["Teacher"], + "title": "Teacher", + "definitions": { + "Teacher": { + "$id": "#/properties/Teacher", + "type": "object", + "title": "Teacher schema", + "required": ["name", "phoneNumber", "email", "school"], + "uniqueIndexFields": ["phoneNumber"], + "properties": { + "name": { "type": "string" }, + "phoneNumber": { "type": "string" }, + "email": { "type": "string" }, + "school": { "type": "string" }, + "subject": { + "type": "string", + "enum": [ + "Math", + "Hindi", + "English", + "History", + "Geography", + "Physics", + "Chemistry", + "Biology" + ] + } + } + } + }, + "_osConfig": { + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/phoneNumber", + "userId": "/phoneNumber" + } + ], + "inviteRoles": ["anonymous"] + } +} From 07a50f002c5c9682de2f9378015065339a152fa7 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 8 Aug 2023 17:34:11 +0530 Subject: [PATCH 02/43] Update SunbirdRCApplication.java --- .../java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java index 7984ad3c6..e0151017d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java @@ -55,11 +55,14 @@ public static ApplicationContext getAppContext() { @Bean public FilterRegistrationBean corsFilter() { + List list = new ArrayList(); + list.add("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin(corsAllowedOrigin); config.addAllowedOrigin("http://localhost:4200"); + config.setAllowedOrigins(list); config.addAllowedHeader("*"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); From a80f8c665dcf84420ee6bd318f3ebab70de42c53 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 8 Aug 2023 17:36:50 +0530 Subject: [PATCH 03/43] Update SunbirdRCApplication.java --- .../java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java index e0151017d..50d4085aa 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java @@ -18,7 +18,8 @@ import org.springframework.web.filter.CorsFilter; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; - +import java.util.ArrayList; +import java.util.List; import java.time.Duration; @SpringBootApplication(exclude={SecurityAutoConfiguration.class}) From 2f6db6ab0925f5d5c71c9cf6096a488d7a730373 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Wed, 9 Aug 2023 12:25:11 +0530 Subject: [PATCH 04/43] schema updates --- .../registry/util/CredentialConstant.java | 63 ++++++++++++------- .../_schemas/studentForeignVerification.json | 33 +++++++++- .../public/_schemas/studentFromUP.json | 44 ++++++++++++- .../public/_schemas/studentGoodStanding.json | 29 ++++++++- .../public/_schemas/studentNursingArmy.json | 44 ++++++++++++- .../public/_schemas/studentOutsideUp.json | 51 ++++++++++++--- 6 files changed, 225 insertions(+), 39 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java index d61348aef..2912f57db 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java @@ -1,27 +1,44 @@ package dev.sunbirdrc.registry.util; public class CredentialConstant { - public static final String credential1 = "REGISTRATION_CERTIFICATE"; - public static final String REGISTRATION_CERTIFICATE_ANM = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing-ANM.html"; - public static final String credential2 = "REGISTRATION_CERTIFICATE"; - public static final String link2 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing-BScNursing.html"; - public static final String credential3 = "REGISTRATION_CERTIFICATE"; - public static final String link3 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing-GNM.html"; - public static final String credential4 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; - public static final String link4 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-Babynursing.html"; - public static final String credential5 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; - public static final String link5 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-BloodTransfusion.html"; - public static final String credential6 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; - public static final String link6 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-Cardiology.html"; - public static final String credential7 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; - public static final String link7 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-TraumaAssistance.html"; - public static final String credential8 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; - public static final String link8 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-TraumaTechnician.html"; - public static final String credential9 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; - public static final String link9 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-Optpmetry.html"; - public static final String credential10 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; - public static final String link10 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-OTtechnician.html"; - public static final String credential11 = "ENROLLMENT_REGISTRATION_CERTIFICATE"; - public static final String link11 = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-Sanitation.html"; -} + public static final String R_CERTIFICATE_ANM = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; + public static final String R_CERTIFICATE_BSC_NURSING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; + public static final String R_CERTIFICATE_GNM = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; + public static final String R_CERTIFICATE_BABY_NURSING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String R_CERTIFICATE_BLOOD_TRANSFUSION = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String R_CERTIFICATE_CARDIOLOGY = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String R_CERTIFICATE_TRAUMA_ASSISTANCE = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String R_CERTIFICATE_TRAUMA_TECHNICIAN = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String R_CERTIFICATE_OPTOMETRY = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String R_CERTIFICATE_OTTECHNICIAN = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String R_CERTIFICATE_SANITATION = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + + public static final String CERTIFICATE_ANM_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String CERTIFICATE_GNM_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String BABY_NURSING_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String BLOOD_TRANSFUSION_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String CARDIOLOGY_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String TRAUMA_ASSISTANCE_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String TRAUMA_TECHNICIAN_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + public static final String OPTOMETRY_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String OT_TECHNICIAN_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String PHYSIOTHERAPY_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String SANITATION_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + + public static final String R_MSC = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html"; + + public static final String R_PBBSC = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html"; + + public static final String R_GOODSTANDING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html"; +} + \ No newline at end of file diff --git a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json index 65082c411..63e9486ec 100644 --- a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json +++ b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json @@ -89,6 +89,23 @@ "$id": "#/properties/dob", "type": "string", "title": "dob" + }, + "doc-proof": { + "type": "array", + "items": { + "type": "String" + }, + "title": "All Document Proof" + }, + "candidate-pics": { + "$id": "#/properties/candidate-pics", + "type": "string", + "title": "candidate-pics" + }, + "paymentStatus": { + "$id": "#/properties/paymentStatus", + "type": "string", + "title": "paymentStatus" } } } @@ -126,7 +143,9 @@ "refNo": "$.refNo", "date": "$.date", "validityOfRegistration": "$.validityOfRegistration", - "dob": "$.dob" + "dob": "$.dob", + "doc-proof": "$.doc-proof", + "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { "@context": [ @@ -226,8 +245,20 @@ "@context": { "name": "schema:Text" } + }, + "doc-proof": { + "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "@context": { + "name": "schema:Text" + } + }, + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "@context": { + "name": "schema:Text" } } + } ], "type": [ "VerifiableCredential" diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 3af4fa592..7b2b14b8c 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -186,6 +186,23 @@ "$id": "#/properties/examBody", "type": "string", "title": "examBody" + }, + "doc-proof": { + "type": "array", + "items": { + "type": "String" + }, + "title": "All Document Proof" + }, + "candidate-pics": { + "$id": "#/properties/candidate-pics", + "type": "string", + "title": "candidate-pics" + }, + "paymentStatus": { + "$id": "#/properties/paymentStatus", + "type": "string", + "title": "paymentStatus" } } } @@ -220,7 +237,10 @@ "passingYear": "$.passingYear", "examBody": "$.examBody", "finalYearRollNo": "$.finalYearRollNo", - "date": "$.date" + "date": "$.date", + "doc-proof": "$.doc-proof", + "candidate-pics": "$.candidate-pics", + "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { "@context": [ @@ -320,7 +340,26 @@ "@context": { "name": "schema:Text" } + }, + "candidate-pics": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidate-pics", + "@context": { + "name": "schema:Text" + } + }, + "doc-proof": { + "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "@context": { + "name": "schema:Text" + } + }, + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "@context": { + "name": "schema:Text" + } } + } ], "type": ["VerifiableCredential"], @@ -338,7 +377,8 @@ "passingYear": "{{passingYear}}", "examBody": "{{examBody}}", "finalYearRollNo": "{{finalYearRollNo}}", - "date": "{{date}}" + "date": "{{date}}", + "candidate-pics": "{{candidate-pics}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json index de46ee797..385191e87 100644 --- a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json +++ b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json @@ -89,6 +89,18 @@ "$id": "#/properties/workPlace", "type": "string", "title": "workPlace" + }, + "doc-proof": { + "type": "array", + "items": { + "type": "String" + }, + "title": "All Document Proof" + }, + "paymentStatus": { + "$id": "#/properties/paymentStatus", + "type": "string", + "title": "paymentStatus" } } } @@ -121,7 +133,9 @@ "trainingCenter": "$.trainingCenter", "registrationNumber": "$.registrationNumber", "workPlace": "$.workPlace", - "council":"$.council" + "council":"$.council", + "doc-proof": "$.doc-proof", + "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { "@context": [ @@ -209,7 +223,20 @@ "@context": { "name": "schema:Text" } + }, + "doc-proof": { + "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "@context": { + "name": "schema:Text" + } + }, + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "@context": { + "name": "schema:Text" + } } + } ], "type": ["VerifiableCredential"], diff --git a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json index 6acb1c39b..2308c41af 100644 --- a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json +++ b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json @@ -196,6 +196,23 @@ "$id": "#/properties/examBody", "type": "string", "title": "examBody" + }, + "doc-proof": { + "type": "array", + "items": { + "type": "String" + }, + "title": "All Document Proof" + }, + "candidate-pics": { + "$id": "#/properties/candidate-pics", + "type": "string", + "title": "candidate-pics" + }, + "paymentStatus": { + "$id": "#/properties/paymentStatus", + "type": "string", + "title": "paymentStatus" } } } @@ -232,7 +249,10 @@ "finalYearRollNo": "$.finalYearRollNo", "examBody": "$.examBody", "armyRegNo": "$.armyRegNo", - "date": "$.date" + "date": "$.date", + "doc-proof": "$.doc-proof", + "candidate-pics": "$.candidate-pics", + "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { "@context": [ @@ -338,7 +358,26 @@ "@context": { "name": "schema:Text" } + }, + "candidate-pics": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidate-pics", + "@context": { + "name": "schema:Text" + } + }, + "doc-proof": { + "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "@context": { + "name": "schema:Text" + } + }, + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "@context": { + "name": "schema:Text" + } } + } ], "type": ["VerifiableCredential"], @@ -357,7 +396,8 @@ "examBody": "{{examBody}}", "finalYearRollNo": "{{finalYearRollNo}}", "armyRegNo": "{{armyRegNo}}", - "date": "{{date}}" + "date": "{{date}}", + "candidate-pics": "{{candidate-pics}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json index 870710d5e..3df7dd871 100644 --- a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -217,14 +217,22 @@ } } }, - "file1": { - "type": "object", - "properties": { - "fileName": { - "type": "string", - "format": "file" - } - } + "doc-proof": { + "type": "array", + "items": { + "type": "String" + }, + "title": "All Document Proof" + }, + "candidate-pics": { + "$id": "#/properties/candidate-pics", + "type": "string", + "title": "candidate-pics" + }, + "paymentStatus": { + "$id": "#/properties/paymentStatus", + "type": "string", + "title": "paymentStatus" } }, @@ -260,7 +268,10 @@ "registrationNo": "$.registrationNo", "nurseRegNo": "$.nurseRegNo", "nurseRegDate": "$.nurseRegDate", - "date": "$.date" + "date": "$.date", + "doc-proof": "$.doc-proof", + "candidate-pics": "$.candidate-pics", + "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { "@context": [ @@ -378,7 +389,26 @@ "@context": { "name": "schema:Text" } + }, + "candidate-pics": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidate-pics", + "@context": { + "name": "schema:Text" + } + }, + "doc-proof": { + "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "@context": { + "name": "schema:Text" + } + }, + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "@context": { + "name": "schema:Text" + } } + } ], "type": ["VerifiableCredential"], @@ -400,7 +430,8 @@ "council": "{{council}}", "registrationNo": "{{registrationNo}}", "nurseRegNo": "{{nurseRegNo}}", - "nurseRegDate": "{{nurseRegDate}}" + "nurseRegDate": "{{nurseRegDate}}", + "candidate-pics": "{{candidate-pics}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } From 51313631a9b42f14faa8d1c03ad14222d81883fb Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Wed, 9 Aug 2023 16:10:26 +0530 Subject: [PATCH 05/43] cors issue --- .../registry/app/SunbirdRCApplication.java | 2 +- .../controller/RegistryEntityController.java | 68 ++++++++++++++----- .../registry/util/CredentialConstant.java | 45 +++++------- .../_schemas/studentForeignVerification.json | 6 +- .../public/_schemas/studentFromUP.json | 20 +++--- .../public/_schemas/studentNursingArmy.json | 13 ++-- .../public/_schemas/studentOutsideUp.json | 13 ++-- 7 files changed, 87 insertions(+), 80 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java index 50d4085aa..393cf9b21 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java @@ -62,7 +62,7 @@ public FilterRegistrationBean corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin(corsAllowedOrigin); - config.addAllowedOrigin("http://localhost:4200"); + config.addAllowedOrigin("*"); config.setAllowedOrigins(list); config.addAllowedHeader("*"); config.addAllowedMethod("POST"); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 74050ad42..9679b0079 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -567,11 +567,14 @@ public ResponseEntity getEntityType(@PathVariable String entityName, viewTemplateManager.getViewTemplateById(viewTemplateId), false) .get(entityName); JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); + + String templateUrlFromRequest = getTemplateUrlFromRequest(request, entityName); + return new ResponseEntity<>(certificateService.getCertificate(signedNode, entityName, entityId, request.getHeader(HttpHeaders.ACCEPT), - getTemplateUrlFromRequest(request, entityName), + templateUrlFromRequest, JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)) ), HttpStatus.OK); } catch (Exception exception) { @@ -582,6 +585,37 @@ public ResponseEntity getEntityType(@PathVariable String entityName, private String getTemplateUrlFromRequest(HttpServletRequest request, String entityName) { + String template = Template; + + if(entityName.equalsIgnoreCase("StudentForeignVerification")){ + return "StudentForeignVerificationTemp"; + } else if (entityName.equalsIgnoreCase("StudentGoodstanding")) { + return "StudentGoodStandingTemp"; + } + + if (externalTemplatesEnabled && !StringUtils.isEmpty(request.getHeader(template))) { + return request.getHeader(template); + } + if (definitionsManager.getCertificateTemplates(entityName) != null && definitionsManager.getCertificateTemplates(entityName).size() > 0 && !StringUtils.isEmpty(request.getHeader(TemplateKey))) { + String templateUri = definitionsManager.getCertificateTemplates(entityName).getOrDefault(request.getHeader(TemplateKey), null); + if (!StringUtils.isEmpty(templateUri)) { + try { + if (templateUri.startsWith(MINIO_URI_PREFIX)) { + return fileStorageService.getSignedUrl(templateUri.substring(MINIO_URI_PREFIX.length())); + } else if (templateUri.startsWith(HTTP_URI_PREFIX) || templateUri.startsWith(HTTPS_URI_PREFIX)) { + return templateUri; + } + } catch (Exception e) { + logger.error("Exception while parsing certificate templates DID urls", e); + return null; + } + } + + } + return null; + } + + private String getTemplateUrlFromRequestFromRegType(HttpServletRequest request, String entityName) { if (externalTemplatesEnabled && !StringUtils.isEmpty(request.getHeader(Template))) { return request.getHeader(Template); } @@ -954,9 +988,7 @@ public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest re //String entityName = "RegCertificate"; - take entity name from input - TODO // call template TODO - String templateurl = null; - String statusCode = "1"; Scanner scanner = null; try { @@ -998,21 +1030,23 @@ public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest re JsonNode node = registryHelper.readEntity(readerUserId, entityName, osid, false, null, false) .get(entityName); String fileName = DigiLockerUtils.getDocUri(); + Object certificate = null; JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); - Object certificate = certificateService.getCertificateForDGL(signedNode, - entityName, - osid, - MediaType.APPLICATION_PDF_VALUE, - getTemplateUrlFromRequest(request, entityName), - JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)), fileName - ); - // Push to DGS - verify that storage required or not - TODO - certificateService.saveToGCS(certificate, fileName+".PDF"); - // get Uri - String uri = GCS_SERVICE_URL + fileName + ".PDF"; - + certificate = certificateService.getCred(fileName + ".PDF"); + + if(certificate == null){ + certificate = certificateService.getCertificateForDGL(signedNode, + entityName, + osid, + MediaType.APPLICATION_PDF_VALUE, + getTemplateUrlFromRequest(request, entityName), + JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)), fileName + ); + + certificateService.saveToGCS(certificate, fileName); + } Person person = DigiLockerUtils.getPersonDetail(result, entityName); - PullURIResponse pullResponse = DigiLockerUtils.getPullUriResponse(uri, statusCode, osid, certificate, person); + PullURIResponse pullResponse = DigiLockerUtils.getPullUriResponse(fileName, statusCode, osid, certificate, person); String responseString = DigiLockerUtils.convertJaxbToString(pullResponse); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); @@ -1039,7 +1073,7 @@ public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest re {MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_XML_VALUE}) public ResponseEntity pullDocURI(HttpServletRequest request) { - String entityName = "RegCertificate"; //- take entity name from input - TODO + String entityName = "StudentFromUP"; //- take entity name from input - TODO String statusCode = "1"; Scanner scanner = null; String hmac = request.getHeader("x-digilocker-hmac"); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java index 2912f57db..f4dd86de0 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/CredentialConstant.java @@ -1,44 +1,31 @@ package dev.sunbirdrc.registry.util; public class CredentialConstant { - public static final String R_CERTIFICATE_ANM = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; - public static final String R_CERTIFICATE_BSC_NURSING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; - public static final String R_CERTIFICATE_GNM = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; - public static final String R_CERTIFICATE_BABY_NURSING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; - public static final String R_CERTIFICATE_BLOOD_TRANSFUSION = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; - public static final String R_CERTIFICATE_CARDIOLOGY = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; - public static final String R_CERTIFICATE_TRAUMA_ASSISTANCE = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; - public static final String R_CERTIFICATE_TRAUMA_TECHNICIAN = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; - public static final String R_CERTIFICATE_OPTOMETRY = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; - public static final String R_CERTIFICATE_OTTECHNICIAN = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; - public static final String R_CERTIFICATE_SANITATION = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; - - public static final String CERTIFICATE_ANM_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - - public static final String CERTIFICATE_GNM_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + public static final String REGISTRATION_ANM = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; + public static final String REGISTRATION_BSC_NURSING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; + public static final String REGISTRATION_GNM = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html"; + public static final String REGISTRATION_BABY_NURSING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String REGISTRATION_BLOOD_TRANSFUSION = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String REGISTRATION_CARDIOLOGY = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String REGISTRATION_TRAUMA_ASSISTANCE = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String REGISTRATION_TRAUMA_TECHNICIAN = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String REGISTRATION_OPTOMETRY = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String REGISTRATION_OTTECHNICIAN = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String REGISTRATION_SANITATION = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + public static final String ANM_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; + public static final String GNM_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; public static final String BABY_NURSING_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - public static final String BLOOD_TRANSFUSION_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - public static final String CARDIOLOGY_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - public static final String TRAUMA_ASSISTANCE_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - public static final String TRAUMA_TECHNICIAN_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - public static final String OPTOMETRY_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - public static final String OT_TECHNICIAN_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - public static final String PHYSIOTHERAPY_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - public static final String SANITATION_DIPLOMA = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html"; - - public static final String R_MSC = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html"; - - public static final String R_PBBSC = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html"; - - public static final String R_GOODSTANDING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html"; + public static final String REGISTRATION_MSC = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html"; + public static final String REGISTRATION_PBBSC = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html"; + public static final String REGISTRATION_GOODSTANDING = "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html"; } \ No newline at end of file diff --git a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json index 63e9486ec..0910cc7bb 100644 --- a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json +++ b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json @@ -97,10 +97,10 @@ }, "title": "All Document Proof" }, - "candidate-pics": { - "$id": "#/properties/candidate-pics", + "candidatePic": { + "$id": "#/properties/candidatePic", "type": "string", - "title": "candidate-pics" + "title": "candidatePic" }, "paymentStatus": { "$id": "#/properties/paymentStatus", diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 7b2b14b8c..b227ed2ed 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -65,11 +65,6 @@ "type": "string", "title": "barCode" }, - "candidatePic": { - "$id": "#/properties/candidatePic", - "type": "string", - "title": "candidatePic" - }, "gender": { "$id": "#/properties/gender", "type": "string", @@ -194,10 +189,10 @@ }, "title": "All Document Proof" }, - "candidate-pics": { - "$id": "#/properties/candidate-pics", + "candidatePic": { + "$id": "#/properties/candidatePic", "type": "string", - "title": "candidate-pics" + "title": "candidatePic" }, "paymentStatus": { "$id": "#/properties/paymentStatus", @@ -238,8 +233,9 @@ "examBody": "$.examBody", "finalYearRollNo": "$.finalYearRollNo", "date": "$.date", + "barCode": "$.barCode", "doc-proof": "$.doc-proof", - "candidate-pics": "$.candidate-pics", + "candidatePic": "$.candidatePic", "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { @@ -341,8 +337,8 @@ "name": "schema:Text" } }, - "candidate-pics": { - "@id": "https://github.com/sunbird-specs/vc-specs#candidate-pics", + "candidatePic": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", "@context": { "name": "schema:Text" } @@ -378,7 +374,7 @@ "examBody": "{{examBody}}", "finalYearRollNo": "{{finalYearRollNo}}", "date": "{{date}}", - "candidate-pics": "{{candidate-pics}}" + "candidatePic": "{{candidatePic}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json index 2308c41af..dc3486627 100644 --- a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json +++ b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json @@ -204,11 +204,6 @@ }, "title": "All Document Proof" }, - "candidate-pics": { - "$id": "#/properties/candidate-pics", - "type": "string", - "title": "candidate-pics" - }, "paymentStatus": { "$id": "#/properties/paymentStatus", "type": "string", @@ -251,7 +246,7 @@ "armyRegNo": "$.armyRegNo", "date": "$.date", "doc-proof": "$.doc-proof", - "candidate-pics": "$.candidate-pics", + "candidatePic": "$.candidatePic", "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { @@ -359,8 +354,8 @@ "name": "schema:Text" } }, - "candidate-pics": { - "@id": "https://github.com/sunbird-specs/vc-specs#candidate-pics", + "candidatePic": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", "@context": { "name": "schema:Text" } @@ -397,7 +392,7 @@ "finalYearRollNo": "{{finalYearRollNo}}", "armyRegNo": "{{armyRegNo}}", "date": "{{date}}", - "candidate-pics": "{{candidate-pics}}" + "candidatePic": "{{candidatePic}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json index 3df7dd871..b743c76ea 100644 --- a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -224,11 +224,6 @@ }, "title": "All Document Proof" }, - "candidate-pics": { - "$id": "#/properties/candidate-pics", - "type": "string", - "title": "candidate-pics" - }, "paymentStatus": { "$id": "#/properties/paymentStatus", "type": "string", @@ -270,7 +265,7 @@ "nurseRegDate": "$.nurseRegDate", "date": "$.date", "doc-proof": "$.doc-proof", - "candidate-pics": "$.candidate-pics", + "candidatePic": "$.candidatePic", "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { @@ -390,8 +385,8 @@ "name": "schema:Text" } }, - "candidate-pics": { - "@id": "https://github.com/sunbird-specs/vc-specs#candidate-pics", + "candidatePic": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", "@context": { "name": "schema:Text" } @@ -431,7 +426,7 @@ "registrationNo": "{{registrationNo}}", "nurseRegNo": "{{nurseRegNo}}", "nurseRegDate": "{{nurseRegDate}}", - "candidate-pics": "{{candidate-pics}}" + "candidatePic": "{{candidatePic}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } From 5c3a6a873a11eb44a02fe55cc12021af24b6da75 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Wed, 9 Aug 2023 16:21:08 +0530 Subject: [PATCH 06/43] feeRecipt --- .../public/_schemas/studentFromUP.json | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index b227ed2ed..08942f490 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -198,6 +198,11 @@ "$id": "#/properties/paymentStatus", "type": "string", "title": "paymentStatus" + }, + "feeReciptNo": { + "$id": "#/properties/feeReciptNo", + "type": "string", + "title": "feeReciptNo" } } } @@ -236,7 +241,8 @@ "barCode": "$.barCode", "doc-proof": "$.doc-proof", "candidatePic": "$.candidatePic", - "paymentStatus": "$.paymentStatus" + "paymentStatus": "$.paymentStatus", + "feeReciptNo": "$.feeReciptNo" }, "credentialTemplate": { "@context": [ @@ -354,6 +360,12 @@ "@context": { "name": "schema:Text" } + }, + "feeReciptNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#feeReciptNo", + "@context": { + "name": "schema:Text" + } } } @@ -374,7 +386,8 @@ "examBody": "{{examBody}}", "finalYearRollNo": "{{finalYearRollNo}}", "date": "{{date}}", - "candidatePic": "{{candidatePic}}" + "candidatePic": "{{candidatePic}}", + "feeReciptNo": "{{feeReciptNo}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } From a173d8e52c19691b43b9d458e7c9d4191243ddcb Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Wed, 9 Aug 2023 17:17:30 +0530 Subject: [PATCH 07/43] cors filter removal --- .../registry/app/SunbirdRCApplication.java | 28 +++++++++---------- .../public/_schemas/studentFromUP.json | 4 ++- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java index 393cf9b21..31968dbe8 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java @@ -51,26 +51,26 @@ public static ApplicationContext getAppContext() { return context; } - @Value("${cors.allowedOrigin}") - public String corsAllowedOrigin; +// @Value("${cors.allowedOrigin}") +// public String corsAllowedOrigin; @Bean public FilterRegistrationBean corsFilter() { List list = new ArrayList(); list.add("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - CorsConfiguration config = new CorsConfiguration(); - config.setAllowCredentials(true); - config.addAllowedOrigin(corsAllowedOrigin); - config.addAllowedOrigin("*"); - config.setAllowedOrigins(list); - config.addAllowedHeader("*"); - config.addAllowedMethod("POST"); - config.addAllowedMethod("DELETE"); - config.addAllowedMethod("GET"); - config.addAllowedMethod("OPTIONS"); - config.addAllowedMethod("PUT"); - source.registerCorsConfiguration("/**", config); +// CorsConfiguration config = new CorsConfiguration(); + //config.setAllowCredentials(true); +// config.addAllowedOrigin(corsAllowedOrigin); +// config.addAllowedOrigin("*"); +// config.setAllowedOrigins(list); +// config.addAllowedHeader("*"); +// config.addAllowedMethod("POST"); +// config.addAllowedMethod("DELETE"); +// config.addAllowedMethod("GET"); +// config.addAllowedMethod("OPTIONS"); +// config.addAllowedMethod("PUT"); +// source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 08942f490..5060abf43 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -394,7 +394,9 @@ } ], "certificateTemplates": { - "StudentFromUPTemp": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html" + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html" + } } } From 817f318e81bc2e38fd54946fbd120d149a58ae04 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Wed, 9 Aug 2023 17:33:31 +0530 Subject: [PATCH 08/43] cors config --- .../java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java index 31968dbe8..fab581d2f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java @@ -59,10 +59,10 @@ public FilterRegistrationBean corsFilter() { List list = new ArrayList(); list.add("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); -// CorsConfiguration config = new CorsConfiguration(); + CorsConfiguration config = new CorsConfiguration(); //config.setAllowCredentials(true); // config.addAllowedOrigin(corsAllowedOrigin); -// config.addAllowedOrigin("*"); + config.addAllowedOrigin("*"); // config.setAllowedOrigins(list); // config.addAllowedHeader("*"); // config.addAllowedMethod("POST"); From d62bf3aad5430a542f63f6fededb8b2127404384 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 10 Aug 2023 10:27:01 +0530 Subject: [PATCH 09/43] multifiles upload and single files upload --- .../claim/controller/FileController.java | 28 ++++++- .../java/dev/sunbirdrc/claim/dto/FileDto.java | 11 +++ .../sunbirdrc/claim/service/FileService.java | 3 + .../claim/service/FileServiceImpl.java | 35 +++++++- .../sunbirdrc/claim/utils/GCPBucketUtil.java | 2 +- .../controller/RegistryEntityController.java | 82 +++++++++++++++++++ .../sunbirdrc/registry/model/dto/FileDto.java | 21 +++++ .../service/impl/CertificateServiceImpl.java | 67 ++++++++++++++- .../registry/util/ClaimRequestClient.java | 38 ++++++++- .../src/main/resources/application.yml | 3 +- .../public/_schemas/studentFromUP.json | 13 ++- 11 files changed, 290 insertions(+), 13 deletions(-) create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/FileDto.java diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java index 184edefcb..7376d439a 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java @@ -10,13 +10,11 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; +import java.util.List; @RestController @RequestMapping("/api/v1/files/") @@ -51,5 +49,27 @@ public ResponseEntity downloadFile( contentType(MediaType.APPLICATION_PDF). headers(headers).body(resource); } + + /** + * @param entityName + * @param entityId + * @param files + * @return + */ + @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) + @RequestMapping("/upload/multiple/{entityName}/{entityId}") + public ResponseEntity> uploadMultipleFiles( + @PathVariable String entityName, + @PathVariable String entityId, + @RequestParam MultipartFile[] files) { + + List fileDtoList = fileService.uploadMultipleFile(files, entityName, entityId); + + if (fileDtoList != null) { + return ResponseEntity.ok(fileDtoList); + } + + return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED); + } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/FileDto.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/FileDto.java index 7544b64ff..c385fcee4 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/FileDto.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/FileDto.java @@ -9,4 +9,15 @@ public class FileDto { private String fileName; private String fileUrl; + + private String status; + + public FileDto(String fileName, String fileUrl) { + this.fileName = fileName; + this.fileUrl = fileUrl; + } + + public FileDto() { + + } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java index 2e9c26b59..3de1b64da 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java @@ -5,10 +5,13 @@ import org.springframework.web.multipart.MultipartFile; import java.io.IOException; +import java.util.List; public interface FileService { ByteArrayResource downloadFile(String fileName); FileDto uploadFile(MultipartFile file) throws IOException; + + List uploadMultipleFile(MultipartFile[] files, String entityName, String entityId); } \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java index 8ae6d67bd..fc6f5ae99 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java @@ -6,6 +6,8 @@ import dev.sunbirdrc.claim.exception.GCPFileUploadException; import dev.sunbirdrc.claim.utils.GCPBucketUtil; import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ByteArrayResource; @@ -16,12 +18,14 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; @Service @RequiredArgsConstructor public class FileServiceImpl implements FileService { - + private static final Logger LOGGER = LoggerFactory.getLogger(FileServiceImpl.class); @Value("dev-public-upsmf") private String bucketName; @Value("${gcp.dir.name}") @@ -54,4 +58,33 @@ public FileDto uploadFile(MultipartFile file) throws IOException { } return fileDto; } + + @Override + public List uploadMultipleFile(MultipartFile[] files, String entityName, String entityId){ + List fileDtoList = new ArrayList<>(); + + if (files == null || files.length == 0) { + LOGGER.error("Invalid file details - There is no file to upload"); + throw new GCPFileUploadException("Invalid file details - There is no file to upload"); + } + + for (MultipartFile file : files) { + FileDto fileDto = new FileDto(); + String originalFileName = entityName + "_" + entityId + "_" + file.getOriginalFilename(); + Path path = new File(originalFileName).toPath(); + + try { + String contentType = Files.probeContentType(path); + fileDto = dataBucketUtil.uploadFile(file, originalFileName, contentType); + + } catch (Exception e) { + LOGGER.error("Error occurred while uploading"); + fileDto.setStatus("Error while uploading file"); + fileDto.setFileName(file.getOriginalFilename()); + } + + fileDtoList.add(fileDto); + } + return fileDtoList; + } } \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/utils/GCPBucketUtil.java b/java/claim/src/main/java/dev/sunbirdrc/claim/utils/GCPBucketUtil.java index a53d53c8b..a5f4e4ebc 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/utils/GCPBucketUtil.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/utils/GCPBucketUtil.java @@ -96,7 +96,7 @@ public Blob DownloadFile(String fileName) { Bucket bucket = storage.get(gcpBucketId,Storage.BucketGetOption.fields()); RandomString id = new RandomString(); - Blob blob = bucket.get(gcpDirectoryName+"/" + fileName); + Blob blob = bucket.get(fileName); return blob; }catch (GCPFileUploadException e){ LOGGER.error("An error occurred while Downloading data. Exception: ", e); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 9679b0079..827152ba3 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -48,6 +48,7 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @@ -1125,4 +1126,85 @@ public ResponseEntity pullDocURI(HttpServletRequest request) { } + /** + * @param entityName + * @param entityId + * @param files + * @param request + * @return + */ + @RequestMapping(value = "/api/v1/{entityName}/{entityId}/upload/multi-files", method = RequestMethod.PUT) + public ResponseEntity putMultiEntityFiles( + @PathVariable String entityName, + @PathVariable String entityId, + @RequestParam MultipartFile[] files, + HttpServletRequest request) { + + if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { + try { + registryHelper.authorize(entityName, entityId, request); + } catch (Exception e) { + return createUnauthorizedExceptionResponse(e); + } + } + ResponseParams responseParams = new ResponseParams(); + + try { + List fileUrlList = certificateService.uploadMultiEntityDocFiles(files, entityName, entityId); + + Response response = new Response(Response.API_ID.CREATE, HttpStatus.OK.name(), responseParams); + response.setResult(fileUrlList); + + responseParams.setErrmsg(""); + responseParams.setStatus(Response.Status.SUCCESSFUL); + + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + logger.error("RegistryController: Exception while uploading files", e); + + Response response = new Response(Response.API_ID.CREATE, HttpStatus.INTERNAL_SERVER_ERROR.name(), responseParams); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(e.getMessage()); + + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + @RequestMapping(value = "/api/v1/{entityName}/{entityId}/upload/file", method = RequestMethod.PUT) + public ResponseEntity putSingleEntityFile( + @PathVariable String entityName, + @PathVariable String entityId, + @RequestParam MultipartFile file, + HttpServletRequest request) { + + if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { + try { + registryHelper.authorize(entityName, entityId, request); + } catch (Exception e) { + return createUnauthorizedExceptionResponse(e); + } + } + ResponseParams responseParams = new ResponseParams(); + + try { + String fileUrl = certificateService.uploadSingleEntityDocFiles(file, entityName, entityId); + + Response response = new Response(Response.API_ID.CREATE, HttpStatus.OK.name(), responseParams); + response.setResult(fileUrl); + + responseParams.setErrmsg(""); + responseParams.setStatus(Response.Status.SUCCESSFUL); + + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + logger.error("RegistryController: Exception while uploading single file", e); + + Response response = new Response(Response.API_ID.CREATE, HttpStatus.INTERNAL_SERVER_ERROR.name(), responseParams); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(e.getMessage()); + + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/FileDto.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/FileDto.java new file mode 100644 index 000000000..bfe49a0ec --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/FileDto.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.registry.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class FileDto { + + + private String fileName; + private String fileUrl; + private String status; + + public FileDto(String fileName, String fileUrl) { + this.fileName = fileName; + this.fileUrl = fileUrl; + } +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java index 8d9e863cf..d6a964580 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java @@ -4,6 +4,7 @@ import dev.sunbirdrc.pojos.ComponentHealthInfo; import dev.sunbirdrc.registry.middleware.util.Constants; import dev.sunbirdrc.registry.model.dto.BarCode; +import dev.sunbirdrc.registry.model.dto.FileDto; import dev.sunbirdrc.registry.service.ICertificateService; import dev.sunbirdrc.registry.util.ClaimRequestClient; import org.jetbrains.annotations.NotNull; @@ -17,11 +18,11 @@ import org.springframework.util.StringUtils; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import org.springframework.web.multipart.MultipartFile; import java.net.URI; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; +import java.util.*; +import java.util.stream.Collectors; import static dev.sunbirdrc.registry.middleware.util.Constants.CONNECTION_FAILURE; import static dev.sunbirdrc.registry.middleware.util.Constants.SUNBIRD_CERTIFICATE_SERVICE_NAME; @@ -33,6 +34,16 @@ public class CertificateServiceImpl implements ICertificateService { private final String certificateHealthCheckURL; private final RestTemplate restTemplate; + @Value("${claims.url}") + private String claimRequestUrl; + + @Value("${claims.download-path}") + private String claimDownloadPath; + + static String static_download_parameter = "?fileName="; + + private static String URL_APPENDER = "/"; + private boolean signatureEnabled; private static Logger logger = LoggerFactory.getLogger(CertificateServiceImpl.class); @@ -171,4 +182,54 @@ public byte[] getCred(String fileName) { return bytes; } + + public List uploadMultiEntityDocFiles(MultipartFile[] files, String entityName, String entityId) throws Exception { + if (files == null || files.length == 0) { + logger.error("Missing files to upload document"); + throw new Exception("Missing files to upload document"); + } + + List fileDtoList = claimRequestClient.uploadCLaimMultipleFiles(files, entityName, entityId); + + if (fileDtoList == null || fileDtoList.isEmpty()) { + throw new Exception("Unable to file file details while uploading file in claim service"); + } + + List fileUrlList = fileDtoList.stream() + .map(fileDto -> claimRequestUrl + claimDownloadPath + static_download_parameter + fileDto.getFileName()) + .collect(Collectors.toList()); + + return fileUrlList; + } + + /** + * @param file + * @param entityName + * @param entityId + * @return + * @throws Exception + */ + public String uploadSingleEntityDocFiles(MultipartFile file, String entityName, String entityId) throws Exception { + if (file == null) { + logger.error("Missing file in single file upload document"); + throw new Exception("Missing file in single file upload document"); + } + + List fileDtoList = claimRequestClient.uploadCLaimMultipleFiles(new MultipartFile[]{file}, entityName, entityId); + + if (fileDtoList == null || fileDtoList.isEmpty()) { + throw new Exception("Unable to file file details while uploading file in claim service"); + } + + Optional fileUrl = fileDtoList.stream() + .map(fileDto -> claimRequestUrl + claimDownloadPath + static_download_parameter + fileDto.getFileName()) + .findFirst(); + + if (!fileUrl.isPresent()) { + logger.error("Missing file url after uploading file"); + throw new Exception("Missing file url after uploading file"); + } + + return fileUrl.get(); + } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index f1a165435..6d824bcad 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -7,11 +7,14 @@ import dev.sunbirdrc.registry.controller.RegistryController; import dev.sunbirdrc.registry.dao.Learner; import dev.sunbirdrc.registry.model.dto.BarCode; +import dev.sunbirdrc.registry.model.dto.FileDto; import dev.sunbirdrc.registry.model.dto.MailDto; +import lombok.NonNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.*; import org.springframework.data.domain.Pageable; @@ -19,11 +22,13 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; +import org.springframework.web.multipart.MultipartFile; import org.springframework.web.util.UriComponentsBuilder; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.util.HashMap; +import java.util.List; @Component public class ClaimRequestClient { @@ -39,7 +44,8 @@ public class ClaimRequestClient { private static final String GET_CRED_URL = "/api/v1/files/download?"; private static final String PDF = ".PDF"; private static final String GCS_CODE_API = "/api/v1/files/upload"; - + private static final String CLAIM_MULTI_FILE_UPLOAD = "/api/v1/files/upload/multiple"; + private static String URL_APPENDER = "/"; ClaimRequestClient(@Value("${claims.url}") String claimRequestUrl, RestTemplate restTemplate) { this.claimRequestUrl = claimRequestUrl; @@ -173,5 +179,35 @@ public byte[] getCredentials(String fileName) { return response.getBody(); } + /** + * @param files + * @return + */ + public List uploadCLaimMultipleFiles(@NonNull MultipartFile[] files, String entityName, String entityId) throws Exception { + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + + MultiValueMap body = new LinkedMultiValueMap<>(); + + for (MultipartFile file : files) { + body.add("files", file.getResource()); + } + + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + + String url = claimRequestUrl + CLAIM_MULTI_FILE_UPLOAD + URL_APPENDER + entityName + URL_APPENDER + entityId; + + logger.debug("Claim Service url for multiple file upload:"+ url); + ResponseEntity> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, + new ParameterizedTypeReference>() {}); + + List fileDtoList = response.getBody(); + return fileDtoList; + } + + + + } diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 770443e95..c93c8fd43 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -242,13 +242,14 @@ keycloak-admin: client-secret: ${sunbird_sso_admin_client_secret:19013b22-82b2-4a7b-a0ef-10ced3ef36f7} keycloak-user: set-default-password: ${sunbird_keycloak_user_set_password:true} - default-password: ${sunbird_keycloak_user_password:abcd@123} + default-password: ${sunbird_keycloak_user_password:medicalCouncil@123} # email actions which will be trigger by keycloak # example email actions: VERIFY_EMAIL, UPDATE_PROFILE, UPDATE_PASSWORD, TERMS_AND_CONDITIONS etc. # email details should be configured in keycloak realm settings email-actions: ${keycloack_user_email_actions:} claims: url: ${claims_url:http://localhost:8082} + download-path: /api/v1/files/download authentication: enabled: ${authentication_enabled:true} publicKey: ${authentication_publickey:} diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 5060abf43..b58039db8 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -395,8 +395,17 @@ ], "certificateTemplates": { "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html" - + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "DEGREE_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "PHARMECY": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "PARAMEDICAL_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", + "PARAMEDICAL_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html" } } } From c245ca679a231047e64755c746369d615b98167f Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 10 Aug 2023 10:30:45 +0530 Subject: [PATCH 10/43] schema updates --- .../public/_schemas/studentFromUP.json | 41 +++++++++++++------ 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index b58039db8..ffb839ae5 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -394,19 +394,34 @@ } ], "certificateTemplates": { - "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "DEGREE_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "PHARMECY": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "PARAMEDICAL_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html", - "PARAMEDICAL_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html" - } + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html";, + "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html", + "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html", + "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html" + "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" } } } From 795aa89f9d5e08b02b9a8dd9d4e135096b61cdac Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 10 Aug 2023 10:57:44 +0530 Subject: [PATCH 11/43] XXX --- .../src/main/resources/public/_schemas/studentFromUP.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index ffb839ae5..5b574b3f2 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -398,7 +398,7 @@ "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", - "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html";, + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", @@ -411,10 +411,10 @@ "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html", "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", - "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html" + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html"; + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", From 7fe9e287cf38ac26a14b6f432d8fefa8944bff3c Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 10 Aug 2023 13:38:14 +0530 Subject: [PATCH 12/43] json updates --- .../src/main/resources/public/_schemas/studentFromUP.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 5b574b3f2..689a62330 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -185,7 +185,7 @@ "doc-proof": { "type": "array", "items": { - "type": "String" + "type": "string" }, "title": "All Document Proof" }, From 454a1efff5221e811d41b51971497657d3fe5f10 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 10 Aug 2023 17:48:13 +0530 Subject: [PATCH 13/43] json change --- .../src/main/resources/application.properties | 2 +- .../controller/RegistryEntityController.java | 9 ++++--- .../_schemas/studentForeignVerification.json | 2 +- .../public/_schemas/studentFromUP.json | 2 +- .../public/_schemas/studentGoodStanding.json | 2 +- .../public/_schemas/studentNursingArmy.json | 25 ++++++++++++++++--- .../public/_schemas/studentOutsideUp.json | 2 +- 7 files changed, 31 insertions(+), 13 deletions(-) diff --git a/java/claim/src/main/resources/application.properties b/java/claim/src/main/resources/application.properties index cada3cd1e..bbe651c90 100644 --- a/java/claim/src/main/resources/application.properties +++ b/java/claim/src/main/resources/application.properties @@ -1,6 +1,6 @@ server.port=8082 -spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry} +spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry10} spring.datasource.username=${connectionInfo_username:postgres} spring.datasource.password=${connectionInfo_password:postgres} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 827152ba3..fcac5c01d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -431,9 +431,9 @@ private String getNotes(JsonNode requestBody) { private JsonNode getAttestationSignedData(String attestationId, JsonNode node) throws AttestationNotFoundException, JsonProcessingException { JsonNode attestationNode = getAttestationNode(attestationId, node); - if (attestationNode.get(OSSystemFields._osAttestedData.name()) == null) - throw new AttestationNotFoundException(); - attestationNode = objectMapper.readTree(attestationNode.get(OSSystemFields._osAttestedData.name()).asText()); +// if (attestationNode.get(OSSystemFields._osAttestedData.name()) == null) +// throw new AttestationNotFoundException(); +// attestationNode = objectMapper.readTree(attestationNode.asText()); return attestationNode; } @@ -443,7 +443,8 @@ private JsonNode getAttestationNode(String attestationId, JsonNode node) { JsonNode attestationNode = null; while (iterator.hasNext()) { attestationNode = iterator.next(); - if (attestationNode.get(uuidPropertyName).toString().equals(attestationId)) { + JsonNode jsonNode = attestationNode.get(uuidPropertyName); + if (jsonNode!=null && jsonNode.toString().equals(attestationId)) { break; } } diff --git a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json index 0910cc7bb..69fc9badd 100644 --- a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json +++ b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json @@ -93,7 +93,7 @@ "doc-proof": { "type": "array", "items": { - "type": "String" + "type": "string" }, "title": "All Document Proof" }, diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 689a62330..07b47be59 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -387,7 +387,7 @@ "finalYearRollNo": "{{finalYearRollNo}}", "date": "{{date}}", "candidatePic": "{{candidatePic}}", - "feeReciptNo": "{{feeReciptNo}" + "feeReciptNo": "{{feeReciptNo}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json index 385191e87..864f1f529 100644 --- a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json +++ b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json @@ -93,7 +93,7 @@ "doc-proof": { "type": "array", "items": { - "type": "String" + "type": "string" }, "title": "All Document Proof" }, diff --git a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json index dc3486627..eed1fabe6 100644 --- a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json +++ b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json @@ -200,7 +200,7 @@ "doc-proof": { "type": "array", "items": { - "type": "String" + "type": "string" }, "title": "All Document Proof" }, @@ -247,7 +247,9 @@ "date": "$.date", "doc-proof": "$.doc-proof", "candidatePic": "$.candidatePic", - "paymentStatus": "$.paymentStatus" + "paymentStatus": "$.paymentStatus", + "email": "$.email", + "phoneNumber": "$.phoneNumber" }, "credentialTemplate": { "@context": [ @@ -371,6 +373,18 @@ "@context": { "name": "schema:Text" } + }, + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@context": { + "name": "schema:Text" + } + }, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + } } } @@ -392,14 +406,17 @@ "finalYearRollNo": "{{finalYearRollNo}}", "armyRegNo": "{{armyRegNo}}", "date": "{{date}}", - "candidatePic": "{{candidatePic}}" + "candidatePic": "{{candidatePic}}", + "email": "{{email}}", + "phoneNumber": "{{phoneNumber}}", + "paymentStatus": "{{paymentStatus}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } } ], "certificateTemplates": { - "StudentArmyRegTemp": "https://raw.githubusercontent.com/aniket-aditya/sunbird-rc/main/rc-demo-template.svg" + "StudentArmyRegTemp": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html" } } } diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json index b743c76ea..4e27c0c36 100644 --- a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -220,7 +220,7 @@ "doc-proof": { "type": "array", "items": { - "type": "String" + "type": "string" }, "title": "All Document Proof" }, From 60a6018d0f377a20491db6ece8fb2544ca68ca73 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 10 Aug 2023 18:10:40 +0530 Subject: [PATCH 14/43] cors issue --- .../registry/app/SunbirdRCApplication.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java index fab581d2f..1f9c30f0f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/app/SunbirdRCApplication.java @@ -51,8 +51,8 @@ public static ApplicationContext getAppContext() { return context; } -// @Value("${cors.allowedOrigin}") -// public String corsAllowedOrigin; + @Value("${cors.allowedOrigin}") + public String corsAllowedOrigin; @Bean public FilterRegistrationBean corsFilter() { @@ -61,17 +61,17 @@ public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); //config.setAllowCredentials(true); -// config.addAllowedOrigin(corsAllowedOrigin); + config.addAllowedOrigin(corsAllowedOrigin); config.addAllowedOrigin("*"); -// config.setAllowedOrigins(list); -// config.addAllowedHeader("*"); -// config.addAllowedMethod("POST"); -// config.addAllowedMethod("DELETE"); -// config.addAllowedMethod("GET"); -// config.addAllowedMethod("OPTIONS"); -// config.addAllowedMethod("PUT"); -// source.registerCorsConfiguration("/**", config); - FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); + config.setAllowedOrigins(list); + config.addAllowedHeader("*"); + config.addAllowedMethod("POST"); + config.addAllowedMethod("DELETE"); + config.addAllowedMethod("GET"); + config.addAllowedMethod("OPTIONS"); + config.addAllowedMethod("PUT"); + source.registerCorsConfiguration("/**", config); + FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; } From 7809c2e43ceda0d17786ef628091d160aa5f8513 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Mon, 14 Aug 2023 17:57:14 +0530 Subject: [PATCH 15/43] claim-ms --- .../claim/contants/AttributeNames.java | 2 + .../claim/controller/ClaimsController.java | 13 +- .../claim/repository/ClaimRepository.java | 2 + .../sunbirdrc/claim/service/ClaimService.java | 8 + .../controller/RegistryClaimsController.java | 16 + .../controller/RegistryEntityController.java | 63 ++- .../registry/helper/RegistryHelper.java | 116 ++---- .../model/attestation/AttestationPath.java | 45 +- .../registry/service/NativeSearchService.java | 2 +- .../registry/util/ClaimRequestClient.java | 9 + .../registry/util/DigiLockerUtils.java | 11 +- .../sunbirdrc/registry/util/DocDetails.java | 34 +- .../src/main/resources/application.yml | 16 +- .../public/_schemas/BaseAttestationField.json | 20 + .../resources/public/_schemas/Common.json | 393 ++++++++++++++++++ .../resources/public/_schemas/Institute.json | 212 ++++++++++ .../resources/public/_schemas/Student.json | 87 ++++ .../public/_schemas/studentFromUP.json | 384 +++++++++-------- .../resources/public/_schemas/teacher.json | 3 +- 19 files changed, 1087 insertions(+), 349 deletions(-) create mode 100644 java/registry/src/main/resources/public/_schemas/BaseAttestationField.json create mode 100644 java/registry/src/main/resources/public/_schemas/Common.json create mode 100644 java/registry/src/main/resources/public/_schemas/Institute.json create mode 100644 java/registry/src/main/resources/public/_schemas/Student.json diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/contants/AttributeNames.java b/java/claim/src/main/java/dev/sunbirdrc/claim/contants/AttributeNames.java index 5c318d889..d76ba5e3e 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/contants/AttributeNames.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/contants/AttributeNames.java @@ -9,6 +9,8 @@ public class AttributeNames { public static final String ENTITY = "ENTITY"; public static final String LOWERCASE_ENTITY = "entity";; public static final String ATTESTOR_INFO = "attestorInfo"; + + public static final String REQUESTOR_INFO = "reguestorInfo"; public static final String CONTENT = "content"; public static final String TOTAL_PAGES = "totalPages"; public static final String TOTAL_ELEMENTS = "totalElements"; diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/ClaimsController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/ClaimsController.java index cf2453488..7ee733ef3 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/ClaimsController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/ClaimsController.java @@ -17,11 +17,11 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; +import java.util.List; import java.util.Map; import java.util.Optional; -import static dev.sunbirdrc.claim.contants.AttributeNames.ATTESTOR_INFO; -import static dev.sunbirdrc.claim.contants.AttributeNames.LOWERCASE_ENTITY; +import static dev.sunbirdrc.claim.contants.AttributeNames.*; @Controller public class ClaimsController { @@ -45,6 +45,15 @@ public ResponseEntity> getClaims(@RequestHeader HttpHeaders return new ResponseEntity<>(claims, HttpStatus.OK); } + + @RequestMapping(value = "/api/v2/getClaims", method = RequestMethod.POST) + public ResponseEntity> getStudentClaims(@RequestHeader HttpHeaders headers, + @RequestBody JsonNode requestBody, Pageable pageable) { + String entity = requestBody.get(LOWERCASE_ENTITY).asText(); + JsonNode attestorNode = requestBody.get(ATTESTOR_INFO); + List claims = claimService.findByRequestorName(attestorNode.asText(), pageable); + return new ResponseEntity<>(claims, HttpStatus.OK); + } @RequestMapping(value = "/api/v1/getClaims/{claimId}", method = RequestMethod.POST) public ResponseEntity getClaimById(@RequestHeader HttpHeaders headers, @PathVariable String claimId, @RequestBody JsonNode requestBody) { diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimRepository.java index 93bdfb8de..e2d992705 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimRepository.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimRepository.java @@ -11,4 +11,6 @@ public interface ClaimRepository extends JpaRepository { List findByConditionsIn(List conditions); List findByAttestorEntityIn(List entities); List findByAttestorEntity(String entity); + + List findByRequestorName(String requestorName); } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java index 3101bbfd2..c556dd42c 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java @@ -63,6 +63,14 @@ public Map findClaimsForAttestor(String entity, JsonNode attesto return toMap(claimsToAttestor, pageable); } + public List findByRequestorName(String entity, Pageable pageable) { + List claims = claimRepository.findByRequestorName(entity); + logger.info("Found {} claims to process", claims.size()); + List claimsRequestor = claims.stream() + .collect(Collectors.toList()); + return claimsRequestor; + } + private Map toMap(List claims, Pageable pageable) { Map response = new HashMap<>(); response.put(TOTAL_PAGES, (int)(Math.ceil(claims.size() * 1.0/pageable.getPageSize()))); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java index edad915bf..633db4f7c 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java @@ -57,6 +57,22 @@ public ResponseEntity getAllClaims(@PathVariable String entityName, Page } } + + @RequestMapping(value = "/api/v2/{entityName}/claims", method = RequestMethod.GET) + public ResponseEntity getStudentsClaims(@PathVariable String entityName, Pageable pageable, + HttpServletRequest request) { + try { + JsonNode result = registryHelper.getRequestedUserDetails(request, entityName); + JsonNode claims = claimRequestClient.getStudentsClaims(result.get(entityName).get(0).get("email"), pageable, entityName); + logger.info("Received {} claims", claims.size()); + return new ResponseEntity<>(claims, HttpStatus.OK); + } catch (Exception e) { + logger.error("Fetching claims failed {}", e.getMessage()); + e.printStackTrace(); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + @RequestMapping(value = "/api/v1/{entityName}/claims/{claimId}", method = RequestMethod.GET) public ResponseEntity getClaim(@PathVariable String entityName, @PathVariable String claimId, HttpServletRequest request) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index fcac5c01d..84cd13469 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -431,9 +431,9 @@ private String getNotes(JsonNode requestBody) { private JsonNode getAttestationSignedData(String attestationId, JsonNode node) throws AttestationNotFoundException, JsonProcessingException { JsonNode attestationNode = getAttestationNode(attestationId, node); -// if (attestationNode.get(OSSystemFields._osAttestedData.name()) == null) -// throw new AttestationNotFoundException(); -// attestationNode = objectMapper.readTree(attestationNode.asText()); + if (attestationNode.get(OSSystemFields._osAttestedData.name()) == null) + throw new AttestationNotFoundException(); + attestationNode = objectMapper.readTree(attestationNode.get(OSSystemFields._osAttestedData.name()).asText()); return attestationNode; } @@ -490,7 +490,7 @@ public ResponseEntity getUserDetails( try { checkEntityNameInDefinitionManager(entityName); ArrayList fields = getConsentFields(request); - JsonNode userInfoFromRegistry = registryHelper.getRequestedUserDetailsSearch(request, entityName); + JsonNode userInfoFromRegistry = registryHelper.getRequestedUserDetails(request, entityName); JsonNode jsonNode = userInfoFromRegistry.get(entityName); if (jsonNode instanceof ArrayNode) { ArrayNode values = (ArrayNode) jsonNode; @@ -568,11 +568,11 @@ public ResponseEntity getEntityType(@PathVariable String entityName, JsonNode node = registryHelper.readEntity(readerUserId, entityName, entityId, false, viewTemplateManager.getViewTemplateById(viewTemplateId), false) .get(entityName); - JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); +// JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); String templateUrlFromRequest = getTemplateUrlFromRequest(request, entityName); - return new ResponseEntity<>(certificateService.getCertificate(signedNode, + return new ResponseEntity<>(certificateService.getCertificate(node, entityName, entityId, request.getHeader(HttpHeaders.ACCEPT), @@ -723,6 +723,13 @@ public ResponseEntity getEntityByToken(@PathVariable String entityName, @RequestHeader(required = false) String viewTemplateId) throws RecordNotFoundException { ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.GET, "OK", responseParams); + ResponseEntity objectResponseEntity = getObjectResponseEntity(entityName, request, viewTemplateId, responseParams, response); + return objectResponseEntity; + } + + + @NotNull + private ResponseEntity getObjectResponseEntity(String entityName, HttpServletRequest request, String viewTemplateId, ResponseParams responseParams, Response response) { try { checkEntityNameInDefinitionManager(entityName); String userId = registryHelper.getUserId(request, entityName); @@ -742,7 +749,7 @@ public ResponseEntity getEntityByToken(@PathVariable String entityName, return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(),responseParams); + createSchemaNotFoundResponse(e.getMessage(), responseParams); response = new Response(Response.API_ID.GET, "ERROR", responseParams); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } catch (Exception e) { @@ -977,7 +984,18 @@ public ResponseEntity revokeACredential ( return new ResponseEntity<>(response,HttpStatus.INTERNAL_SERVER_ERROR); } } - + @Nullable + private JsonNode getAttestationNode1(String attestationId, JsonNode node) { + Iterator iterator = node.iterator(); + JsonNode attestationNode = null; + while (iterator.hasNext()) { + attestationNode = iterator.next(); + if (attestationNode.get(uuidPropertyName).toString().equals(attestationId)) { + break; + } + } + return attestationNode; + } /** * PULL-URI-Request API for DigiLocker * @param request @@ -1012,20 +1030,33 @@ public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest re Response response = new Response(Response.API_ID.SEARCH, "OK", responseParams); String osid = null; JsonNode result = null; - try { - result = registryHelper.getRequestedUserDetailsCustom(request, entityName, xmlString); - if (result != null && result.get(entityName) != null && result.get(entityName).size() > 0) { - ArrayNode responseFromDb = registryHelper.fetchFromDBUsingEsResponse(entityName, (ArrayNode) result.get(entityName)); - if(responseFromDb!=null && responseFromDb.size() > 0){ - osid = responseFromDb.get(0).get("osid").asText(); - } - } + try{ + String userId = registryHelper.getUserId(request, entityName); + JsonNode responseFromDb = registryHelper.searchEntitiesByUserId(entityName, userId, null); + JsonNode entities = responseFromDb.get(entityName); } catch (Exception e) { statusCode = "0"; e.printStackTrace(); return new ResponseEntity<>(statusCode, HttpStatus.INTERNAL_SERVER_ERROR); } + +// ResponseEntity objectResponseEntity = getObjectResponseEntity(entityName, request, null, responseParams, response); + +// try { +// result = registryHelper.getRequestedUserDetailsCustom(request, entityName, xmlString); +// if (result != null && result.get(entityName) != null && result.get(entityName).size() > 0) { +// ArrayNode responseFromDb = registryHelper.fetchFromDBUsingEsResponse(entityName, (ArrayNode) result.get(entityName)); +// if(responseFromDb!=null && responseFromDb.size() > 0){ +// osid = responseFromDb.get(0).get("osid").asText(); +// } +// } +// } catch (Exception e) { +// statusCode = "0"; +// e.printStackTrace(); +// return new ResponseEntity<>(statusCode, HttpStatus.INTERNAL_SERVER_ERROR); +// } + if(osid!=null) { try { String readerUserId = getUserId(entityName, request); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index 49937a6cb..efc9107dd 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -87,10 +87,14 @@ public class RegistryHelper { private static final Logger logger = LoggerFactory.getLogger(RegistryHelper.class); - @Value("${authentication.enabled:true}") boolean securityEnabled; - @Value("${notification.service.enabled}") boolean notificationEnabled; - @Value("${invite.required_validation_enabled}") boolean skipRequiredValidationForInvite = true; - @Value("${invite.signature_enabled}") boolean skipSignatureForInvite = true; + @Value("${authentication.enabled:true}") + boolean securityEnabled; + @Value("${notification.service.enabled}") + boolean notificationEnabled; + @Value("${invite.required_validation_enabled}") + boolean skipRequiredValidationForInvite = true; + @Value("${invite.signature_enabled}") + boolean skipSignatureForInvite = true; @Autowired private NotificationHelper notificationHelper; @Autowired @@ -275,7 +279,7 @@ public JsonNode readEntity(JsonNode inputJson, String userId, boolean requireLDR public JsonNode readEntity(String userId, String entityType, String label, boolean includeSignatures, ViewTemplate viewTemplate, boolean requireLDResponse) throws Exception { - boolean includePrivateFields = false; + boolean includePrivateFields = true; JsonNode resultNode = null; RecordIdentifier recordId = RecordIdentifier.parse(label); String shardId = dbConnectionInfoMgr.getShardId(recordId.getShardLabel()); @@ -300,7 +304,7 @@ public JsonNode readEntity(String userId, String entityType, String label, boole resultNode = vTransformer.transform(viewTemplate, resultNode); } logger.debug("readEntity ends"); - if(isEventsEnabled) { + if (isEventsEnabled) { registryService.maskAndEmitEvent(resultNode.get(entityType), entityType, EventType.READ, userId, label); } return resultNode; @@ -432,8 +436,8 @@ public String triggerAttestation(AttestationRequest attestationRequest, Attestat private void updateGetFileUrl(JsonNode additionalInput) { - if(additionalInput!= null && additionalInput.has(FILE_URL)) { - ArrayNode fileUrls = (ArrayNode)(additionalInput.get(FILE_URL)); + if (additionalInput != null && additionalInput.has(FILE_URL)) { + ArrayNode fileUrls = (ArrayNode) (additionalInput.get(FILE_URL)); ArrayNode signedUrls = JsonNodeFactory.instance.arrayNode(); for (JsonNode fileNode : fileUrls) { String fileUrl = fileNode.asText(); @@ -446,7 +450,7 @@ private void updateGetFileUrl(JsonNode additionalInput) { e.printStackTrace(); } } - ((ObjectNode)additionalInput).replace(FILE_URL, signedUrls); + ((ObjectNode) additionalInput).replace(FILE_URL, signedUrls); } } @@ -470,6 +474,7 @@ private void addAttestationProperty(AttestationRequest attestationRequest) throw createOrUpdateProperty(attestationRequest.getEntityName(), attestationJsonNode, nodeToUpdate, attestationRequest.getName(), (ObjectNode) parentNode, propertyNode); updateEntityAndState(existingEntityNode, nodeToUpdate, attestationRequest.getUserId()); } + private void createOrUpdateProperty(String entityName, JsonNode inputJson, JsonNode updateNode, String propertyName, ObjectNode parentNode, JsonNode propertyNode) throws JsonProcessingException { if (propertyNode != null && !propertyNode.isMissingNode()) { updateProperty(inputJson, propertyName, parentNode, propertyNode); @@ -620,7 +625,7 @@ private void triggerNextFLowIfExists(PluginResponseMessage pluginResponseMessage } else if (attestationPolicy.getCompletionType() == FlowType.FUNCTION) { FunctionDefinition functionDefinition = definitionsManager.getDefinition(sourceEntity).getOsSchemaConfiguration() .getFunctionDefinition(attestationPolicy.getCompletionFunctionName()); - if (functionDefinition != null ) { + if (functionDefinition != null) { try { JsonNode inputJsonNode = generateInputForFunctionExecutor(sourceEntity, sourceNode.deepCopy(), pluginResponseMessage); JsonNode executedJsonNode = functionExecutor.execute(attestationPolicy.getCompletionValue(), functionDefinition, inputJsonNode); @@ -723,7 +728,7 @@ public String getUserId(HttpServletRequest request, String entityName) throws Ex } private String fetchUserIdFromToken(HttpServletRequest request) throws Exception { - if(!securityEnabled){ + if (!securityEnabled) { return DEFAULT_USER; } return getKeycloakUserId(request); @@ -741,9 +746,9 @@ public String fetchEmailIdFromToken(HttpServletRequest request, String entityNam if (doesEntityContainOwnershipAttributes(entityName) || getManageRoles(entityName).size() > 0) { KeycloakAuthenticationToken principal = (KeycloakAuthenticationToken) request.getUserPrincipal(); if (principal != null) { - try{ + try { return principal.getAccount().getKeycloakSecurityContext().getToken().getEmail(); - }catch (Exception exception){ + } catch (Exception exception) { return principal.getAccount().getPrincipal().getName(); } } @@ -762,14 +767,6 @@ public JsonNode getRequestedUserDetails(HttpServletRequest request, String entit throw new Exception(NOT_PART_OF_THE_SYSTEM_EXCEPTION); } - public JsonNode getRequestedUserDetailsSearch(HttpServletRequest request, String entityName) throws Exception { - if (isInternalRegistry(entityName)) { - return getUserInfoFromRegistryByEntity(request, entityName); - } else if (entityTypeHandler.isExternalRegistry(entityName)) { - return getUserInfoFromKeyCloak(request, entityName); - } - throw new Exception(NOT_PART_OF_THE_SYSTEM_EXCEPTION); - } private boolean isInternalRegistry(String entityName) { return definitionsManager.getAllKnownDefinitions().contains(entityName); } @@ -786,7 +783,7 @@ private JsonNode getUserInfoFromKeyCloak(HttpServletRequest request, String enti } private JsonNode getUserInfoFromRegistry(HttpServletRequest request, String entityName) throws Exception { - String userId = getUserId(request,entityName); + String userId = getUserId(request, entityName); if (userId != null) { ObjectNode payload = getSearchByOwnerQuery(entityName, userId); @@ -798,46 +795,6 @@ private JsonNode getUserInfoFromRegistry(HttpServletRequest request, String enti throw new Exception("Forbidden"); } - private JsonNode getUserInfoFromRegistryByEntity(HttpServletRequest request, String entityName) throws Exception { - String userId = getUserId(request,entityName); - Scanner scanner = new Scanner(request.getInputStream(), "UTF-8"); - String filterString = null; - if(scanner!=null){ - Scanner scanner1 = scanner.useDelimiter("\\A"); - if(scanner1.hasNext()) - filterString = scanner1.next(); - } - - if (userId != null) { - ObjectNode payload = JsonNodeFactory.instance.objectNode(); - payload.set(ENTITY_TYPE, JsonNodeFactory.instance.arrayNode().add(entityName)); - ObjectNode filters = JsonNodeFactory.instance.objectNode(); - if(filterString!=null) { - ObjectNode customFilter = (ObjectNode) new ObjectMapper().readTree(filterString); - if(customFilter!=null){ - Iterator fieldNames = customFilter.fieldNames(); - while (fieldNames.hasNext()) { - String key = fieldNames.next(); - String value = String.valueOf(customFilter.get(key)); - JsonNode contains = JsonNodeFactory.instance.objectNode().put("contains", value); - filters.set(key, contains); - } - } - } - ObjectNode contains = JsonNodeFactory.instance.objectNode().put("contains", userId); - filters.set(OSSystemFields.osOwner.toString(), contains); - - //payload.set(FILTERS, filters.get("filters")); - payload.set(FILTERS, filters); - watch.start("RegistryController.searchEntity"); - JsonNode result = searchEntity(payload); - watch.stop("RegistryController.searchEntity"); - return result; - } - throw new Exception("Forbidden"); - } - - @NotNull private ObjectNode getSearchByOwnerQuery(String entityName, String userId) { ObjectNode payload = JsonNodeFactory.instance.objectNode(); @@ -909,6 +866,7 @@ public ArrayNode fetchFromDBUsingEsResponse(String entity, ArrayNode esSearchRes } return result; } + public JsonNode searchEntitiesByUserId(String entity, String userId, String viewTemplateId) throws Exception { ObjectNode searchByOwnerQuery = getSearchByOwnerQuery(entity, userId); if (!Strings.isEmpty(viewTemplateId)) { @@ -939,7 +897,7 @@ public String authorizeDeleteEntity(HttpServletRequest request, String entityNam JsonNode entityFromDB = response.get(entityName); final boolean hasNoValidRole = !deleteRoles.isEmpty() && deleteRoles.stream().noneMatch(userRoles::contains); final boolean hasInValidOwnership = !isOwner(entityFromDB, userIdFromRequest); - if(hasNoValidRole || hasInValidOwnership){ + if (hasNoValidRole || hasInValidOwnership) { throw new UnAuthorizedException(UNAUTHORIZED_OPERATION_MESSAGE); } return userIdFromRequest; @@ -973,7 +931,7 @@ private List getManageRoles(String entityName) { private Set getUserRolesFromRequest(HttpServletRequest request) { KeycloakAuthenticationToken userPrincipal = (KeycloakAuthenticationToken) request.getUserPrincipal(); - return userPrincipal!=null ? userPrincipal.getAccount().getRoles():Collections.emptySet(); + return userPrincipal != null ? userPrincipal.getAccount().getRoles() : Collections.emptySet(); } private void authorizeUserRole(Set userRoles, List allowedRoles) throws Exception { @@ -1023,15 +981,16 @@ public void invalidateAttestation(String entityName, String entityId, String use } } - public String getPropertyToUpdate(HttpServletRequest request, String entityId){ + public String getPropertyToUpdate(HttpServletRequest request, String entityId) { String propertyURI = getPropertyURI(entityId, request); return propertyURI.split("/")[0]; } - private void updateAttestation(ArrayNode attestations,String propertyToUpdate) { + + private void updateAttestation(ArrayNode attestations, String propertyToUpdate) { for (JsonNode attestation : attestations) { if (attestation.get(_osState.name()).asText().equals(States.PUBLISHED.name()) - && !attestation.get("name").asText().equals(propertyToUpdate) - ){ + && !attestation.get("name").asText().equals(propertyToUpdate) + ) { ObjectNode propertiesOSID = attestation.get("propertiesOSID").deepCopy(); JSONUtil.removeNode(propertiesOSID, uuidPropertyName); ((ObjectNode) attestation).set(_osState.name(), JsonNodeFactory.instance.textNode(States.INVALID.name())); @@ -1076,7 +1035,7 @@ public Vertex deleteEntity(String entityName, String entityId, String userId) th return vertex; } - public JsonNode revokeAnEntity (String entityName, String entityId, String userId, JsonNode currentJsonNode) throws Exception { + public JsonNode revokeAnEntity(String entityName, String entityId, String userId, JsonNode currentJsonNode) throws Exception { RecordIdentifier recordId = RecordIdentifier.parse(entityId); String shardId = dbConnectionInfoMgr.getShardId(recordId.getShardLabel()); Shard shard = shardManager.activateShard(shardId); @@ -1084,7 +1043,7 @@ public JsonNode revokeAnEntity (String entityName, String entityId, String userI ObjectNode newRootNode = objectMapper.createObjectNode(); newRootNode.set(entityName, JSONUtil.convertObjectJsonNode(currentJsonNode)); String jsonString = objectMapper.writeValueAsString(newRootNode); - registryService.updateEntity(shard, userId, recordId.getUuid(),jsonString, true); + registryService.updateEntity(shard, userId, recordId.getUuid(), jsonString, true); return currentJsonNode; } @@ -1198,13 +1157,13 @@ public boolean doesEntityOperationRequireAuthorization(String entity) { boolean hasAttestationPropertiesChanged(JsonNode updatedNode, JsonNode existingNode, AttestationPolicy attestationPolicy, String entityName) { boolean result = false; List paths = new ArrayList<>(attestationPolicy == null ? CollectionUtils.emptyCollection() : attestationPolicy.getAttestationProperties().values()); - for(String path : paths) { + for (String path : paths) { JsonNode extractedExistingAttestationNode = null; JsonNode extractedUpdatedAttestationNode = null; try { extractedExistingAttestationNode = JSONUtil.extractPropertyDataFromEntity(existingNode.get(entityName), attestationPolicy.getAttestationProperties(), null); extractedUpdatedAttestationNode = JSONUtil.extractPropertyDataFromEntity(updatedNode, attestationPolicy.getAttestationProperties(), null); - if(!StringUtils.isEmpty(path) && !(extractedExistingAttestationNode.toString()) + if (!StringUtils.isEmpty(path) && !(extractedExistingAttestationNode.toString()) .equals(extractedUpdatedAttestationNode.toString())) { result = true; } @@ -1273,16 +1232,17 @@ public JsonNode getRequestedUserDetailsCustom(HttpServletRequest request, String throw new Exception(NOT_PART_OF_THE_SYSTEM_EXCEPTION); } + public JsonNode getUserInfoFromRegistryCustomQuery(HttpServletRequest request, String entityName, String filterString) throws Exception { - String userId = getUserId(request,entityName); + String userId = getUserId(request, entityName); if (userId != null) { ObjectNode payload = JsonNodeFactory.instance.objectNode(); payload.set(ENTITY_TYPE, JsonNodeFactory.instance.arrayNode().add(entityName)); ObjectNode filters = JsonNodeFactory.instance.objectNode(); - if(filterString!=null) { + if (filterString != null) { ObjectNode customFilter = (ObjectNode) new ObjectMapper().readTree(filterString); - if(customFilter!=null){ + if (customFilter != null) { Iterator fieldNames = customFilter.fieldNames(); while (fieldNames.hasNext()) { String key = fieldNames.next(); @@ -1293,7 +1253,7 @@ public JsonNode getUserInfoFromRegistryCustomQuery(HttpServletRequest request, S } } ObjectNode contains = JsonNodeFactory.instance.objectNode().put("contains", userId); - filters.set(OSSystemFields.osOwner.toString(), contains); + // filters.set(OSSystemFields.osOwner.toString(), contains); //payload.set(FILTERS, filters.get("filters")); payload.set(FILTERS, filters); @@ -1304,7 +1264,6 @@ public JsonNode getUserInfoFromRegistryCustomQuery(HttpServletRequest request, S } throw new Exception("Forbidden"); } - public JsonNode getUserInfoFromRegistryByOsId(HttpServletRequest request, String entityName, String osid) throws Exception { String userId = getUserId(request,entityName); if (userId != null) { @@ -1327,5 +1286,4 @@ public JsonNode getUserInfoFromRegistryByOsId(HttpServletRequest request, String } throw new Exception("Forbidden"); } - -} +} \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/attestation/AttestationPath.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/attestation/AttestationPath.java index 49dc45b07..a0346ad7f 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/model/attestation/AttestationPath.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/attestation/AttestationPath.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.*; @@ -56,24 +57,42 @@ public Set getEntityPropertyURIs(JsonNode node, String uuidPr if (currNode == null || currNode.isMissingNode()) { continue; } - ArrayNode arrayNode = (ArrayNode) currNode; - for (int j = 0; j < arrayNode.size(); j++) { - if (arrayNode.get(j).isObject()) { - JsonNode uuidNode = arrayNode.get(j).get(uuidPropertyName); - String uuidPointer = SEP; - if (uuidNode == null || uuidNode.isMissingNode()) { - uuidPointer = uuidPointer + EntityPropertyURI.NO_UUID; + ArrayNode arrayNode = null; + ObjectNode objectNode = null; + if(currNode instanceof ArrayNode){ + arrayNode = (ArrayNode) currNode; + for (int j = 0; j < arrayNode.size(); j++) { + if (arrayNode.get(j).isObject()) { + JsonNode uuidNode = arrayNode.get(j).get(uuidPropertyName); + String uuidPointer = SEP; + if (uuidNode == null || uuidNode.isMissingNode()) { + uuidPointer = uuidPointer + EntityPropertyURI.NO_UUID; + } else { + uuidPointer = uuidPointer + uuidNode.asText(); + } + currPaths.add(EntityPropertyURI.merge(currPath, + uuidPointer, + SEP + j + )); } else { - uuidPointer = uuidPointer + uuidNode.asText(); + currPaths.add(EntityPropertyURI.merge(currPath, SEP + j, SEP + j)); } - currPaths.add(EntityPropertyURI.merge(currPath, - uuidPointer, - SEP + j - )); + } + } else if(currNode instanceof ObjectNode){ + objectNode = (ObjectNode) currNode; + String uuidPointer = SEP; + if (objectNode == null || objectNode.isMissingNode()) { + uuidPointer = uuidPointer + EntityPropertyURI.NO_UUID; } else { - currPaths.add(EntityPropertyURI.merge(currPath, SEP + j, SEP + j)); + uuidPointer = uuidPointer + objectNode.asText(); } + currPaths.add(EntityPropertyURI.merge(currPath, + uuidPointer, + SEP + )); } + + } } return new HashSet<>(currPaths); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java index fdf00989e..820accdcb 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NativeSearchService.java @@ -75,7 +75,7 @@ public class NativeSearchService implements ISearchService { @Value("${search.expandInternal}") private boolean expandInternal; - @Value("${search.removeNonPublicFieldsForNativeSearch:true}") + @Value("${search.removeNonPublicFieldsForNativeSearch:false}") private boolean removeNonPublicFieldsForNativeSearch; @Override diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index 6d824bcad..d1c738af9 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -38,6 +38,7 @@ public class ClaimRequestClient { private static final String CLAIMS_PATH = "/api/v1/claims"; private static final String FETCH_CLAIMS_PATH = "/api/v1/getClaims"; + private static final String FETCH_CLAIMS_STUDENT_PATH = "/api/v2/getClaims"; private static final String MAIL_SEND_URL = "/api/v1/sendMail"; private static final String BAR_CODE_API = "/api/v1/barcode"; private static final String SAVE_CRED_API = "/api/v1/credentials/save"; @@ -66,6 +67,14 @@ public JsonNode getClaims(JsonNode jsonNode, Pageable pageable, String entityNam return restTemplate.postForObject(claimRequestUrl + FETCH_CLAIMS_PATH + QUERY_PARAMS, requestBody, JsonNode.class); } + public JsonNode getStudentsClaims(JsonNode jsonNode, Pageable pageable, String entityName) { + final String QUERY_PARAMS = "?size=" + pageable.getPageSize() + "&page="+pageable.getPageNumber(); + ObjectNode requestBody = JsonNodeFactory.instance.objectNode(); + requestBody.set("attestorInfo", jsonNode); + requestBody.put("entity", entityName); + return restTemplate.postForObject(claimRequestUrl + FETCH_CLAIMS_STUDENT_PATH + QUERY_PARAMS, requestBody, JsonNode.class); + } + public JsonNode getClaim(JsonNode jsonNode, String entityName, String claimId) { ObjectNode requestBody = JsonNodeFactory.instance.objectNode(); requestBody.set("attestorInfo", jsonNode); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java index ea8953c2c..1034d70ab 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java @@ -154,13 +154,10 @@ public static String getXmlString(String xmlString) { sb.append("\"name\""+":"+"\""+docDetails.getName()+"\""+","); if(docDetails.getMobile()!=null) sb.append("\"mobile\""+":"+"\""+docDetails.getMobile()+"\""+","); - if(docDetails.getDateOfBirth()!=null) - sb.append("\"dob\""+":"+"\""+docDetails.getDateOfBirth()+"\""+","); - if(docDetails.getRollNumber()!=null) - sb.append("\"rollNumber\""+":"+"\""+docDetails.getRollNumber()+"\""); - else if (docDetails.getEnrollmentNumber() != null) { - sb.append("\"enrollmentNumber\""+":"+"\""+docDetails.getEnrollmentNumber()+"\""); - } +// if(docDetails.getDateOfBirth()!=null) +// sb.append("\"dob\""+":"+"\""+docDetails.getDateOfBirth()+"\""+","); + if(docDetails.getFinalYearRollNo()!=null) + sb.append("\"finalYearRollNo\""+":"+"\""+docDetails.getFinalYearRollNo()+"\""); sb.append("}"); xmlString = sb.toString(); } catch (JAXBException e) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java index d3feb9134..485f61baf 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java @@ -8,22 +8,23 @@ public class DocDetails { private String digiLockerId; private String mobile; private String name; - private String rollNumber; - private String dateOfBirth; + private String finalYearRollNo; private String docType; - private String enrollmentNumber; + public String getFinalYearRollNo() { + return finalYearRollNo; + } + public void setFinalYearRollNo(String finalYearRollNo) { + this.finalYearRollNo = finalYearRollNo; + } - private String entityName; - public String getEnrollmentNumber() { - return enrollmentNumber; - } - public void setEnrollmentNumber(String enrollmentNumber) { - this.enrollmentNumber = enrollmentNumber; - } + + + private String entityName; + public String getuID() { return uID; @@ -57,21 +58,8 @@ public void setName(String name) { this.name = name; } - public String getRollNumber() { - return rollNumber; - } - public void setRollNumber(String rollNumber) { - this.rollNumber = rollNumber; - } - public String getDateOfBirth() { - return dateOfBirth; - } - - public void setDateOfBirth(String dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } public String getDocType() { return docType; diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index c93c8fd43..49a05a5da 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -57,7 +57,7 @@ registry: rootEntity: type: ${registry_rootentity_type:Regulator} schema: - url: ${registry_schema_url:D:/Registry/sunbird-rc-core/java/registry/src/main/resources/public/_schemas} + url: ${registry_schema_url:/src/main/resources/public/_schemas} attestationPolicy: createAccess: ${create_attestation_access_entities:User} manager: @@ -87,7 +87,7 @@ kafka: postCreateEntityTopic: ${kafka_post_create_entity_topic:post_create_entity} webhook: - enabled: ${webhook_enabled:false} + enabled: ${webhook_enabled:true} url: ${webhook_url:http://localhost:5001/api/v1/callback} conditionalAccess: @@ -105,8 +105,8 @@ search: # not offer high speed reads. This is the default search service, if this config is not provided. # If ElasticSearchService, then Elastic search is used. expandInternal: ${search_expandInternal:true} - removeNonPublicFieldsForNativeSearch: ${remove_non_public_fields_for_native_search:true} - providerName: ${search_providerName:dev.sunbirdrc.registry.service.NativeSearchService} + removeNonPublicFieldsForNativeSearch: ${remove_non_public_fields_for_native_search:false} + providerName: ${search_providerName:dev.sunbirdrc.registry.service.ElasticSearchService} # This property is to be used for read request read: @@ -239,10 +239,10 @@ keycloak: resource: ${sunbird_sso_client_id:client} keycloak-admin: client-id: ${sunbird_sso_admin_client_id:admin-api} - client-secret: ${sunbird_sso_admin_client_secret:19013b22-82b2-4a7b-a0ef-10ced3ef36f7} + client-secret: ${sunbird_sso_admin_client_secret:2b65f70c-bd02-4d5c-95d9-5341225aa849} keycloak-user: set-default-password: ${sunbird_keycloak_user_set_password:true} - default-password: ${sunbird_keycloak_user_password:medicalCouncil@123} + default-password: ${sunbird_keycloak_user_password:admin@123} # email actions which will be trigger by keycloak # example email actions: VERIFY_EMAIL, UPDATE_PROFILE, UPDATE_PASSWORD, TERMS_AND_CONDITIONS etc. # email details should be configured in keycloak realm settings @@ -308,7 +308,7 @@ auditTaskExecutor: elastic: search: # elastic-search can be enable and disable through this flag - enabled: ${elastic_search_enabled:false} + enabled: ${elastic_search_enabled:true} # elastic-search connection info connection_url: ${elastic_search_connection_url:localhost:9200} add_shard_prefix: ${elastic_search_add_shard_prefix:true} @@ -358,7 +358,7 @@ registry: # This property is to be used for read request read: # The read mechanism to use, values could be either NativeReadService or ElasticReadService - providerName: io.opensaber.registry.service.NativeReadService + providerName: io.opensaber.registry.service.ElasticReadService database: # This property is internal. Clients use this property to perform read/update operation. diff --git a/java/registry/src/main/resources/public/_schemas/BaseAttestationField.json b/java/registry/src/main/resources/public/_schemas/BaseAttestationField.json new file mode 100644 index 000000000..aff8ebb24 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/BaseAttestationField.json @@ -0,0 +1,20 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "title": "BaseAttestationField", + "definitions": { + "baseAttestationField": { + "title": "BaseAttestationField", + "type": "object", + "properties": { + "state": { + "type": "string", + "description": "field state (draft, submitted, attested, invalid)" + }, + "signature": { + "type": "string", + "description": "digital signature after attestation. Contains attested data, attestorInfo and verification details" + } + } + } + } +} diff --git a/java/registry/src/main/resources/public/_schemas/Common.json b/java/registry/src/main/resources/public/_schemas/Common.json new file mode 100644 index 000000000..77cc05d08 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/Common.json @@ -0,0 +1,393 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "title": "Common", + "definitions": { + "IdentityDetails": { + "type": "object", + "title": "Identity Details", + "description": "Identity Details", + "required": [], + "properties": { + "fullName": { + "$id": "#/properties/fullName", + "type": "string", + "title": "Full name" + }, + "gender": { + "$id": "#/properties/gender", + "type": "string", + "enum": [ + "Male", + "Female", + "Other" + ], + "title": "Gender" + }, + "dob": { + "$id": "#/properties/dob", + "type": "string", + "format": "date", + "title": "DOB" + }, + "identityHolder": { + "type": "object", + "properties": { + "type": { + "$id": "#/properties/type", + "type": "string", + "$comment": "Nationality", + "title": "ID Type", + "enum": [ + "AADHAR", + "PAN", + "LICENSE", + "OTHER" + ] + }, + "value": { + "$id": "#/properties/value", + "type": "string", + "$comment": "Nationality", + "title": "ID Value" + } + } + } + } + }, + "ContactDetails": { + "type": "object", + "title": "Contact Details", + "description": "Contact Details", + "required": [], + "properties": { + "email": { + "$id": "#/properties/email", + "type": "string", + "title": "Email" + }, + "mobile": { + "$id": "#/properties/mobile", + "type": "string", + "title": "Mobile" + }, + "address": { + "$id": "#/properties/address", + "$ref": "#/definitions/Address", + "title": "Address" + } + } + }, + "AcademicQualification": { + "type": "object", + "properties": { + "instituteOSID": { + "$id": "#/properties/instituteOSID", + "type": "string", + "title": "Institute OSID" + }, + "instituteName": { + "$id": "#/properties/instituteName", + "type": "string", + "title": "Institute Name" + }, + "qualification": { + "$id": "#/properties/qualification", + "type": "string", + "title": "Qualification" + }, + "program": { + "$id": "#/properties/program", + "type": "string", + "title": "Program of Study" + }, + "graduationYear": { + "$id": "#/properties/graduationYear", + "type": "string", + "title": "Year of Graduation" + }, + "marks": { + "$id": "#/properties/marks", + "type": "string", + "title": "Marks / Ranking / GPA, etc" + } + } + }, + "ExperienceType": { + "type": "object", + "properties": { + "instituteOSID": { + "$id": "#/properties/instituteOSID", + "type": "string", + "title": "Institute OSID" + }, + "instituteName": { + "$id": "#/properties/instituteName", + "type": "string", + "title": "Institute Name" + }, + "employmentType": { + "$id": "#/properties/employmentType", + "type": "string", + "title": "Employment Type", + "enum": [ + "Permanent", + "Contract" + ] + }, + "start": { + "$id": "#/properties/start", + "type": "string", + "format": "date", + "title": "Start Date" + }, + "end": { + "$id": "#/properties/end", + "type": "string", + "format": "date", + "title": "End Date" + }, + "teacherType": { + "$id": "#/properties/teacherType", + "type": "string", + "title": "Teacher Type", + "enum": [ + "Head teacher", + "Acting head teacher", + "Teacher", + "Instructor positioned as per RTE", + "Principal", + "VicePrincipal", + "Lecturer" + ] + }, + "subjectsTaught": { + "$id": "#/properties/subjectsTaught", + "title": "Subjects Taught", + "type": "array", + "items": { + "type": "object", + "properties": { + "subjects": { + "$id": "#/properties/subjects", + "type": "string", + "title": "Subject", + "enum": [ + "English", + "Kannada", + "Mathematics", + "Science", + "Social Science", + "Art" + ] + }, + "grades": { + "$id": "#/properties/grades", + "type": "string", + "title": "Grades", + "enum": [ + "Pre-Pri.", + "Class I", + "Class II", + "Class III", + "Class IV", + "Class V", + "Class VI", + "Class VII", + "Class VIII", + "Class IX", + "Class X", + "Class XI", + "Class XII" + ] + } + } + } + } + } + }, + "EducationType": { + "type": "object", + "properties": { + "institute": { + "$id": "#/properties/institute", + "type": "string", + "title": "Institute Name" + }, + "instituteOSID": { + "$id": "#/properties/instituteOSID", + "type": "string", + "title": "Institute Osid" + }, + "board": { + "$id": "#/properties/board", + "type": "string", + "title": "Board of Education" + }, + "medium": { + "$id": "#/properties/program", + "type": "string", + "enum": [ + "English", + "Hindi", + "Gujarati", + "Malayalam", + "Tamil" + ], + "title": "Medium of Education" + }, + "class": { + "$id": "#/properties/graduationYear", + "type": "string", + "enum": [ + "Pre-Pri.", + "Class I", + "Class II", + "Class III", + "Class IV", + "Class V", + "Class VI", + "Class VII", + "Class VIII", + "Class IX", + "Class X", + "Class XI", + "Class XII" + ], + "title": "Current Enrollment Class / Std." + }, + "documents": { + "type": "array", + "items": { + "type": "object", + "properties": { + "fileName": { + "type": "string", + "format": "file" + } + } + }, + "title": "Education related documents" + } + } + }, + "GuardianDetails": { + "type": "object", + "properties": { + "fullName": { + "$id": "#/properties/fullName", + "type": "string", + "title": "Guardian's Full Name" + }, + "relation": { + "$id": "#/properties/relation", + "type": "string", + "title": "Guardian Relation type" + } + } + }, + "CertificationType": { + "type": "object", + "properties": { + "institute": { + "type": "string" + }, + "start": { + "type": "string", + "format": "date" + }, + "end": { + "type": "string", + "format": "date" + } + } + }, + "Document": { + "type": "object", + "properties": { + "fileName": { + "type": "string", + "format": "file" + } + } + }, + "Address": { + "type": "object", + "required": [ + ], + "additionalProperties": false, + "properties": { + "plot": { + "type": "string", + "title": "Plot" + }, + "street": { + "type": "string", + "title": "Street" + }, + "landmark": { + "type": "string", + "title": "Landmark" + }, + "locality": { + "type": "string", + "title": "Locality" + }, + "state": { + "type": "string", + "title": "State", + "enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] + }, + "district": { + "type": "string", + "title": "District" + }, + "village": { + "type": "string", + "title": "Village/Town/City" + }, + "pincode": { + "type": "string", + "title": "Pincode" + } + } + } + } +} diff --git a/java/registry/src/main/resources/public/_schemas/Institute.json b/java/registry/src/main/resources/public/_schemas/Institute.json new file mode 100644 index 000000000..82f9f84cf --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/Institute.json @@ -0,0 +1,212 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "Institute": { + "$ref": "#/definitions/Institute" + } + }, + "required": [ + "Institute" + ], + "title": "Institute", + "definitions": { + "Institute": { + "$id": "#/properties/Institute", + "type": "object", + "title": "The Institute Schema", + "required": [], + "properties": { + "instituteName": { + "$id": "#/properties/instituteName", + "type": "string", + "title": "Institute Name" + }, + "address": { + "$ref": "Common.json/#/definitions/Address", + "title": "Address" + }, + "establishmentYear": { + "$id": "#/properties/establishmentYear", + "type": "integer", + "title": "Year of establishment of institute" + }, + "gstnId": { + "$id": "#/properties/gstnId", + "type": "string", + "title": "GSTN ID" + }, + "contactNumber": { + "$id": "#/properties/contactNumber", + "type": "string", + "title": "Landline / Mobile" + }, + "email": { + "$id": "#/properties/email", + "type": "string", + "format": "email", + "title": "Email" + }, + "website": { + "$id": "#/properties/website", + "type": "string", + "format": "uri", + "title": "Website" + }, + "category": { + "$id": "#/properties/category", + "type": "string", + "title": "Institute Category (Primary/Secondary etc)", + "enum": [ + "Primary", + "Secondary" + ] + }, + "schoolType": { + "$id": "#/properties/schoolType", + "type": "string", + "title": "School Type ", + "enum": [ + "Boys", + "Girls", + "Co-ed" + ] + }, + "instituteManagement": { + "$id": "#/properties/instituteManagement", + "type": "string", + "title": "Management of institute" + }, + "committee": { + "$id": "#/properties/instituteManagement", + "type": "string", + "title": "Name of Trust / Society / Managing Committee" + }, + "adminName": { + "$id": "#/properties/adminName", + "type": "string", + "title": "Principal / Dean / Head - Full Name" + }, + "adminEmail": { + "$id": "#/properties/adminEmail", + "type": "string", + "title": "Principal / Dean / Head - Email" + }, + "adminMobile": { + "$id": "#/properties/adminMobile", + "type": "string", + "title": "Principal / Dean / Head - Mobile" + }, + "affiliation": { + "type": "array", + "items": { + "$ref": "#/definitions/Affiliation" + }, + "title": "Affiliation" + } + } + }, + "Affiliation": { + "type": "object", + "properties": { + "medium": { + "type": "string", + "enum": ["English", "Hindi", "Gujarati", "Malayalam", "Tamil"], + "title": "Medium of Education" + }, + "board": { + "type": "string", + "title": "Affiliations Board" + }, + "affiliationNumber": { + "type": "string", + "title": "Affiliation Number" + }, + "grantYear": { + "type": "string", + "title": "Grant year" + }, + "expiryYear": { + "type": "string", + "title": "Expiry Year" + }, + "classes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "Pre-Pri.", + "Class I", + "Class II", + "Class III", + "Class IV", + "Class V", + "Class VI", + "Class VII", + "Class VIII", + "Class IX", + "Class X", + "Class XI", + "Class XII" + ] + }, + "title": "Classes / Grades" + } + } + } + }, + "_osConfig": { + "osComment": [ + "This section contains the specific configuration information", + "privateFields: Optional; list of field names to be encrypted and stored in database", + "signedFields: Optional; list of field names that must be pre-signed", + "indexFields: Optional; list of field names used for creating index. Enclose within braces to indicate it is a composite index. In this definition, (serialNum, schoolCode) is a composite index and schoolName is a single column index.", + "uniqueIndexFields: Optional; list of field names used for creating unique index. Field names must be different from index field name", + "systemFields: Optional; list of fields names used for system standard information like created, updated timestamps and userid" + ], + "privateFields": [ + "$.contactNumber", + "$.email" + ], + "internalFields": [ + "$.adminEmail", + "$.adminMobile" + ], + "indexFields": [], + "uniqueIndexFields": [ + "instituteName" + ], + "systemFields": [ + "osCreatedAt", + "osUpdatedAt", + "osCreatedBy", + "osUpdatedBy" + ], + "attestationPolicies": [ + { + "name": "instituteAffiliation", + "conditions": "(ATTESTOR#$.[*]#.contains('board-cbse'))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=board-cbse", + "attestationProperties": { + "affiliation": "$.affiliation", + "instituteName": "$.instituteName" + } + } + ], + "inviteRoles":["anonymous"], + "roles":[], + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/contactNumber", + "userId": "/email" + }, + { + "email": "/adminEmail", + "mobile": "/adminMobile", + "userId": "/adminEmail" + } + ] + } +} diff --git a/java/registry/src/main/resources/public/_schemas/Student.json b/java/registry/src/main/resources/public/_schemas/Student.json new file mode 100644 index 000000000..58c07f649 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/Student.json @@ -0,0 +1,87 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { "Student": { "$ref": "#/definitions/Student" } }, + "required": ["Student"], + "title": "Student", + "definitions": { + "Student": { + "$id": "#/properties/Student", + "type": "object", + "title": "Student", + "required": ["name", "phoneNumber", "email", "school"], + "uniqueIndexFields": ["phoneNumber"], + "properties": { + "name": { "type": "string" }, + "phoneNumber": { "type": "string" }, + "email": { "type": "string" }, + "school": { "type": "string" } + } + } + }, + "_osConfig": { + + "ownershipAttributes": [ + { + "email": "/email", + "mobile": "/phoneNumber", + "userId": "/phoneNumber" + } + ], + "inviteRoles": ["anonymous"], + "roles": ["Regulator"], + "attestationPolicies": [ + { + "name": "studentVerification", + "conditions": "(ATTESTOR#$.school#.contains(REQUESTER#$.school#))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", + "attestationProperties": { + "name": "$.name", + "school": "$.school" + }, + "credentialTemplate": { + "@context": [ + "https://www.w3.org/2018/credentials/v1", + { + "@version": 1.1, + "@protected": true, + "SkillCertificate": { + "@id": "https://github.com/sunbird-specs/vc-specs#SkillCertificate", + "@context": { + "id": "@id", + "@version": 1.1, + "@protected": true, + "skills": "schema:Text" + } + }, + "Person": { + "@id": "https://github.com/sunbird-specs/vc-specs#Person", + "@context": { + "name": "schema:Text" + } + }, + "trainedOn": { + "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", + "@context": { + "name": "schema:Text" + } + } + } + ], + "type": ["VerifiableCredential"], + "issuanceDate": "2021-08-27T10:57:57.237Z", + "credentialSubject": { + "type": "Person", + "name": "{{name}}", + "trainedOn": "{{school}}" + }, + "issuer": "did:web:sunbirdrc.dev/vc/skill" + } + } + ], + "certificateTemplates": { + "svg": "https://raw.githubusercontent.com/aniket-aditya/sunbird-rc/main/rc-demo-template.svg" + } + } +} diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 07b47be59..3c9977867 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -13,198 +13,155 @@ "$id": "#/properties/StudentFromUP", "type": "object", "title": "StudentFromUP", + "required": ["name", "phoneNumber", "email", "council"], + "uniqueIndexFields": [ + "phoneNumber" + ], "properties": { - "registrationType": { - "$id": "#/properties/registrationType", + "name": { + "type": "string" + }, + "phoneNumber": { + "type": "string" + }, + "email": { + "type": "string" + }, + "council": { + "type": "string" + }, + "mothersName": { "type": "string", - "title": "registrationType", - "required": [ - "name", - "phoneNumber", - "email", - "council" - ], - "uniqueIndexFields": [ - "phoneNumber" - ], - "properties": { - "name": { - "type": "string" - }, - "phoneNumber": { - "type": "string" - }, - "email": { - "type": "string" - }, - "council": { - "type": "string" - }, - "mothersName": { - "$id": "#/properties/mothersName", - "type": "string", - "title": "motherName" - }, - "fathersName": { - "$id": "#/properties/fathersName", - "type": "string", - "title": "fatherName" - }, - "dateOfBirth": { - "$id": "#/properties/dateOfBirth", - "type": "string", - "title": "dateOfBirth" - }, - "aadhaarNo": { - "$id": "#/properties/aadhaarNo", - "type": "string", - "title": "aadhaarNo" - }, - "barCode": { - "$id": "#/properties/barCode", - "type": "string", - "title": "barCode" - }, - "gender": { - "$id": "#/properties/gender", - "type": "string", - "title": "gender", - "enum": ["male", "female"] - }, - "address": { - "$id": "#/properties/address", - "type": "object", - "title": "address", - "required": [], - "properties": { - "address-text": { - "type": "string", - "title": "Plot" - }, - "state": { - "$id": "#/properties/state", - "type": "string", - "title": "State", - "enum": [ - "Andaman and Nicobar Islands", - "Andhra Pradesh", - "Arunachal Pradesh", - "Assam", - "Bihar", - "Chandigarh", - "Chhattisgarh", - "Dadra and Nagar Haveli", - "Daman and Diu", - "Delhi", - "Goa", - "Gujarat", - "Haryana", - "Himachal Pradesh", - "Jammu and Kashmir", - "Jharkhand", - "Karnataka", - "Kerala", - "Ladakh", - "Lakshadweep", - "Madhya Pradesh", - "Maharashtra", - "Manipur", - "Meghalaya", - "Mizoram", - "Nagaland", - "Odisha", - "Puducherry", - "Punjab", - "Rajasthan", - "Sikkim", - "Tamil Nadu", - "Telangana", - "Tripura", - "Uttar Pradesh", - "Uttarakhand", - "West Bengal" - ] - }, - "district": { - "$id": "#/properties/district", - "type": "string", - "title": "district" - }, - "country": { - "$id": "#/properties/country", - "type": "string", - "title": "country" - }, - "pincode": { - "$id": "#/properties/pincode", - "type": "string", - "title": "pincode" - } - } - }, - "courseName": { - "$id": "#/properties/courseName", - "type": "string", - "title": "courseName" - }, - "nursingCollage": { - "$id": "#/properties/nursingCollage", - "type": "string", - "title": "nursingCollage" - }, - "joiningMonth": { - "$id": "#/properties/joiningMonth", - "type": "string", - "title": "joiningMonth" - }, - "joiningYear": { - "$id": "#/properties/joiningYear", - "type": "string", - "title": "joiningYear" - }, - "passingMonth": { - "$id": "#/properties/passingMonth", - "type": "string", - "title": "passingMonth" - }, - "passingYear": { - "$id": "#/properties/passingYear", - "type": "string", - "title": "passingYear" - }, - "finalYearRollNo": { - "$id": "#/properties/finalYearRollNo", - "type": "string", - "title": "finalYearRollNo" - }, - "examBody": { - "$id": "#/properties/examBody", - "type": "string", - "title": "examBody" - }, - "doc-proof": { - "type": "array", - "items": { - "type": "string" - }, - "title": "All Document Proof" - }, - "candidatePic": { - "$id": "#/properties/candidatePic", - "type": "string", - "title": "candidatePic" - }, - "paymentStatus": { - "$id": "#/properties/paymentStatus", - "type": "string", - "title": "paymentStatus" - }, - "feeReciptNo": { - "$id": "#/properties/feeReciptNo", - "type": "string", - "title": "feeReciptNo" - } - } + "title": "motherName" + }, + "fathersName": { + "type": "string", + "title": "fatherName" + }, + "dateOfBirth": { + "type": "string", + "title": "dateOfBirth" + }, + "aadhaarNo": { + "type": "string", + "title": "aadhaarNo" + }, + "barCode": { + "type": "string", + "title": "barCode" + }, + "gender": { + "type": "string", + "title": "gender", + "enum": ["male", "female"] + }, + "address": { + "type": "string"}, + "state": { + "type": "string", + "title": "State", + "enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] + }, + "district": { + "type": "string", + "title": "district" + }, + "country": { + "type": "string", + "title": "country" + }, + "pincode": { + "type": "string", + "title": "pincode" + }, + "candidatePic": { + "type": "string", + "title": "candidatePic" + }, + "doc-proof": { + "type": "string", + "items": { + "type": "string" + }, + "title": "All Document Proof" + }, + "courseName": { + "type": "string", + "title": "courseName" + }, + "nursingCollage": { + "type": "string", + "title": "nursingCollage" + }, + "joiningMonth": { + "type": "string", + "title": "joiningMonth" + }, + "joiningYear": { + "type": "string", + "title": "joiningYear" + }, + "passingMonth": { + "type": "string", + "title": "passingMonth" + }, + "passingYear": { + "type": "string", + "title": "passingYear" + }, + "finalYearRollNo": { + "type": "string", + "title": "finalYearRollNo" + }, + "feeReciptNo": { + "type": "string", + "title": "feeReciptNo" + }, + "examBody": { + "type": "string", + "title": "examBody" + }, + "paymentStatus": { + "type": "string", + "title": "paymentStatus" } } } @@ -219,6 +176,7 @@ ], "inviteRoles": ["anonymous"], "roles": ["StudentFromUP"], + "attestationPolicies": [ { "name": "studentUPVerification", @@ -242,7 +200,12 @@ "doc-proof": "$.doc-proof", "candidatePic": "$.candidatePic", "paymentStatus": "$.paymentStatus", - "feeReciptNo": "$.feeReciptNo" + "feeReciptNo": "$.feeReciptNo", + "address": "$.address", + "state": "$.state", + "district": "$.district", + "country": "$.country", + "pincode": "$.pincode" }, "credentialTemplate": { "@context": [ @@ -265,12 +228,6 @@ "name": "schema:Text" } }, - "trainedOn": { - "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", - "@context": { - "name": "schema:Text" - } - }, "mothersName": { "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", "@context": { @@ -289,6 +246,30 @@ "name": "schema:Text" } }, + "state": { + "@id": "https://github.com/sunbird-specs/vc-specs#state", + "@context": { + "name": "schema:Text" + } + }, + "district": { + "@id": "https://github.com/sunbird-specs/vc-specs#district", + "@context": { + "name": "schema:Text" + } + }, + "country": { + "@id": "https://github.com/sunbird-specs/vc-specs#country", + "@context": { + "name": "schema:Text" + } + }, + "pincode": { + "@id": "https://github.com/sunbird-specs/vc-specs#pincode", + "@context": { + "name": "schema:Text" + } + }, "courseName": { "@id": "https://github.com/sunbird-specs/vc-specs#courseName", "@context": { @@ -377,7 +358,6 @@ "name": "{{name}}", "mothersName": "{{mothersName}}", "fathersName": "{{fathersName}}", - "address": "{{address}}", "courseName": "{{courseName}}", "joiningMonth": "{{joiningMonth}}", "joiningYear": "{{joiningYear}}", @@ -387,7 +367,13 @@ "finalYearRollNo": "{{finalYearRollNo}}", "date": "{{date}}", "candidatePic": "{{candidatePic}}", - "feeReciptNo": "{{feeReciptNo}}" + "feeReciptNo": "{{feeReciptNo}}", + "council": "{{council}}", + "address": "{{address}}", + "district": "{{district}}", + "country": "{{country}}", + "state": "{{state}}", + "pincode": "{{pincode}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/teacher.json b/java/registry/src/main/resources/public/_schemas/teacher.json index 70b78de91..219c5255a 100644 --- a/java/registry/src/main/resources/public/_schemas/teacher.json +++ b/java/registry/src/main/resources/public/_schemas/teacher.json @@ -44,6 +44,7 @@ "userId": "/phoneNumber" } ], - "inviteRoles": ["anonymous"] + "inviteRoles": ["anonymous"], + "roles": ["Teacher"] } } From fd31bc3cd8ad0152ffc48fa38af472829d4ededc Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 15 Aug 2023 07:36:50 +0530 Subject: [PATCH 16/43] json correction --- .../resources/public/_schemas/Student.json | 67 ++++++++++++++++--- .../public/_schemas/studentFromUP.json | 37 +++------- 2 files changed, 65 insertions(+), 39 deletions(-) diff --git a/java/registry/src/main/resources/public/_schemas/Student.json b/java/registry/src/main/resources/public/_schemas/Student.json index 58c07f649..f092c16e3 100644 --- a/java/registry/src/main/resources/public/_schemas/Student.json +++ b/java/registry/src/main/resources/public/_schemas/Student.json @@ -9,13 +9,17 @@ "$id": "#/properties/Student", "type": "object", "title": "Student", - "required": ["name", "phoneNumber", "email", "school"], + "required": ["name", "phoneNumber", "email", "council"], "uniqueIndexFields": ["phoneNumber"], "properties": { "name": { "type": "string" }, "phoneNumber": { "type": "string" }, "email": { "type": "string" }, - "school": { "type": "string" } + "council": { "type": "string" }, + "mothersName": {"type": "string", "title": "motherName"}, + "fathersName": { "type": "string","title": "fatherName"}, + "dateOfBirth": {"type": "string", "title": "dateOfBirth"}, + "aadhaarNo": {"type": "string", "title": "aadhaarNo"} } } }, @@ -33,12 +37,18 @@ "attestationPolicies": [ { "name": "studentVerification", - "conditions": "(ATTESTOR#$.school#.contains(REQUESTER#$.school#))", + "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", "type": "MANUAL", "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", "attestationProperties": { "name": "$.name", - "school": "$.school" + "email": "$.email", + "phoneNumber": "$.phoneNumber", + "council": "$.council", + "mothersName": "$.mothersName", + "fathersName": "$.fathersName", + "dateOfBirth": "$.dateOfBirth", + "aadhaarNo": "$.aadhaarNo" }, "credentialTemplate": { "@context": [ @@ -61,12 +71,42 @@ "name": "schema:Text" } }, - "trainedOn": { - "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", + "council": { + "@id": "https://github.com/sunbird-specs/vc-specs#council", "@context": { "name": "schema:Text" - } - } + }}, + "mothersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", + "@context": { + "name": "schema:Text" + }}, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + }}, + "dateOfBirth": { + "@id": "https://github.com/sunbird-specs/vc-specs#dateOfBirth", + "@context": { + "name": "schema:Text" + }}, + "aadhaarNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#aadhaarNo", + "@context": { + "name": "schema:Text" + }}, + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@context": { + "name": "schema:Text" + }}, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + }} + } ], "type": ["VerifiableCredential"], @@ -74,14 +114,21 @@ "credentialSubject": { "type": "Person", "name": "{{name}}", - "trainedOn": "{{school}}" + "mothersName": "{{mothersName}}", + "fathersName": "{{fathersName}}", + "dateOfBirth": "{{dateOfBirth}}", + "aadhaarNo": "{{aadhaarNo}}", + "council": "{{council}}", + "email": "{{email}}", + "phoneNumber": "{{phoneNumber}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } } ], "certificateTemplates": { - "svg": "https://raw.githubusercontent.com/aniket-aditya/sunbird-rc/main/rc-demo-template.svg" + "svg": "https://raw.githubusercontent.com/aniket-aditya/sunbird-rc/main/rc-demo-template.svg", + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" } } } diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 3c9977867..d5735ed5e 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -17,35 +17,14 @@ "uniqueIndexFields": [ "phoneNumber" ], - "properties": { - "name": { - "type": "string" - }, - "phoneNumber": { - "type": "string" - }, - "email": { - "type": "string" - }, - "council": { - "type": "string" - }, - "mothersName": { - "type": "string", - "title": "motherName" - }, - "fathersName": { - "type": "string", - "title": "fatherName" - }, - "dateOfBirth": { - "type": "string", - "title": "dateOfBirth" - }, - "aadhaarNo": { - "type": "string", - "title": "aadhaarNo" - }, + "properties": {"name": {"type": "string"}, + "phoneNumber": {"type": "string"}, + "email": {"type": "string"}, + "council": {"type": "string"}, + "mothersName": {"type": "string", "title": "motherName"}, + "fathersName": { "type": "string","title": "fatherName"}, + "dateOfBirth": {"type": "string", "title": "dateOfBirth"}, + "aadhaarNo": {"type": "string", "title": "aadhaarNo"}, "barCode": { "type": "string", "title": "barCode" From 0252ce4676ed7b311653a2320b8297a5b1d22e64 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Wed, 16 Aug 2023 10:25:18 +0530 Subject: [PATCH 17/43] json fix --- .../src/main/resources/application.yml | 2 +- .../public/_schemas/Registration.json | 342 ++++++++++++++++++ .../resources/public/_schemas/Student.json | 233 ++++++++++-- .../public/_schemas/studentFromUP.json | 329 ++++++++--------- 4 files changed, 695 insertions(+), 211 deletions(-) create mode 100644 java/registry/src/main/resources/public/_schemas/Registration.json diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 49a05a5da..143429a40 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -59,7 +59,7 @@ registry: schema: url: ${registry_schema_url:/src/main/resources/public/_schemas} attestationPolicy: - createAccess: ${create_attestation_access_entities:User} + createAccess: ${create_attestation_access_entities:Regulator} manager: type: ${manager_type:DefinitionsManager} redis: diff --git a/java/registry/src/main/resources/public/_schemas/Registration.json b/java/registry/src/main/resources/public/_schemas/Registration.json new file mode 100644 index 000000000..104a53483 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/Registration.json @@ -0,0 +1,342 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { "Registration": { "$ref": "#/definitions/Registration" } }, + "required": ["Registration"], + "title": "Registration", + "definitions": { + "Registration": { + "$id": "#/properties/Registration", + "type": "object", + "title": "Registration", + "required": ["name", "phoneNumber", "email", "council"], + "uniqueIndexFields": ["phoneNumber"], + "properties": { + "name": { "type": "string" }, + "phoneNumber": { "type": "string" }, + "email": { "type": "string" }, + "council": { "type": "string" }, + "mothersName": {"type": "string", "title": "motherName"}, + "fathersName": { "type": "string","title": "fatherName"}, + "dateOfBirth": {"type": "string", "title": "dateOfBirth"}, + "aadhaarNo": {"type": "string", "title": "aadhaarNo"}, + "gender": {"type": "string", "title": "gender", "enum": ["male", "female"]}, + "address": {"type": "string", "title": "address"}, + "state": { "type": "string", "title": "State","enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] }, + "district": {"type": "string", "title": "district"}, + "country": {"type": "string", "title": "country"}, + "pincode": {"type": "string", "title": "pincode"}, + "candidatePic": {"type": "string", "title": "candidatePic"}, + "courseName": {"type": "string","title": "courseName"}, + "nursingCollage": {"type": "string", "title": "nursingCollage"}, + "joiningMonth": {"type": "string","title": "joiningMonth"}, + "joiningYear": {"type": "string", "title": "joiningYear"}, + "passingMonth": {"type": "string", "title": "passingMonth"}, + "passingYear": {"type": "string","title": "passingYear"}, + "examBody":{"type": "string","title": "examBody"}, + "paymentStatus":{"type": "string","title": "paymentStatus"} + } + } + }, + "_osConfig": { + + "ownershipAttributes": [ + ], + "inviteRoles": ["anonymous"], + "roles": ["Regulator","Student"], + "attestationPolicies": [ + { + "name": "studentVerification", + "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", + "attestationProperties": { + "name": "$.name", + "email": "$.email", + "phoneNumber": "$.phoneNumber", + "council": "$.council", + "mothersName": "$.mothersName", + "fathersName": "$.fathersName", + "dateOfBirth": "$.dateOfBirth", + "aadhaarNo": "$.aadhaarNo", + "gender": "$.gender", + "address": "$.address", + "state":"$.state", + "district": "$.district", + "country": "$.country", + "pincode": "$.pincode", + "candidatePic": "$.candidatePic", + "courseName": "$.courseName", + "nursingCollage": "$.nursingCollage", + "joiningMonth": "$.joiningMonth", + "joiningYear": "$.joiningYear", + "passingMonth": "$.passingMonth", + "passingYear": "$.passingYear", + "finalYearRollNo": "$.finalYearRollNo", + "examBody": "$.examBody", + "paymentStatus": "$.paymentStatus" + }, + "credentialTemplate": { + "@context": [ + "https://www.w3.org/2018/credentials/v1", + { + "@version": 1.1, + "@protected": true, + "SkillCertificate": { + "@id": "https://github.com/sunbird-specs/vc-specs#SkillCertificate", + "@context": { + "id": "@id", + "@version": 1.1, + "@protected": true, + "skills": "schema:Text" + } + }, + "Person": { + "@id": "https://github.com/sunbird-specs/vc-specs#Person", + "@context": { + "name": "schema:Text" + } + }, + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@context": { + "name": "schema:Text" + }}, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + }}, + "council": { + "@id": "https://github.com/sunbird-specs/vc-specs#council", + "@context": { + "name": "schema:Text" + }}, + "mothersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", + "@context": { + "name": "schema:Text" + }}, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + }}, + "dateOfBirth": { + "@id": "https://github.com/sunbird-specs/vc-specs#dateOfBirth", + "@context": { + "name": "schema:Text" + }}, + "aadhaarNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#aadhaarNo", + "@context": { + "name": "schema:Text" + }}, + "gender": { + "@id": "https://github.com/sunbird-specs/vc-specs#gender", + "@context": { + "name": "schema:Text" + } + }, + "address": { + "@id": "https://github.com/sunbird-specs/vc-specs#address", + "@context": { + "name": "schema:Text" + } + }, + "state": { + "@id": "https://github.com/sunbird-specs/vc-specs#state", + "@context": { + "name": "schema:Text" + } + }, + "district": { + "@id": "https://github.com/sunbird-specs/vc-specs#district", + "@context": { + "name": "schema:Text" + } + }, + "country": { + "@id": "https://github.com/sunbird-specs/vc-specs#country", + "@context": { + "name": "schema:Text" + } + }, + "pincode": { + "@id": "https://github.com/sunbird-specs/vc-specs#pincode", + "@context": { + "name": "schema:Text" + } + }, + "candidatePic": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", + "@context": { + "name": "schema:Text" + } + }, + "nursingCollage": { + "@id": "https://github.com/sunbird-specs/vc-specs#nursingCollage", + "@context": { + "name": "schema:Text" + } + }, + "courseName": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseName", + "@context": { + "name": "schema:Text" + } + }, + "joiningMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningMonth", + "@context": { + "name": "schema:Text" + } + }, + "joiningYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningYear", + "@context": { + "name": "schema:Text" + } + }, + "passingMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingMonth", + "@context": { + "name": "schema:Text" + } + }, + "passingYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingYear", + "@context": { + "name": "schema:Text" + } + }, + "finalYearRollNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#finalYearRollNo", + "@context": { + "name": "schema:Text" + } + }, + "examBody": { + "@id": "https://github.com/sunbird-specs/vc-specs#examBody", + "@context": { + "name": "schema:Text" + } + }, + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "@context": { + "name": "schema:Text" + } + }, + "feeReciptNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#feeReciptNo", + "@context": { + "name": "schema:Text" + } + } + } + ], + "type": ["VerifiableCredential"], + "issuanceDate": "2021-08-27T10:57:57.237Z", + "credentialSubject": { + "type": "Person", + "name": "{{name}}", + "council": "{{council}}", + "email": "{{email}}", + "phoneNumber": "{{phoneNumber}}", + "mothersName": "{{mothersName}}", + "fathersName": "{{fathersName}}", + "dateOfBirth": "{{dateOfBirth}}", + "aadhaarNo": "{{aadhaarNo}}", + "gender": "{{gender}}", + "address": "{{address}}", + "state":"{{state}}", + "district": "{{district}}", + "country": "{{country}}", + "pincode": "{{pincode}}", + "candidatePic": "{{candidatePic}}", + "courseName": "{{courseName}}", + "nursingCollage": "{{nursingCollage}}", + "joiningMonth": "{{joiningMonth}}", + "joiningYear": "{{joiningYear}}", + "passingMonth": "{{passingMonth}}", + "passingYear": "{{passingYear}}", + "finalYearRollNo": "{{finalYearRollNo}}", + "feeReciptNo": "{{feeReciptNo}}", + "examBody": "{{examBody}}", + "paymentStatus": "{{paymentStatus}}" + }, + "issuer": "did:web:sunbirdrc.dev/vc/skill" + } + } + ], + "certificateTemplates": { + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html", + "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html", + "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" + } + } +} diff --git a/java/registry/src/main/resources/public/_schemas/Student.json b/java/registry/src/main/resources/public/_schemas/Student.json index f092c16e3..190fc06e5 100644 --- a/java/registry/src/main/resources/public/_schemas/Student.json +++ b/java/registry/src/main/resources/public/_schemas/Student.json @@ -19,7 +19,60 @@ "mothersName": {"type": "string", "title": "motherName"}, "fathersName": { "type": "string","title": "fatherName"}, "dateOfBirth": {"type": "string", "title": "dateOfBirth"}, - "aadhaarNo": {"type": "string", "title": "aadhaarNo"} + "aadhaarNo": {"type": "string", "title": "aadhaarNo"}, + "gender": {"type": "string", "title": "gender", "enum": ["male", "female"]}, + "address": {"type": "string", "title": "address"}, + "state": { "type": "string", "title": "State","enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] }, + "district": {"type": "string", "title": "district"}, + "country": {"type": "string", "title": "country"}, + "pincode": {"type": "string", "title": "pincode"}, + "candidatePic": {"type": "string", "title": "candidatePic"}, + "courseName": {"type": "string","title": "courseName"}, + "nursingCollage": {"type": "string", "title": "nursingCollage"}, + "joiningMonth": {"type": "string","title": "joiningMonth"}, + "joiningYear": {"type": "string", "title": "joiningYear"}, + "passingMonth": {"type": "string", "title": "passingMonth"}, + "passingYear": {"type": "string","title": "passingYear"}, + "examBody":{"type": "string","title": "examBody"}, + "paymentStatus":{"type": "string","title": "paymentStatus"} } } }, @@ -48,7 +101,23 @@ "mothersName": "$.mothersName", "fathersName": "$.fathersName", "dateOfBirth": "$.dateOfBirth", - "aadhaarNo": "$.aadhaarNo" + "aadhaarNo": "$.aadhaarNo", + "gender": "$.gender", + "address": "$.address", + "state":"$.state", + "district": "$.district", + "country": "$.country", + "pincode": "$.pincode", + "candidatePic": "$.candidatePic", + "courseName": "$.courseName", + "nursingCollage": "$.nursingCollage", + "joiningMonth": "$.joiningMonth", + "joiningYear": "$.joiningYear", + "passingMonth": "$.passingMonth", + "passingYear": "$.passingYear", + "finalYearRollNo": "$.finalYearRollNo", + "examBody": "$.examBody", + "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { "@context": [ @@ -71,6 +140,16 @@ "name": "schema:Text" } }, + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@context": { + "name": "schema:Text" + }}, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + }}, "council": { "@id": "https://github.com/sunbird-specs/vc-specs#council", "@context": { @@ -82,31 +161,122 @@ "name": "schema:Text" }}, "fathersName": { - "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", - "@context": { - "name": "schema:Text" - }}, + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + }}, "dateOfBirth": { - "@id": "https://github.com/sunbird-specs/vc-specs#dateOfBirth", - "@context": { - "name": "schema:Text" - }}, + "@id": "https://github.com/sunbird-specs/vc-specs#dateOfBirth", + "@context": { + "name": "schema:Text" + }}, "aadhaarNo": { - "@id": "https://github.com/sunbird-specs/vc-specs#aadhaarNo", - "@context": { - "name": "schema:Text" - }}, - "phoneNumber": { - "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@id": "https://github.com/sunbird-specs/vc-specs#aadhaarNo", "@context": { "name": "schema:Text" }}, - "email": { - "@id": "https://github.com/sunbird-specs/vc-specs#email", + "gender": { + "@id": "https://github.com/sunbird-specs/vc-specs#gender", "@context": { "name": "schema:Text" - }} - + } + }, + "address": { + "@id": "https://github.com/sunbird-specs/vc-specs#address", + "@context": { + "name": "schema:Text" + } + }, + "state": { + "@id": "https://github.com/sunbird-specs/vc-specs#state", + "@context": { + "name": "schema:Text" + } + }, + "district": { + "@id": "https://github.com/sunbird-specs/vc-specs#district", + "@context": { + "name": "schema:Text" + } + }, + "country": { + "@id": "https://github.com/sunbird-specs/vc-specs#country", + "@context": { + "name": "schema:Text" + } + }, + "pincode": { + "@id": "https://github.com/sunbird-specs/vc-specs#pincode", + "@context": { + "name": "schema:Text" + } + }, + "candidatePic": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", + "@context": { + "name": "schema:Text" + } + }, + "nursingCollage": { + "@id": "https://github.com/sunbird-specs/vc-specs#nursingCollage", + "@context": { + "name": "schema:Text" + } + }, + "courseName": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseName", + "@context": { + "name": "schema:Text" + } + }, + "joiningMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningMonth", + "@context": { + "name": "schema:Text" + } + }, + "joiningYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningYear", + "@context": { + "name": "schema:Text" + } + }, + "passingMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingMonth", + "@context": { + "name": "schema:Text" + } + }, + "passingYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingYear", + "@context": { + "name": "schema:Text" + } + }, + "finalYearRollNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#finalYearRollNo", + "@context": { + "name": "schema:Text" + } + }, + "examBody": { + "@id": "https://github.com/sunbird-specs/vc-specs#examBody", + "@context": { + "name": "schema:Text" + } + }, + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "@context": { + "name": "schema:Text" + } + }, + "feeReciptNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#feeReciptNo", + "@context": { + "name": "schema:Text" + } + } } ], "type": ["VerifiableCredential"], @@ -114,13 +284,30 @@ "credentialSubject": { "type": "Person", "name": "{{name}}", + "council": "{{council}}", + "email": "{{email}}", + "phoneNumber": "{{phoneNumber}}", "mothersName": "{{mothersName}}", "fathersName": "{{fathersName}}", "dateOfBirth": "{{dateOfBirth}}", "aadhaarNo": "{{aadhaarNo}}", - "council": "{{council}}", - "email": "{{email}}", - "phoneNumber": "{{phoneNumber}}" + "gender": "{{gender}}", + "address": "{{address}}", + "state":"{{state}}", + "district": "{{district}}", + "country": "{{country}}", + "pincode": "{{pincode}}", + "candidatePic": "{{candidatePic}}", + "courseName": "{{courseName}}", + "nursingCollage": "{{nursingCollage}}", + "joiningMonth": "{{joiningMonth}}", + "joiningYear": "{{joiningYear}}", + "passingMonth": "{{passingMonth}}", + "passingYear": "{{passingYear}}", + "finalYearRollNo": "{{finalYearRollNo}}", + "feeReciptNo": "{{feeReciptNo}}", + "examBody": "{{examBody}}", + "paymentStatus": "{{paymentStatus}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index d5735ed5e..312134dd9 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -1,11 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema", "type": "object", - "properties": { - "StudentFromUP": { - "$ref": "#/definitions/StudentFromUP" - } - }, + "properties": { "StudentFromUP": { "$ref": "#/definitions/StudentFromUP" } }, "required": ["StudentFromUP"], "title": "StudentFromUP", "definitions": { @@ -14,138 +10,74 @@ "type": "object", "title": "StudentFromUP", "required": ["name", "phoneNumber", "email", "council"], - "uniqueIndexFields": [ - "phoneNumber" - ], - "properties": {"name": {"type": "string"}, - "phoneNumber": {"type": "string"}, - "email": {"type": "string"}, - "council": {"type": "string"}, + "uniqueIndexFields": ["phoneNumber"], + "properties": { + "name": { "type": "string" }, + "phoneNumber": { "type": "string" }, + "email": { "type": "string" }, + "council": { "type": "string" }, "mothersName": {"type": "string", "title": "motherName"}, "fathersName": { "type": "string","title": "fatherName"}, "dateOfBirth": {"type": "string", "title": "dateOfBirth"}, "aadhaarNo": {"type": "string", "title": "aadhaarNo"}, - "barCode": { - "type": "string", - "title": "barCode" - }, - "gender": { - "type": "string", - "title": "gender", - "enum": ["male", "female"] - }, - "address": { - "type": "string"}, - "state": { - "type": "string", - "title": "State", - "enum": [ - "Andaman and Nicobar Islands", - "Andhra Pradesh", - "Arunachal Pradesh", - "Assam", - "Bihar", - "Chandigarh", - "Chhattisgarh", - "Dadra and Nagar Haveli", - "Daman and Diu", - "Delhi", - "Goa", - "Gujarat", - "Haryana", - "Himachal Pradesh", - "Jammu and Kashmir", - "Jharkhand", - "Karnataka", - "Kerala", - "Ladakh", - "Lakshadweep", - "Madhya Pradesh", - "Maharashtra", - "Manipur", - "Meghalaya", - "Mizoram", - "Nagaland", - "Odisha", - "Puducherry", - "Punjab", - "Rajasthan", - "Sikkim", - "Tamil Nadu", - "Telangana", - "Tripura", - "Uttar Pradesh", - "Uttarakhand", - "West Bengal" - ] - }, - "district": { - "type": "string", - "title": "district" - }, - "country": { - "type": "string", - "title": "country" - }, - "pincode": { - "type": "string", - "title": "pincode" - }, - "candidatePic": { - "type": "string", - "title": "candidatePic" - }, - "doc-proof": { - "type": "string", - "items": { - "type": "string" - }, - "title": "All Document Proof" - }, - "courseName": { - "type": "string", - "title": "courseName" - }, - "nursingCollage": { - "type": "string", - "title": "nursingCollage" - }, - "joiningMonth": { - "type": "string", - "title": "joiningMonth" - }, - "joiningYear": { - "type": "string", - "title": "joiningYear" - }, - "passingMonth": { - "type": "string", - "title": "passingMonth" - }, - "passingYear": { - "type": "string", - "title": "passingYear" - }, - "finalYearRollNo": { - "type": "string", - "title": "finalYearRollNo" - }, - "feeReciptNo": { - "type": "string", - "title": "feeReciptNo" - }, - "examBody": { - "type": "string", - "title": "examBody" - }, - "paymentStatus": { - "type": "string", - "title": "paymentStatus" - } + "gender": {"type": "string", "title": "gender", "enum": ["male", "female"]}, + "address": {"type": "string", "title": "address"}, + "state": { "type": "string", "title": "State","enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] }, + "district": {"type": "string", "title": "district"}, + "country": {"type": "string", "title": "country"}, + "pincode": {"type": "string", "title": "pincode"}, + "candidatePic": {"type": "string", "title": "candidatePic"}, + "courseName": {"type": "string","title": "courseName"}, + "nursingCollage": {"type": "string", "title": "nursingCollage"}, + "joiningMonth": {"type": "string","title": "joiningMonth"}, + "joiningYear": {"type": "string", "title": "joiningYear"}, + "passingMonth": {"type": "string", "title": "passingMonth"}, + "passingYear": {"type": "string","title": "passingYear"}, + "examBody":{"type": "string","title": "examBody"}, + "paymentStatus":{"type": "string","title": "paymentStatus"} } } }, "_osConfig": { + "ownershipAttributes": [ { "email": "/email", @@ -154,37 +86,38 @@ } ], "inviteRoles": ["anonymous"], - "roles": ["StudentFromUP"], - + "roles": ["Regulator"], "attestationPolicies": [ { - "name": "studentUPVerification", + "name": "studentVerification", "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", "type": "MANUAL", "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", "attestationProperties": { "name": "$.name", + "email": "$.email", + "phoneNumber": "$.phoneNumber", + "council": "$.council", "mothersName": "$.mothersName", "fathersName": "$.fathersName", - "council": "$.council", + "dateOfBirth": "$.dateOfBirth", + "aadhaarNo": "$.aadhaarNo", + "gender": "$.gender", + "address": "$.address", + "state":"$.state", + "district": "$.district", + "country": "$.country", + "pincode": "$.pincode", + "candidatePic": "$.candidatePic", "courseName": "$.courseName", + "nursingCollage": "$.nursingCollage", "joiningMonth": "$.joiningMonth", - "joiningYear": "$.joiningYear", - "passingMonth": "$.passingMonth", + "joiningYear": "$.joiningYear", + "passingMonth": "$.passingMonth", "passingYear": "$.passingYear", - "examBody": "$.examBody", "finalYearRollNo": "$.finalYearRollNo", - "date": "$.date", - "barCode": "$.barCode", - "doc-proof": "$.doc-proof", - "candidatePic": "$.candidatePic", - "paymentStatus": "$.paymentStatus", - "feeReciptNo": "$.feeReciptNo", - "address": "$.address", - "state": "$.state", - "district": "$.district", - "country": "$.country", - "pincode": "$.pincode" + "examBody": "$.examBody", + "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { "@context": [ @@ -207,14 +140,43 @@ "name": "schema:Text" } }, + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@context": { + "name": "schema:Text" + }}, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + }}, + "council": { + "@id": "https://github.com/sunbird-specs/vc-specs#council", + "@context": { + "name": "schema:Text" + }}, "mothersName": { "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", "@context": { "name": "schema:Text" - } - }, + }}, "fathersName": { "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + }}, + "dateOfBirth": { + "@id": "https://github.com/sunbird-specs/vc-specs#dateOfBirth", + "@context": { + "name": "schema:Text" + }}, + "aadhaarNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#aadhaarNo", + "@context": { + "name": "schema:Text" + }}, + "gender": { + "@id": "https://github.com/sunbird-specs/vc-specs#gender", "@context": { "name": "schema:Text" } @@ -249,14 +211,20 @@ "name": "schema:Text" } }, - "courseName": { - "@id": "https://github.com/sunbird-specs/vc-specs#courseName", + "candidatePic": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", "@context": { "name": "schema:Text" } }, - "council": { - "@id": "https://github.com/sunbird-specs/vc-specs#council", + "nursingCollage": { + "@id": "https://github.com/sunbird-specs/vc-specs#nursingCollage", + "@context": { + "name": "schema:Text" + } + }, + "courseName": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseName", "@context": { "name": "schema:Text" } @@ -285,32 +253,14 @@ "name": "schema:Text" } }, - "examBody": { - "@id": "https://github.com/sunbird-specs/vc-specs#examBody", - "@context": { - "name": "schema:Text" - } - }, "finalYearRollNo": { "@id": "https://github.com/sunbird-specs/vc-specs#finalYearRollNo", "@context": { "name": "schema:Text" } }, - "date": { - "@id": "https://github.com/sunbird-specs/vc-specs#date", - "@context": { - "name": "schema:Text" - } - }, - "candidatePic": { - "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", - "@context": { - "name": "schema:Text" - } - }, - "doc-proof": { - "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "examBody": { + "@id": "https://github.com/sunbird-specs/vc-specs#examBody", "@context": { "name": "schema:Text" } @@ -327,7 +277,6 @@ "name": "schema:Text" } } - } ], "type": ["VerifiableCredential"], @@ -335,24 +284,30 @@ "credentialSubject": { "type": "Person", "name": "{{name}}", + "council": "{{council}}", + "email": "{{email}}", + "phoneNumber": "{{phoneNumber}}", "mothersName": "{{mothersName}}", "fathersName": "{{fathersName}}", + "dateOfBirth": "{{dateOfBirth}}", + "aadhaarNo": "{{aadhaarNo}}", + "gender": "{{gender}}", + "address": "{{address}}", + "state":"{{state}}", + "district": "{{district}}", + "country": "{{country}}", + "pincode": "{{pincode}}", + "candidatePic": "{{candidatePic}}", "courseName": "{{courseName}}", + "nursingCollage": "{{nursingCollage}}", "joiningMonth": "{{joiningMonth}}", - "joiningYear": "{{joiningYear}}", - "passingMonth": "{{passingMonth}}", + "joiningYear": "{{joiningYear}}", + "passingMonth": "{{passingMonth}}", "passingYear": "{{passingYear}}", - "examBody": "{{examBody}}", "finalYearRollNo": "{{finalYearRollNo}}", - "date": "{{date}}", - "candidatePic": "{{candidatePic}}", "feeReciptNo": "{{feeReciptNo}}", - "council": "{{council}}", - "address": "{{address}}", - "district": "{{district}}", - "country": "{{country}}", - "state": "{{state}}", - "pincode": "{{pincode}}" + "examBody": "{{examBody}}", + "paymentStatus": "{{paymentStatus}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } @@ -386,7 +341,7 @@ "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" } + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" + } } } - From 1e56ca87e0999cf15205f16c54fef73aa20572a7 Mon Sep 17 00:00:00 2001 From: rkrahu Date: Wed, 16 Aug 2023 12:49:57 +0530 Subject: [PATCH 18/43] mail integration upto pending item --- .../claim/config/PropertyMapper.java | 4 ++++ .../claim/dto/CertificateMailDto.java | 21 +++++++++++++++++++ .../sunbirdrc/claim/dto/PendingMailDTO.java | 4 ++++ .../claim/exception/ClaimMailException.java | 7 +++++++ .../resources/templates/credentials-mail.ftl | 12 +++++++++++ .../resources/templates/pending-item-mail.ftl | 12 +++++++++++ .../registry/model/dto/PendingMailDTO.java | 15 +++++++++++++ 7 files changed, 75 insertions(+) create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/dto/CertificateMailDto.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/exception/ClaimMailException.java create mode 100644 java/claim/src/main/resources/templates/credentials-mail.ftl create mode 100644 java/claim/src/main/resources/templates/pending-item-mail.ftl create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/PendingMailDTO.java diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java new file mode 100644 index 000000000..e0e537548 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java @@ -0,0 +1,4 @@ +package dev.sunbirdrc.claim.config; + +public class PropertyMapper { +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/CertificateMailDto.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/CertificateMailDto.java new file mode 100644 index 000000000..da666cd9d --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/CertificateMailDto.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.claim.dto; + + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class CertificateMailDto { + private String name; + private String certificate; + private String emailAddress; + + private String credentialsType; + + private String certificateBase64; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java new file mode 100644 index 000000000..90147742f --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java @@ -0,0 +1,4 @@ +package dev.sunbirdrc.claim.dto; + +public class PendingMailDTO { +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/exception/ClaimMailException.java b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/ClaimMailException.java new file mode 100644 index 000000000..2e3377d87 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/exception/ClaimMailException.java @@ -0,0 +1,7 @@ +package dev.sunbirdrc.claim.exception; + +public class ClaimMailException extends RuntimeException { + public ClaimMailException(String message) { + super(message); + } +} diff --git a/java/claim/src/main/resources/templates/credentials-mail.ftl b/java/claim/src/main/resources/templates/credentials-mail.ftl new file mode 100644 index 000000000..98d67435c --- /dev/null +++ b/java/claim/src/main/resources/templates/credentials-mail.ftl @@ -0,0 +1,12 @@ + + +

Hi ${name}

+ +

"We are pleased to inform you that a ${credType} has been issued to you. You can view and download the credential by using the following link.

+ +
${idLink}
+ +

Thank you,

+

< Registration Credential Issuing Authority >

+ + diff --git a/java/claim/src/main/resources/templates/pending-item-mail.ftl b/java/claim/src/main/resources/templates/pending-item-mail.ftl new file mode 100644 index 000000000..98d67435c --- /dev/null +++ b/java/claim/src/main/resources/templates/pending-item-mail.ftl @@ -0,0 +1,12 @@ + + +

Hi ${name}

+ +

"We are pleased to inform you that a ${credType} has been issued to you. You can view and download the credential by using the following link.

+ +
${idLink}
+ +

Thank you,

+

< Registration Credential Issuing Authority >

+ + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/PendingMailDTO.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/PendingMailDTO.java new file mode 100644 index 000000000..349f9143e --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/PendingMailDTO.java @@ -0,0 +1,15 @@ +package dev.sunbirdrc.registry.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class PendingMailDTO { + private String name; + private String emailAddress; + private String council; + private String itemName; +} From 21e8169ee54451bf73c7360fbffc08374eab4559 Mon Sep 17 00:00:00 2001 From: rkrahu Date: Wed, 16 Aug 2023 12:51:20 +0530 Subject: [PATCH 19/43] Mail integration up-to pending Item --- java/claim/pom.xml | 4 + .../claim/config/PropertyMapper.java | 11 ++ .../claim/controller/EmailController.java | 14 ++ .../sunbirdrc/claim/dto/PendingMailDTO.java | 11 ++ .../sunbirdrc/claim/service/EmailService.java | 125 ++++++++++++++++++ .../src/main/resources/application.properties | 16 ++- .../resources/templates/pending-item-mail.ftl | 4 +- .../controller/RegistryEntityController.java | 31 +++++ .../registry/util/ClaimRequestClient.java | 10 +- 9 files changed, 217 insertions(+), 9 deletions(-) diff --git a/java/claim/pom.xml b/java/claim/pom.xml index bb17d8bdc..39b13a0c3 100644 --- a/java/claim/pom.xml +++ b/java/claim/pom.xml @@ -154,6 +154,10 @@ json 20210307 + + org.freemarker + freemarker + diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java index e0e537548..b5302aa38 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java @@ -1,4 +1,15 @@ package dev.sunbirdrc.claim.config; +import lombok.Data; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +@Data public class PropertyMapper { + @Value("${simple.mail.message.from}") + private String simpleMailMessageFrom; + + @Value("${foreign.pending.item.subject}") + private String foreignPendingItemSubject; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java index 4016b1b7d..da3f0d72d 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java @@ -1,7 +1,9 @@ package dev.sunbirdrc.claim.controller; import dev.sunbirdrc.claim.dto.BarCode; +import dev.sunbirdrc.claim.dto.CertificateMailDto; import dev.sunbirdrc.claim.dto.MailDto; +import dev.sunbirdrc.claim.dto.PendingMailDTO; import dev.sunbirdrc.claim.service.EmailService; import net.sourceforge.barbecue.Barcode; import net.sourceforge.barbecue.BarcodeFactory; @@ -111,5 +113,17 @@ private String prepareBody(String idLink, String name, String credType) { return body; } + @RequestMapping(value = "/api/v1/sendCertificateMail", method = RequestMethod.POST) + public ResponseEntity sendCertificateMail(@RequestBody CertificateMailDto certificateMailDto) { + emailService.sendCertificateMail(certificateMailDto); + return new ResponseEntity<>("Mail is sending", HttpStatus.OK); + } + + @RequestMapping(value = "/api/v1/sendPendingForeignItemMail", method = RequestMethod.POST) + public ResponseEntity sendPendingItemMail(@RequestHeader HttpHeaders headers, + @RequestBody PendingMailDTO pendingMailDTO) { + emailService.sendPendingMail(pendingMailDTO); + return new ResponseEntity<>("Mail is sending", HttpStatus.OK); + } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java index 90147742f..50c3cf3d0 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java @@ -1,4 +1,15 @@ package dev.sunbirdrc.claim.dto; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor public class PendingMailDTO { + private String name; + private String emailAddress; + private String council; + private String itemName; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java index a40f8dcd3..1777c7096 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java @@ -1,27 +1,56 @@ package dev.sunbirdrc.claim.service; +import dev.sunbirdrc.claim.config.PropertyMapper; +import dev.sunbirdrc.claim.controller.EmailController; +import dev.sunbirdrc.claim.dto.CertificateMailDto; +import dev.sunbirdrc.claim.dto.MailDto; +import dev.sunbirdrc.claim.dto.PendingMailDTO; +import dev.sunbirdrc.claim.exception.ClaimMailException; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; +import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.File; +import java.io.IOException; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; @Service("emailService") public class EmailService { + private static final Logger logger = LoggerFactory.getLogger(EmailController.class); @Autowired private JavaMailSender mailSender; @Autowired private SimpleMailMessage preConfiguredMessage; + + @Autowired + private Configuration freeMarkerConfiguration; + + @Value("${simple.mail.message.from}") + private String simpleMailMessageFrom; + + @Autowired + private PropertyMapper propertyMapper; /** * This method will send compose and send the message @@ -99,4 +128,100 @@ public void prepare(MimeMessage mimeMessage) throws Exception System.err.println(ex.getMessage()); } } + + @Async + public void sendCertificateMail(CertificateMailDto certificateMailDto) { + String subject = certificateMailDto.getCredentialsType(); + + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + + MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + + mimeMessageHelper.setSubject(subject); + mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(), certificateMailDto.getName())); + mimeMessageHelper.setTo(certificateMailDto.getEmailAddress()); + mimeMessageHelper.setText(generateAttachedCertificateMailContent(certificateMailDto), true); + + + byte[] doc = Base64.getDecoder().decode(certificateMailDto.getCertificateBase64()); + mimeMessageHelper.addAttachment("certificate.pdf", new ByteArrayResource(doc)); + + mailSender.send(mimeMessageHelper.getMimeMessage()); + } catch (Exception e) { + logger.error("Exception while sending mail: ", e); + throw new ClaimMailException("Exception while composing and sending mail with OTP"); + } + } + + private String generateAttachedCertificateMailContent(CertificateMailDto certificateMailDto) { + String processedTemplateString = null; + + Map mailMap = new HashMap<>(); + mailMap.put("name", certificateMailDto.getName()); + mailMap.put("credType", certificateMailDto.getCredentialsType()); + mailMap.put("idLink", certificateMailDto.getCertificate()); + + try { + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("credentials-mail.ftl"); + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + + } catch (TemplateException e) { + logger.error("TemplateException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } catch (IOException e) { + logger.error("IOException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } + return processedTemplateString; + } + + @Async + public void sendPendingMail(PendingMailDTO pendingMailDTO) { + + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + + MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + + mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); + mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(),pendingMailDTO.getName())); + mimeMessageHelper.setTo(pendingMailDTO.getEmailAddress()); + mimeMessageHelper.setText(generateCertificateMailContent(pendingMailDTO), true); + + mailSender.send(mimeMessageHelper.getMimeMessage()); + } catch (Exception e) { + logger.error("Exception while sending mail: ", e); + throw new ClaimMailException("Exception while composing and sending mail with OTP"); + } + + } + + /** + * @param mailDto + * @return + */ + private String generateCertificateMailContent(PendingMailDTO pendingMailDTO) { + String processedTemplateString = null; + + Map mailMap = new HashMap<>(); + mailMap.put("name", pendingMailDTO.getName()); + mailMap.put("council", pendingMailDTO.getCouncil()); + mailMap.put("itemName", pendingMailDTO.getItemName()); + + try { + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("pending-item-mail.ftl"); + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + + } catch (TemplateException e) { + logger.error("TemplateException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } catch (IOException e) { + logger.error("IOException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } + return processedTemplateString; + } } diff --git a/java/claim/src/main/resources/application.properties b/java/claim/src/main/resources/application.properties index cada3cd1e..d60a5fb9d 100644 --- a/java/claim/src/main/resources/application.properties +++ b/java/claim/src/main/resources/application.properties @@ -1,6 +1,6 @@ server.port=8082 -spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry} +spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry5} spring.datasource.username=${connectionInfo_username:postgres} spring.datasource.password=${connectionInfo_password:postgres} @@ -9,11 +9,11 @@ spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true sunbirdrc.url=${sunbirdrc_url:http://localhost:8081} -spring.mail.host=smtp.sendgrid.net -spring.mail.port=587 -spring.mail.username=apikey - -spring.mail.password= +spring.mail.host=smtp.gmail.com +spring.mail.port=465 +spring.mail.username=upsmf.otp@upsmfac.org +spring.mail.password=OTP22023## +spring.mail.properties.mail.smtp.ssl.enable = true # Other properties @@ -42,4 +42,8 @@ gcp.file.validity=2 spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB +# Mail config +simple.mail.message.from = r.kishor.rahu@gmail.com +foreign.pending.item.subject = Pending Item + diff --git a/java/claim/src/main/resources/templates/pending-item-mail.ftl b/java/claim/src/main/resources/templates/pending-item-mail.ftl index 98d67435c..876281666 100644 --- a/java/claim/src/main/resources/templates/pending-item-mail.ftl +++ b/java/claim/src/main/resources/templates/pending-item-mail.ftl @@ -2,9 +2,9 @@

Hi ${name}

-

"We are pleased to inform you that a ${credType} has been issued to you. You can view and download the credential by using the following link.

+

We have pending item for ${council}, which have been requested

-
${idLink}
+
Item name:

${itemName}

Thank you,

< Registration Credential Issuing Authority >

diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 827152ba3..e92abd721 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -23,11 +23,13 @@ import dev.sunbirdrc.registry.middleware.util.Constants; import dev.sunbirdrc.registry.middleware.util.JSONUtil; import dev.sunbirdrc.registry.middleware.util.OSSystemFields; +import dev.sunbirdrc.registry.model.dto.PendingMailDTO; import dev.sunbirdrc.registry.service.FileStorageService; import dev.sunbirdrc.registry.service.impl.CertificateServiceImpl; import dev.sunbirdrc.registry.transform.Configuration; import dev.sunbirdrc.registry.transform.Data; import dev.sunbirdrc.registry.transform.ITransformer; +import dev.sunbirdrc.registry.util.ClaimRequestClient; import org.agrona.Strings; import dev.sunbirdrc.registry.util.DigiLockerUtils; import dev.sunbirdrc.registry.util.DocDetails; @@ -84,6 +86,9 @@ public class RegistryEntityController extends AbstractController { @Value("${certificate.enableExternalTemplates:false}") boolean externalTemplatesEnabled; + @Autowired + private ClaimRequestClient claimRequestClient; + @RequestMapping(value = "/api/v1/{entityName}/invite", method = RequestMethod.POST) public ResponseEntity invite( @PathVariable String entityName, @@ -1207,4 +1212,30 @@ public ResponseEntity putSingleEntityFile( } } + @RequestMapping(value = "/api/v1/{entityName}/sendPendingForeignItemMail", method = RequestMethod.POST) + public ResponseEntity sendPendingForeignItemMail(@PathVariable String entityName, + @RequestBody PendingMailDTO pendingMailDTO, + HttpServletRequest request) { + + ResponseParams responseParams = new ResponseParams(); + Response response = new Response(Response.API_ID.SEND, "OK", responseParams); + + try { + registryHelper.authorizeInviteEntity(request, entityName); + + String mailStatus = claimRequestClient.sendPendingForeignItemMail(pendingMailDTO); + + response.setResult(mailStatus); + responseParams.setStatus(Response.Status.SUCCESSFUL); + + } catch (Exception exception) { + logger.error("Exception : {}", exception.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(exception.getMessage()); + return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); + } + + return new ResponseEntity<>(response, HttpStatus.OK); + } + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index 6d824bcad..bd2c088c1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -9,6 +9,7 @@ import dev.sunbirdrc.registry.model.dto.BarCode; import dev.sunbirdrc.registry.model.dto.FileDto; import dev.sunbirdrc.registry.model.dto.MailDto; +import dev.sunbirdrc.registry.model.dto.PendingMailDTO; import lombok.NonNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -47,6 +48,8 @@ public class ClaimRequestClient { private static final String CLAIM_MULTI_FILE_UPLOAD = "/api/v1/files/upload/multiple"; private static String URL_APPENDER = "/"; + private static final String MAIL_SEND_PENDING_FOREIGN_ITEM_URL = "/api/v1/sendPendingForeignItemMail"; + ClaimRequestClient(@Value("${claims.url}") String claimRequestUrl, RestTemplate restTemplate) { this.claimRequestUrl = claimRequestUrl; this.restTemplate = restTemplate; @@ -206,7 +209,12 @@ public List uploadCLaimMultipleFiles(@NonNull MultipartFile[] files, St return fileDtoList; } - + public String sendPendingForeignItemMail(PendingMailDTO pendingMailDTO) { + String mailStatus = restTemplate.postForObject( + claimRequestUrl + MAIL_SEND_PENDING_FOREIGN_ITEM_URL, pendingMailDTO, String.class); + logger.info("Pending foreign item mail status: " + mailStatus); + return mailStatus; + } From 3f240856e58c94dd4e02595a6c78db4aa6b104d0 Mon Sep 17 00:00:00 2001 From: rkrahu Date: Wed, 16 Aug 2023 17:49:30 +0530 Subject: [PATCH 20/43] Added new feature to persist user credential through API --- java/pom.xml | 1 + java/user-management/.gitignore | 38 + java/user-management/pom.xml | 103 +++ .../sunbirdrc/UserManagementApplication.java | 22 + .../config/ExceptionHandlerConfig.java | 82 ++ .../dev/sunbirdrc/config/KeycloakConfig.java | 54 ++ .../config/PropertiesValueMapper.java | 54 ++ .../dev/sunbirdrc/config/RedisConfig.java | 62 ++ .../sunbirdrc/config/WebSecurityConfig.java | 61 ++ .../sunbirdrc/controller/UserController.java | 155 ++++ .../main/java/dev/sunbirdrc/dto/AdminDTO.java | 17 + .../java/dev/sunbirdrc/dto/AdminLoginDTO.java | 21 + .../dto/BulkCustomUserResponseDTO.java | 17 + .../java/dev/sunbirdrc/dto/BulkUserDTO.java | 16 + .../java/dev/sunbirdrc/dto/CustomUserDTO.java | 33 + .../sunbirdrc/dto/CustomUserDeleteDTO.java | 17 + .../dev/sunbirdrc/dto/CustomUserLoginDTO.java | 21 + .../sunbirdrc/dto/CustomUserResponseDTO.java | 17 + .../sunbirdrc/dto/CustomUserUpdateDTO.java | 26 + .../dev/sunbirdrc/dto/CustomUsernameDTO.java | 18 + .../dev/sunbirdrc/dto/UserDetailsDTO.java | 44 ++ .../java/dev/sunbirdrc/dto/UserLoginDTO.java | 21 + .../java/dev/sunbirdrc/dto/UserOtpDTO.java | 25 + .../sunbirdrc/dto/UserTokenDetailsDTO.java | 25 + .../dev/sunbirdrc/entity/UserCredential.java | 29 + .../dev/sunbirdrc/entity/UserDetails.java | 40 + .../exception/AuthorizationException.java | 11 + .../exception/CipherEncoderException.java | 11 + .../exception/InvalidInputDataException.java | 11 + .../exception/KeycloakUserException.java | 11 + .../dev/sunbirdrc/exception/OtpException.java | 11 + .../exception/RoleNotFoundException.java | 11 + .../exception/UserConflictException.java | 11 + .../exception/UserCredentialsException.java | 10 + .../exception/UserNotFoundException.java | 12 + .../repository/UserCredentialRepository.java | 13 + .../repository/UserDetailsRepository.java | 9 + .../dev/sunbirdrc/service/MailService.java | 145 ++++ .../dev/sunbirdrc/service/UserService.java | 741 ++++++++++++++++++ .../dev/sunbirdrc/utils/CipherEncoder.java | 97 +++ .../java/dev/sunbirdrc/utils/OtpUtil.java | 80 ++ .../java/dev/sunbirdrc/utils/RedisUtil.java | 36 + .../dev/sunbirdrc/utils/UserConstant.java | 17 + .../src/main/resources/application.properties | 76 ++ .../templates/otp-verification-mail.ftl | 16 + .../user-creation-notification-mail.ftl | 13 + 46 files changed, 2361 insertions(+) create mode 100644 java/user-management/.gitignore create mode 100644 java/user-management/pom.xml create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/UserManagementApplication.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/config/ExceptionHandlerConfig.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/config/KeycloakConfig.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/config/PropertiesValueMapper.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/config/RedisConfig.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/config/WebSecurityConfig.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/controller/UserController.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/AdminDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/AdminLoginDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/BulkCustomUserResponseDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/BulkUserDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserDeleteDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserLoginDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserResponseDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserUpdateDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUsernameDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/UserDetailsDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/UserLoginDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/UserOtpDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/dto/UserTokenDetailsDTO.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/entity/UserCredential.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/entity/UserDetails.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/AuthorizationException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/CipherEncoderException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/InvalidInputDataException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/KeycloakUserException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/OtpException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/RoleNotFoundException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/UserConflictException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/UserCredentialsException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/exception/UserNotFoundException.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/repository/UserCredentialRepository.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/repository/UserDetailsRepository.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/service/MailService.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/service/UserService.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/utils/CipherEncoder.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/utils/OtpUtil.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/utils/RedisUtil.java create mode 100644 java/user-management/src/main/java/dev/sunbirdrc/utils/UserConstant.java create mode 100644 java/user-management/src/main/resources/application.properties create mode 100644 java/user-management/src/main/resources/templates/otp-verification-mail.ftl create mode 100644 java/user-management/src/main/resources/templates/user-creation-notification-mail.ftl diff --git a/java/pom.xml b/java/pom.xml index 73c2c8b5b..10e18168f 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -41,6 +41,7 @@ claim apitest plugins + user-management diff --git a/java/user-management/.gitignore b/java/user-management/.gitignore new file mode 100644 index 000000000..5ff6309b7 --- /dev/null +++ b/java/user-management/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/java/user-management/pom.xml b/java/user-management/pom.xml new file mode 100644 index 000000000..d68a2b948 --- /dev/null +++ b/java/user-management/pom.xml @@ -0,0 +1,103 @@ + + + 4.0.0 + + dev.sunbirdrc + user-management + 1.0-SNAPSHOT + user-management + + + org.springframework.boot + spring-boot-starter-parent + 2.5.0 + + + + + 17 + 17 + UTF-8 + + + + + org.projectlombok + lombok + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.postgresql + postgresql + + + org.springframework.boot + spring-boot-starter-data-redis + + + redis.clients + jedis + + + org.freemarker + freemarker + + + org.springframework.boot + spring-boot-starter-mail + + + org.keycloak + keycloak-admin-client + 11.0.3 + + + org.jboss.resteasy + resteasy-client + 3.1.3.Final + + + org.keycloak + keycloak-spring-security-adapter + 14.0.0 + compile + + + org.keycloak + keycloak-spring-boot-adapter-core + 11.0.2 + compile + + + org.springframework.boot + spring-boot-starter-validation + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/java/user-management/src/main/java/dev/sunbirdrc/UserManagementApplication.java b/java/user-management/src/main/java/dev/sunbirdrc/UserManagementApplication.java new file mode 100644 index 000000000..713d7d050 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/UserManagementApplication.java @@ -0,0 +1,22 @@ +package dev.sunbirdrc; + + +import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.scheduling.annotation.EnableAsync; + + +@EnableAsync +@SpringBootApplication +public class UserManagementApplication { + public static void main(String[] args) { + SpringApplication.run(UserManagementApplication.class, args); + } + +// @Bean +// public KeycloakSpringBootConfigResolver keycloakSpringBootConfigResolver(){ +// return new KeycloakSpringBootConfigResolver(); +// } +} \ No newline at end of file diff --git a/java/user-management/src/main/java/dev/sunbirdrc/config/ExceptionHandlerConfig.java b/java/user-management/src/main/java/dev/sunbirdrc/config/ExceptionHandlerConfig.java new file mode 100644 index 000000000..47f660cb4 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/config/ExceptionHandlerConfig.java @@ -0,0 +1,82 @@ +package dev.sunbirdrc.config; + +import dev.sunbirdrc.exception.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class ExceptionHandlerConfig { + private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlerConfig.class); + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity>> handleValidationErrors(MethodArgumentNotValidException exception) { + + List errors = exception.getBindingResult().getFieldErrors().stream() + .map(FieldError::getDefaultMessage) + .collect(Collectors.toList()); + + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(UserNotFoundException.class) + public ResponseEntity>> handleNotFoundException(UserNotFoundException exception) { + List errors = Collections.singletonList(exception.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(OtpException.class) + public ResponseEntity>> handleNotFoundException(OtpException exception) { + List errors = Collections.singletonList(exception.getLocalizedMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(KeycloakUserException.class) + public ResponseEntity>> handleNotFoundException(KeycloakUserException exception) { + List errors = Collections.singletonList(exception.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(AuthorizationException.class) + public ResponseEntity>> handleNotFoundException(AuthorizationException exception) { + List errors = Collections.singletonList(exception.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(InvalidInputDataException.class) + public ResponseEntity>> handleNotFoundException(InvalidInputDataException exception) { + List errors = Collections.singletonList(exception.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + @ExceptionHandler(RoleNotFoundException.class) + public ResponseEntity>> handleNotFoundException(RoleNotFoundException exception) { + List errors = Collections.singletonList(exception.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(UserConflictException.class) + public ResponseEntity>> handleNotFoundException(UserConflictException exception) { + List errors = Collections.singletonList(exception.getMessage()); + return new ResponseEntity<>(getErrorsMap(errors), new HttpHeaders(), HttpStatus.BAD_REQUEST); + } + + + private Map> getErrorsMap(List errors) { + Map> errorResponse = new HashMap<>(); + errorResponse.put("errors", errors); + return errorResponse; + } + +} \ No newline at end of file diff --git a/java/user-management/src/main/java/dev/sunbirdrc/config/KeycloakConfig.java b/java/user-management/src/main/java/dev/sunbirdrc/config/KeycloakConfig.java new file mode 100644 index 000000000..0067edba1 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/config/KeycloakConfig.java @@ -0,0 +1,54 @@ +package dev.sunbirdrc.config; + +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.keycloak.OAuth2Constants; +import org.keycloak.admin.client.Keycloak; +import org.keycloak.admin.client.KeycloakBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.web.client.RestTemplate; + + +@Configuration +public class KeycloakConfig { + @Autowired + private PropertiesValueMapper valueMapper; + + @Primary + @Bean(name = "systemKeycloak") + public Keycloak systemKeycloak() { + return KeycloakBuilder.builder() + .serverUrl(valueMapper.getKeycloakServerUrl()) + .realm(valueMapper.getRealm()) + .grantType(OAuth2Constants.CLIENT_CREDENTIALS) + .clientId(valueMapper.getConfidentialClientId()) + .clientSecret(valueMapper.getClientSecret()) + .resteasyClient(new ResteasyClientBuilder() + .connectionPoolSize(10) + .build() + ) + .build(); + } + + public Keycloak getUserKeycloak(String username, String password) { + return KeycloakBuilder.builder() + .serverUrl(valueMapper.getKeycloakServerUrl()) + .realm(valueMapper.getRealm()) + .grantType(OAuth2Constants.PASSWORD) + .username(username) + .password(password) + .clientId(valueMapper.getPublicClientId()) + .resteasyClient(new ResteasyClientBuilder() + .connectionPoolSize(10) + .build() + ) + .build(); + } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/config/PropertiesValueMapper.java b/java/user-management/src/main/java/dev/sunbirdrc/config/PropertiesValueMapper.java new file mode 100644 index 000000000..d949bbd3b --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/config/PropertiesValueMapper.java @@ -0,0 +1,54 @@ +package dev.sunbirdrc.config; + +import lombok.Data; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Data +@Component +public class PropertiesValueMapper { + @Value("${keycloak.server.url}") + private String keycloakServerUrl; + @Value("${keycloak.realm}") + private String realm; + @Value("${keycloak.confidential.client.id}") + private String confidentialClientId; + @Value("${keycloak.public.client.id}") + private String publicClientId; + @Value("${keycloak.client.secret}") + private String clientSecret; + @Value("${keycloak.username}") + private String userName; + @Value("${keycloak.password}") + private String password; + @Value("${keycloak.token.url}") + private String keyCloakTokenUrl; + @Value("${otp.mail.verification.subject}") + private String otpMailVerificationSubject; + @Value("${otp.mail.verification.personal.name}") + private String otpMailVerificationPersonalName; + @Value("${otp.mail.verification.from.address}") + private String otpMailVerificationFromAddress; + @Value("${otp.ttl.duration}") + private Long otpTtlDuration; + @Value("${otp.time.unit}") + private String otpTimeUnit; + @Value("${custom.user.login.url}") + private String customUserLoginUrl; + @Value("${bulk.user.size.limit}") + private Integer bulkUserSizeLimit; + @Value("${custom.user.creation.subject}") + private String customUserCreationSubject; + @Value("${custom.user.creation.personal.name}") + private String customUserCreationPersonalName; + @Value("${custom.user.creation.from.address}") + private String customUserCreationFromAddress; + @Value("${custom.redis.host}") + private String customRedisHost; + @Value("${custom.redis.port}") + private Integer customRedisPort; + @Value("${custom.user.credential.secret.key}") + private String customUserCredentialSecretKey; + @Value("${custom.user.cipher.provider.algorithm}") + private String customUserCipherProviderAlgorithm; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/config/RedisConfig.java b/java/user-management/src/main/java/dev/sunbirdrc/config/RedisConfig.java new file mode 100644 index 000000000..c13a83a70 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/config/RedisConfig.java @@ -0,0 +1,62 @@ +package dev.sunbirdrc.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.serializer.GenericToStringSerializer; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +@Configuration +public class RedisConfig { +// @Bean +// public StringRedisTemplate redisTemplate(RedisConnectionFactory factory) { +// ObjectMapper objectMapper = new ObjectMapper(); +// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); +// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); +// +// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); +// jackson2JsonRedisSerializer.setObjectMapper(objectMapper); +// +// StringRedisTemplate template = new StringRedisTemplate(factory); +// template.setValueSerializer(jackson2JsonRedisSerializer); +// template.afterPropertiesSet(); +// +// return template; +// } + +// @Bean +// JedisConnectionFactory jedisConnectionFactory() { +// return new JedisConnectionFactory(); +// } + + @Autowired + private PropertiesValueMapper valueMapper; + + @Bean + JedisConnectionFactory jedisConnectionFactory() { + JedisConnectionFactory factory = new JedisConnectionFactory(); + factory.setHostName(valueMapper.getCustomRedisHost()); + factory.setPort(valueMapper.getCustomRedisPort()); + factory.setUsePool(true); + return factory; + } + + @Bean(name="customRedis") + RedisTemplate< String, String > customRedis() { + final RedisTemplate< String, String > template = new RedisTemplate<>(); + template.setConnectionFactory( jedisConnectionFactory() ); + template.setKeySerializer( new StringRedisSerializer() ); + template.setHashValueSerializer( new GenericToStringSerializer<>( String.class ) ); + template.setValueSerializer( new GenericToStringSerializer<>( String.class ) ); + return template; + } + +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/config/WebSecurityConfig.java b/java/user-management/src/main/java/dev/sunbirdrc/config/WebSecurityConfig.java new file mode 100644 index 000000000..81edd9156 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/config/WebSecurityConfig.java @@ -0,0 +1,61 @@ +package dev.sunbirdrc.config; + +import dev.sunbirdrc.utils.UserConstant; +import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; +import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; + +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + private static final Logger LOG = LoggerFactory.getLogger(WebSecurityConfig.class); + +// @Override +// protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { +// return new NullAuthenticatedSessionStrategy(); +// } + + @Override + protected void configure(HttpSecurity http) throws Exception { +// http.csrf().disable() +// .authorizeRequests() +// .antMatchers("**/**/login").permitAll() +//// .antMatchers("/**/keycloak/**").hasAnyRole(UserConstant.ADMIN_ROLE) +// .anyRequest() +// .authenticated(); + +// http.csrf().disable() +// .authorizeRequests() +// .antMatchers("/**/**/login").permitAll() +// .and() +// .authorizeRequests() +// .antMatchers("/**/**/keycloak").hasRole(UserConstant.ADMIN_ROLE) +// .anyRequest() +// .authenticated() +// .and() +// .oauth2ResourceServer() +// .jwt(); + + http.csrf().disable() + .authorizeRequests() + .antMatchers("/**/keycloak/**", "/**/keycloak/**/**") + .authenticated() + .and() + .oauth2ResourceServer() + .jwt(); + + + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(10); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/controller/UserController.java b/java/user-management/src/main/java/dev/sunbirdrc/controller/UserController.java new file mode 100644 index 000000000..249013317 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/controller/UserController.java @@ -0,0 +1,155 @@ +package dev.sunbirdrc.controller; + + +import dev.sunbirdrc.dto.*; +import dev.sunbirdrc.service.UserService; +import org.apache.commons.codec.binary.Base64; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.SecretKeySpec; +import javax.validation.Valid; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.Security; +import java.util.List; + +@RestController +@RequestMapping(path = "/api/v1") +public class UserController { + + @Autowired + private UserService userService; + + @PostMapping("/login") + public ResponseEntity loginUser(@Valid @RequestBody UserLoginDTO userLoginDTO) { + UserTokenDetailsDTO keycloakTokenDetailsDTO = userService.loginAndGenerateKeycloakToken(userLoginDTO); + + return new ResponseEntity<>(keycloakTokenDetailsDTO, HttpStatus.OK); + } + + @PostMapping("/registerUser") + public ResponseEntity registerUser(@Valid @RequestBody UserDetailsDTO userDTO) { + boolean status = userService.registerUser(userDTO); + + if (status) { + return new ResponseEntity<>("Successfully added user", HttpStatus.CREATED); + }else { + return new ResponseEntity<>("Unable to create user", HttpStatus.FAILED_DEPENDENCY); + } + } + + @PostMapping("/verifyAndUpdate/otp") + public ResponseEntity verifyUserMailOTP(@Valid @RequestBody UserOtpDTO userOtpDTO) { + boolean verified = false; + try { + verified = userService.verifyMailOTP(userOtpDTO); + } catch (Exception e) { + throw new RuntimeException(e); + } + + if (verified) { + return new ResponseEntity<>("Successfully verified user", HttpStatus.CREATED); + }else { + return new ResponseEntity<>("Unable to verify", HttpStatus.FAILED_DEPENDENCY); + } + } + + @PostMapping("/admin/generateOtp") + public ResponseEntity generateAdminOtp(@Valid @RequestBody AdminDTO adminDTO) { + try { + userService.generateAdminOtp(adminDTO); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return new ResponseEntity<>("Sending OTP to user mail", HttpStatus.OK); + } + + @PostMapping("/admin/login") + public ResponseEntity loginAdminUser(@Valid @RequestBody AdminLoginDTO adminLoginDTO) { + UserTokenDetailsDTO tokenDetailsDTO = null; + try { + tokenDetailsDTO = userService.getAdminTokenByOtp(adminLoginDTO); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return new ResponseEntity<>(tokenDetailsDTO, HttpStatus.OK); + } + + @GetMapping(path = "/keycloak") + public ResponseEntity getUser(){ + + + return new ResponseEntity<>("Role base access", HttpStatus.OK); + } + + @PostMapping("/keycloak/createBulkUser") + public ResponseEntity createBulkUser(@Valid @RequestBody List customUserDTOList) { + BulkCustomUserResponseDTO bulkCustomUserResponseDTO = userService.addBulkUser(customUserDTOList); + + return new ResponseEntity<>(bulkCustomUserResponseDTO, HttpStatus.CREATED); + } + + @PostMapping("/user/generateOtp") + public ResponseEntity generateUserOtp(@Valid @RequestBody CustomUsernameDTO customUsernameDTO) { + userService.generateCustomUserOtp(customUsernameDTO); + + return new ResponseEntity<>("Sending OTP to user mail", HttpStatus.OK); + } + + @PostMapping("/user/login") + public ResponseEntity loginCustomUser(@Valid @RequestBody CustomUserLoginDTO customUserLoginDTO) { + UserTokenDetailsDTO tokenDetailsDTO = null; + try { + tokenDetailsDTO = userService.getCustomUserTokenByOtp(customUserLoginDTO); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return new ResponseEntity<>(tokenDetailsDTO, HttpStatus.OK); + } + + @PostMapping(path = "/keycloak/user/delete") + public ResponseEntity deleteUser(@Valid @RequestBody List customUserDeleteDTOList){ + userService.deleteBulkUSer(customUserDeleteDTOList); + + return new ResponseEntity<>("Successfully delete the user", HttpStatus.OK); + } + + @PostMapping("/keycloak/user/update") + public ResponseEntity updateUser(@Valid @RequestBody CustomUserUpdateDTO customUserUpdateDTO) { + userService.updateUser(customUserUpdateDTO); + + return new ResponseEntity<>("Successfully updated user", HttpStatus.OK); + } + + @PostMapping("/keycloak/user/create") + public ResponseEntity createCustomUser(@Valid @RequestBody CustomUserDTO customUserDTO) { + CustomUserResponseDTO customUserResponseDTO = userService.createCustomUser(customUserDTO); + + return new ResponseEntity<>(customUserResponseDTO, HttpStatus.OK); + } + + @PostMapping("/keycloak/persist/userCredential") + public ResponseEntity persistUserCredential(@RequestBody CustomUserDTO customUserDTO) { + try { + userService.persistUserDetailsWithCredentials(customUserDTO); + } catch (Exception e) { + return new ResponseEntity<>("Failed to persist", HttpStatus.EXPECTATION_FAILED); + } + + return new ResponseEntity<>("Persist successfully", HttpStatus.OK); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/AdminDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/AdminDTO.java new file mode 100644 index 000000000..791193b37 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/AdminDTO.java @@ -0,0 +1,17 @@ +package dev.sunbirdrc.dto; + + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.*; + +@AllArgsConstructor +@Data +public class AdminDTO { + @NotBlank(message = "Username is required field") + @Email(message = "Username should be valid mail id") + private String username; + + private String description; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/AdminLoginDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/AdminLoginDTO.java new file mode 100644 index 000000000..448db9e10 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/AdminLoginDTO.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.dto; + + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@AllArgsConstructor +@Data +public class AdminLoginDTO { + @NotBlank(message = "Email is required field") + @Email(message = "Invalid mail id") + private String email; + + @NotBlank(message = "OTP is required field") + @Size(min = 6, max = 6, message = "OTP length should be six digit") + private String otp; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/BulkCustomUserResponseDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/BulkCustomUserResponseDTO.java new file mode 100644 index 000000000..36501642b --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/BulkCustomUserResponseDTO.java @@ -0,0 +1,17 @@ +package dev.sunbirdrc.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@AllArgsConstructor +@Data +@Builder +@NoArgsConstructor +public class BulkCustomUserResponseDTO { + private List succeedUser; + private List failedUser; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/BulkUserDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/BulkUserDTO.java new file mode 100644 index 000000000..ffba635c8 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/BulkUserDTO.java @@ -0,0 +1,16 @@ +package dev.sunbirdrc.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@NoArgsConstructor +@AllArgsConstructor +@Data +@Builder +public class BulkUserDTO { + List customUserDTOList; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserDTO.java new file mode 100644 index 000000000..394bddf1f --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserDTO.java @@ -0,0 +1,33 @@ +package dev.sunbirdrc.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +@AllArgsConstructor +@Data +@Builder +public class CustomUserDTO { + @Email(message = "Username should be valid mail id") + @NotBlank(message = "userName is required field") + private String username; + + @NotBlank(message = "email is required field") + @Email(message = "Invalid mail id") + private String email; + + @NotBlank(message = "password is required field") + private String password; + + @NotBlank(message = "firstName is required field") + private String firstName; + + @NotBlank(message = "lastName is required field") + private String lastName; + + @NotBlank(message = "roleName is required field") + private String roleName; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserDeleteDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserDeleteDTO.java new file mode 100644 index 000000000..ad77f85fe --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserDeleteDTO.java @@ -0,0 +1,17 @@ +package dev.sunbirdrc.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +@AllArgsConstructor +@Data +public class CustomUserDeleteDTO { + @NotBlank(message = "Username is required field") + @Email(message = "Username should be valid mail id") + private String email; + + private String description; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserLoginDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserLoginDTO.java new file mode 100644 index 000000000..5eb009fb8 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserLoginDTO.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.dto; + + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@AllArgsConstructor +@Data +public class CustomUserLoginDTO { + @NotBlank(message = "Email is required field") + @Email(message = "Invalid mail id") + private String email; + + @NotBlank(message = "OTP is required field") + @Size(min = 6, max = 6, message = "OTP length should be six digit") + private String otp; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserResponseDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserResponseDTO.java new file mode 100644 index 000000000..8894ebf7c --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserResponseDTO.java @@ -0,0 +1,17 @@ +package dev.sunbirdrc.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +@AllArgsConstructor +@Data +@Builder +public class CustomUserResponseDTO { + private String userId; + private String email; + private String firstName; + private String lastName; + private String roleName; + private String status; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserUpdateDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserUpdateDTO.java new file mode 100644 index 000000000..614ce4df5 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUserUpdateDTO.java @@ -0,0 +1,26 @@ +package dev.sunbirdrc.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import java.util.List; + +@AllArgsConstructor +@Data +@Builder +public class CustomUserUpdateDTO { + @Email(message = "Username should be valid mail id") + @NotBlank(message = "userName is required field") + private String username; + + @NotBlank(message = "firstName is required field") + private String firstName; + + @NotBlank(message = "lastName is required field") + private String lastName; + + private List roleNames; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUsernameDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUsernameDTO.java new file mode 100644 index 000000000..2c8ca330b --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/CustomUsernameDTO.java @@ -0,0 +1,18 @@ +package dev.sunbirdrc.dto; + + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +@AllArgsConstructor +@Data +public class CustomUsernameDTO { + @NotBlank(message = "Username is required field") + @Email(message = "Username should be valid mail id") + private String username; + + private String description; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/UserDetailsDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/UserDetailsDTO.java new file mode 100644 index 000000000..837e68a77 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/UserDetailsDTO.java @@ -0,0 +1,44 @@ +package dev.sunbirdrc.dto; + + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +@AllArgsConstructor +@Data +@Builder +public class UserDetailsDTO { + @Email(message = "Username should be valid mail id") + @NotBlank(message = "userName is required field") + private String userName; + + @NotBlank(message = "email is required field") + @Email(message = "Invalid mail id") + private String email; + + private String password; + + @NotBlank(message = "firstName is required field") + private String firstName; + + @NotBlank(message = "lastName is required field") + private String lastName; + + @NotBlank(message = "rollNo is required field") + private String rollNo; + + @NotBlank(message = "instituteId is required field") + private String instituteId; + + @NotBlank(message = "instituteName is required field") + private String instituteName; + + @NotBlank(message = "phoneNo is required field") + private String phoneNo; + + private String userId; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/UserLoginDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/UserLoginDTO.java new file mode 100644 index 000000000..42aae8869 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/UserLoginDTO.java @@ -0,0 +1,21 @@ +package dev.sunbirdrc.dto; + + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +@AllArgsConstructor +@Data +@Builder +public class UserLoginDTO { + @NotBlank(message = "Username is required field") + @Email(message = "Username accepts only user mail id") + private String username; + + @NotBlank(message = "Password is required field") + private String password; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/UserOtpDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/UserOtpDTO.java new file mode 100644 index 000000000..4932821c3 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/UserOtpDTO.java @@ -0,0 +1,25 @@ +package dev.sunbirdrc.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +@AllArgsConstructor +@Data +public class UserOtpDTO { + + @NotBlank(message = "Username is required field") + @Email(message = "Username accepts only user mail id") + private String username; + + @NotBlank(message = "OTP is required field") + @Size(min = 6, max = 6, message = "OTP length should be six digit") + private String otp; + + @NotBlank(message = "Password is required field") + private String password; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/dto/UserTokenDetailsDTO.java b/java/user-management/src/main/java/dev/sunbirdrc/dto/UserTokenDetailsDTO.java new file mode 100644 index 000000000..e201b7408 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/dto/UserTokenDetailsDTO.java @@ -0,0 +1,25 @@ +package dev.sunbirdrc.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.keycloak.representations.idm.RoleRepresentation; +import org.keycloak.representations.idm.UserRepresentation; + +import java.util.List; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class UserTokenDetailsDTO { + private String accessToken; + private long expiresIn; + private String refreshToken; + private long refreshExpiresIn; + private String tokenType; + private String scope; + UserRepresentation userRepresentation; + List roleRepresentationList; +} \ No newline at end of file diff --git a/java/user-management/src/main/java/dev/sunbirdrc/entity/UserCredential.java b/java/user-management/src/main/java/dev/sunbirdrc/entity/UserCredential.java new file mode 100644 index 000000000..e0964c436 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/entity/UserCredential.java @@ -0,0 +1,29 @@ +package dev.sunbirdrc.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; + +@AllArgsConstructor +@NoArgsConstructor +@Builder +@Data +@Entity +@Table(name = "user_credential") +public class UserCredential { + @Id + @GeneratedValue(generator = "UUID") + @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") + @Column(updatable = false, nullable = false) + private String id; + + @Column(unique = true, nullable = false) + private String userName; + + @Column + private String password; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/entity/UserDetails.java b/java/user-management/src/main/java/dev/sunbirdrc/entity/UserDetails.java new file mode 100644 index 000000000..ef8028062 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/entity/UserDetails.java @@ -0,0 +1,40 @@ +package dev.sunbirdrc.entity; + +import lombok.Builder; +import lombok.Data; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; + +@Builder +@Data +@Entity +@Table(name = "user_details") +public class UserDetails { + @Id + @GeneratedValue(generator = "UUID") + @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") + @Column(updatable = false, nullable = false) + private String id; + + @Column + private String userId; + @Column + private String userName; + @Column + private String firstName; + @Column + private String lastName; + @Column + private String email; + @Column + private Boolean enabled; + @Column + private String rollNo; + @Column + private String instituteId; + @Column + private String instituteName; + @Column + private String phoneNo; +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/AuthorizationException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/AuthorizationException.java new file mode 100644 index 000000000..078a2fafc --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/AuthorizationException.java @@ -0,0 +1,11 @@ +package dev.sunbirdrc.exception; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class AuthorizationException extends RuntimeException { + + public AuthorizationException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/CipherEncoderException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/CipherEncoderException.java new file mode 100644 index 000000000..d18a48dc0 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/CipherEncoderException.java @@ -0,0 +1,11 @@ +package dev.sunbirdrc.exception; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class CipherEncoderException extends RuntimeException { + + public CipherEncoderException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/InvalidInputDataException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/InvalidInputDataException.java new file mode 100644 index 000000000..73a6986af --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/InvalidInputDataException.java @@ -0,0 +1,11 @@ +package dev.sunbirdrc.exception; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class InvalidInputDataException extends RuntimeException { + + public InvalidInputDataException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/KeycloakUserException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/KeycloakUserException.java new file mode 100644 index 000000000..47436eae8 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/KeycloakUserException.java @@ -0,0 +1,11 @@ +package dev.sunbirdrc.exception; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class KeycloakUserException extends RuntimeException { + + public KeycloakUserException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/OtpException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/OtpException.java new file mode 100644 index 000000000..b6ef7abba --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/OtpException.java @@ -0,0 +1,11 @@ +package dev.sunbirdrc.exception; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class OtpException extends RuntimeException { + + public OtpException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/RoleNotFoundException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/RoleNotFoundException.java new file mode 100644 index 000000000..c2edec892 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/RoleNotFoundException.java @@ -0,0 +1,11 @@ +package dev.sunbirdrc.exception; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class RoleNotFoundException extends RuntimeException { + + public RoleNotFoundException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/UserConflictException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/UserConflictException.java new file mode 100644 index 000000000..a9a15a30d --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/UserConflictException.java @@ -0,0 +1,11 @@ +package dev.sunbirdrc.exception; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class UserConflictException extends RuntimeException { + + public UserConflictException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/UserCredentialsException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/UserCredentialsException.java new file mode 100644 index 000000000..00d2d9be5 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/UserCredentialsException.java @@ -0,0 +1,10 @@ +package dev.sunbirdrc.exception; + +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class UserCredentialsException extends RuntimeException{ + public UserCredentialsException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/exception/UserNotFoundException.java b/java/user-management/src/main/java/dev/sunbirdrc/exception/UserNotFoundException.java new file mode 100644 index 000000000..7b0f0d014 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/exception/UserNotFoundException.java @@ -0,0 +1,12 @@ +package dev.sunbirdrc.exception; + +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; + +@NoArgsConstructor +public class UserNotFoundException extends RuntimeException { + + public UserNotFoundException(String message) { + super(message); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/repository/UserCredentialRepository.java b/java/user-management/src/main/java/dev/sunbirdrc/repository/UserCredentialRepository.java new file mode 100644 index 000000000..c8f5f8916 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/repository/UserCredentialRepository.java @@ -0,0 +1,13 @@ +package dev.sunbirdrc.repository; + +import dev.sunbirdrc.entity.UserCredential; +import dev.sunbirdrc.entity.UserDetails; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserCredentialRepository extends JpaRepository { + Optional findByUserName(String username); +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/repository/UserDetailsRepository.java b/java/user-management/src/main/java/dev/sunbirdrc/repository/UserDetailsRepository.java new file mode 100644 index 000000000..c973b1d60 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/repository/UserDetailsRepository.java @@ -0,0 +1,9 @@ +package dev.sunbirdrc.repository; + +import dev.sunbirdrc.entity.UserDetails; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserDetailsRepository extends JpaRepository { +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/service/MailService.java b/java/user-management/src/main/java/dev/sunbirdrc/service/MailService.java new file mode 100644 index 000000000..24fe2642b --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/service/MailService.java @@ -0,0 +1,145 @@ +package dev.sunbirdrc.service; + +import dev.sunbirdrc.config.PropertiesValueMapper; +import dev.sunbirdrc.dto.CustomUserDTO; +import dev.sunbirdrc.entity.UserDetails; +import dev.sunbirdrc.exception.OtpException; +import dev.sunbirdrc.utils.OtpUtil; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; + +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; + +@Service +public class MailService { + Logger logger = LoggerFactory.getLogger(this.getClass()); + @Autowired + private Configuration freeMarkerConfiguration; + + @Autowired + private JavaMailSender mailSender; + + @Autowired + private PropertiesValueMapper propMapping; + + @Autowired + private OtpUtil otpUtil; + + /** + * @param userDetails + */ + @Async + public void sendOtpMail(UserDetails userDetails) { + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + + MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + + mimeMessageHelper.setSubject(propMapping.getOtpMailVerificationSubject()); + mimeMessageHelper.setFrom(new InternetAddress(propMapping.getOtpMailVerificationFromAddress(), + propMapping.getOtpMailVerificationPersonalName())); + mimeMessageHelper.setTo(userDetails.getEmail()); + mimeMessageHelper.setText(generateMailContent(userDetails), true); + + mailSender.send(mimeMessageHelper.getMimeMessage()); + } catch (Exception e) { + logger.error("Exception while sending mail: ", e); + throw new OtpException("Exception while composing and sending mail with OTP"); + } + } + + + /** + * @param userProfile + * @return + * @throws Exception + */ + private String generateMailContent(UserDetails userProfile) throws Exception { + String processedTemplateString = null; + + + Map mailMap = new HashMap<>(); + mailMap.put("userFirstName", userProfile.getFirstName()); + mailMap.put("userLastName", userProfile.getLastName()); + mailMap.put("signature", "UPSMF"); + mailMap.put("location", ""); + + TimeUnit timeUnit = otpUtil.getOtpTimeUnit(); + Optional optionalOTP = otpUtil.generateAndPersistOTP(userProfile.getUserId(), timeUnit); + + if (optionalOTP.isPresent()) { + mailMap.put("otp", String.valueOf(optionalOTP.get())); + mailMap.put("otpDuration", propMapping.getOtpTtlDuration()); + mailMap.put("timeUnit", timeUnit.name().toLowerCase()); + } + + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("otp-verification-mail.ftl"); + + try { + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + } catch (TemplateException e) { + logger.error("Error while creating mail template for request info"); + throw new Exception("Error while creating mail template for request info"); + } + + return processedTemplateString; + } + + @Async + public void sendUserCreationNotification(CustomUserDTO customUserDTO) { + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + + MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + + mimeMessageHelper.setSubject(propMapping.getCustomUserCreationSubject()); + mimeMessageHelper.setFrom(new InternetAddress(propMapping.getCustomUserCreationFromAddress(), + propMapping.getCustomUserCreationPersonalName())); + mimeMessageHelper.setTo(customUserDTO.getEmail()); + mimeMessageHelper.setText(generateNotificationMailContent(customUserDTO), true); + + mailSender.send(mimeMessageHelper.getMimeMessage()); + } catch (Exception e) { + logger.error("Exception while sending user creation mail notification: ", e); +// throw new Exception("Exception while composing and sending user creation mail notification"); + } + } + + private String generateNotificationMailContent(CustomUserDTO customUserDTO) throws Exception { + String processedTemplateString = null; + + + Map mailMap = new HashMap<>(); + mailMap.put("userFirstName", customUserDTO.getFirstName()); + mailMap.put("userLastName", customUserDTO.getLastName()); + mailMap.put("loginLInk", propMapping.getCustomUserLoginUrl()); + mailMap.put("signature", "UPSMF"); + + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("user-creation-notification-mail.ftl"); + + try { + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + } catch (TemplateException e) { + logger.error("Error while creating notification mail template for request info"); + throw new Exception("Error while creating notification mail template for request info"); + } + + return processedTemplateString; + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/service/UserService.java b/java/user-management/src/main/java/dev/sunbirdrc/service/UserService.java new file mode 100644 index 000000000..068c7491b --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/service/UserService.java @@ -0,0 +1,741 @@ +package dev.sunbirdrc.service; + + +import dev.sunbirdrc.config.KeycloakConfig; +import dev.sunbirdrc.config.PropertiesValueMapper; +import dev.sunbirdrc.dto.*; +import dev.sunbirdrc.entity.UserCredential; +import dev.sunbirdrc.entity.UserDetails; +import dev.sunbirdrc.exception.*; +import dev.sunbirdrc.repository.UserCredentialRepository; +import dev.sunbirdrc.repository.UserDetailsRepository; +import dev.sunbirdrc.utils.CipherEncoder; +import dev.sunbirdrc.utils.OtpUtil; +import dev.sunbirdrc.utils.UserConstant; +import org.keycloak.admin.client.Keycloak; +import org.keycloak.admin.client.resource.ClientsResource; +import org.keycloak.admin.client.resource.UserResource; +import org.keycloak.admin.client.resource.UsersResource; +import org.keycloak.admin.client.token.TokenManager; +import org.keycloak.representations.AccessTokenResponse; +import org.keycloak.representations.idm.CredentialRepresentation; +import org.keycloak.representations.idm.RoleRepresentation; +import org.keycloak.representations.idm.UserRepresentation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpStatus; +import org.springframework.lang.NonNull; +import org.springframework.scheduling.annotation.Async; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.ws.rs.NotAuthorizedException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class UserService { + + private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class); + + @Autowired + private KeycloakConfig keycloakConfig; + + @Qualifier("systemKeycloak") + @Autowired + private Keycloak systemKeycloak; + + @Autowired + private MailService mailService; + + @Autowired + private OtpUtil otpUtil; + + @Autowired + private PropertiesValueMapper valueMapper; + + @Autowired + private UserDetailsRepository userDetailsRepository; + + @Autowired + private UserCredentialRepository userCredentialRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private CipherEncoder cipherEncoder; + + public UsersResource getSystemUsersResource(){ + return systemKeycloak.realm(valueMapper.getRealm()).users(); + } + + public CredentialRepresentation createPasswordCredentials(String password) { + CredentialRepresentation passwordCredentials = new CredentialRepresentation(); + passwordCredentials.setTemporary(false); + passwordCredentials.setType(CredentialRepresentation.PASSWORD); + passwordCredentials.setValue(password); + return passwordCredentials; + } + + public ClientsResource getSystemClientResource(){ + return systemKeycloak.realm(valueMapper.getRealm()).clients(); + } + + /** + * It provides all details of user that exist in keycloak server. + * @param userName + * @return + */ + public List getUserDetails(String userName) { + return getSystemUsersResource().search(userName, true); + } + + + public boolean configureAdmin(UserDetailsDTO userDetailsDTO) { + + return false; + } + + public UserTokenDetailsDTO loginAndGenerateKeycloakToken(UserLoginDTO userLoginDTO) { + if (userLoginDTO != null && StringUtils.hasText(userLoginDTO.getUsername()) + && StringUtils.hasText(userLoginDTO.getPassword())) { + + try { + TokenManager tokenManager = keycloakConfig + .getUserKeycloak(userLoginDTO.getUsername(), userLoginDTO.getPassword()).tokenManager(); + + AccessTokenResponse accessTokenResponse = tokenManager.getAccessToken(); + + return UserTokenDetailsDTO.builder() + .accessToken(accessTokenResponse.getToken()) + .expiresIn(accessTokenResponse.getExpiresIn()) + .refreshToken(accessTokenResponse.getRefreshToken()) + .refreshExpiresIn(accessTokenResponse.getRefreshExpiresIn()) + .tokenType(accessTokenResponse.getTokenType()) + .scope(accessTokenResponse.getScope()) + .build(); + } catch (NotAuthorizedException e) { + throw new AuthorizationException("Credentials have authorization issue"); + } catch (Exception e) { + throw new KeycloakUserException("Unable to get user detils - Update user"); + } + } else { + throw new UserCredentialsException("User credentials are invalid"); + } + } + + public boolean registerUser(UserDetailsDTO userDTO){ + boolean status = false; + + if (userDTO != null && !StringUtils.isEmpty(userDTO.getUserName())) { + + UserRepresentation user = new UserRepresentation(); + user.setUsername(userDTO.getUserName()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + user.setEmail(userDTO.getEmail()); + user.setRequiredActions(Arrays.asList(UserConstant.VERIFY_MAIL_ACTION, UserConstant.UPDATE_PASSWORD_ACTION)); + user.setEnabled(false); + + Map> customAttributes = new HashMap<>(); + customAttributes.put(UserConstant.ROLL_NO, Collections.singletonList(userDTO.getRollNo())); + customAttributes.put(UserConstant.INSTITUTE_ID, Collections.singletonList(userDTO.getInstituteId())); + customAttributes.put(UserConstant.INSTITUTE_NAME, Collections.singletonList(userDTO.getInstituteName())); + customAttributes.put(UserConstant.PHONE_NUMBER, Collections.singletonList(userDTO.getPhoneNo())); + + user.setAttributes(customAttributes); + + try { + Response response = getSystemUsersResource().create(user); + + if (response.getStatus() == HttpStatus.CREATED.value()) { + persistUserDetails(userDTO); + status = true; + } else { + LOGGER.error("Unable to create user, systemKeycloak response - " + response.getStatusInfo()); + throw new KeycloakUserException("Unable to create user in keycloak directory: " + response.getStatusInfo()); + } + } catch (Exception e) { + LOGGER.error("Unable to create user in systemKeycloak", e.getMessage()); + throw new KeycloakUserException("Unable to create user - error message: " + e.getMessage()); + } + } + return status; + } + + public void persistUserDetails(UserDetailsDTO userDTO) throws Exception { + if (userDTO != null && !StringUtils.isEmpty(userDTO.getUserName())) { + List userRepresentationList = getUserDetails(userDTO.getUserName()); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> userDTO.getUserName().equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + + if (userRepresentationOptional.isPresent()) { + UserRepresentation userRepresentation = userRepresentationOptional.get(); + + UserDetails claimUser = UserDetails.builder() + .userId(userRepresentation.getId()) + .userName(userRepresentation.getUsername()) + .firstName(userRepresentation.getFirstName()) + .lastName(userRepresentation.getLastName()) + .email(userRepresentation.getEmail()) + .enabled(userRepresentation.isEnabled()) + .rollNo(userDTO.getRollNo()) + .instituteId(userDTO.getInstituteId()) + .instituteName(userDTO.getInstituteName()) + .phoneNo(userDTO.getPhoneNo()) + .build(); + + userDetailsRepository.save(claimUser); + mailService.sendOtpMail(claimUser); + } + } + } else { + throw new UserNotFoundException("Invalid user details or username, while saving user in claim service"); + } + } + + public boolean verifyMailOTP(UserOtpDTO userOtpDTO) throws Exception { + if (userOtpDTO != null && !StringUtils.isEmpty(userOtpDTO.getUsername())) { + + List userRepresentationList = getUserDetails(userOtpDTO.getUsername()); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> + userOtpDTO.getUsername().equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + + if (!userRepresentationOptional.isPresent()) { + throw new Exception("Username missing while verifying OTP"); + } + + + boolean matched = otpUtil.verifyUserMailOtp(userRepresentationOptional.get().getId(), userOtpDTO.getOtp()); + + if (matched) { + UserResource userResource = getSystemUsersResource().get(userRepresentationOptional.get().getId()); + + UserRepresentation existingUserRepresentation = userResource.toRepresentation(); + List requiredActions = existingUserRepresentation.getRequiredActions(); + + if (requiredActions != null && !requiredActions.isEmpty()) { + requiredActions = requiredActions.stream() + .filter(actionName -> !UserConstant.VERIFY_MAIL_ACTION.equals(actionName) + && !UserConstant.UPDATE_PASSWORD_ACTION.equals(actionName)) + .collect(Collectors.toList()); + } + + existingUserRepresentation.setRequiredActions(requiredActions); + + CredentialRepresentation credential = createPasswordCredentials(userOtpDTO.getPassword()); + existingUserRepresentation.setCredentials(Collections.singletonList(credential)); + existingUserRepresentation.setEnabled(true); + + userResource.update(existingUserRepresentation); + + return true; + } + } + } + + return false; + } + + public void generateAdminOtp(AdminDTO adminDTO) throws Exception { + if (adminDTO != null && !StringUtils.isEmpty(adminDTO.getUsername())) { + String username = adminDTO.getUsername(); + + List userRepresentationList = getUserDetails(username); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> username.equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + + if (userRepresentationOptional.isPresent()) { + UserRepresentation userRepresentation = userRepresentationOptional.get(); + + UsersResource usersResource = getSystemUsersResource(); + List roleRepresentationList = usersResource.get(userRepresentation.getId()).roles().realmLevel().listEffective(); + + Optional roleRepresentationOptional = roleRepresentationList.stream() + .filter(roleRepresentation -> UserConstant.ADMIN_ROLE.equals(roleRepresentation.getName())) + .findFirst(); + + if (roleRepresentationOptional.isPresent()) { + UserDetails userDetails = UserDetails.builder() + .userId(userRepresentation.getId()) + .userName(userRepresentation.getUsername()) + .firstName(userRepresentation.getFirstName()) + .lastName(userRepresentation.getLastName()) + .email(userRepresentation.getEmail()) + .enabled(userRepresentation.isEnabled()) + .build(); + + mailService.sendOtpMail(userDetails); + } else { + throw new OtpException("User doesn't have role admin"); + } + } + } + } + } + + public UserTokenDetailsDTO getAdminTokenByOtp(AdminLoginDTO adminLoginDTO) throws Exception { + if (adminLoginDTO != null && !StringUtils.isEmpty(adminLoginDTO.getEmail())) { + String username = adminLoginDTO.getEmail(); + + List userRepresentationList = getUserDetails(username); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> username.equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + + if (!userRepresentationOptional.isPresent()) { + throw new OtpException("Username missing while verifying OTP"); + } + /////////////////////////////////////// + +// UserRepresentation userRepresentation = userRepresentationOptional.get(); +// List credentials = userRepresentation.getCredentials(); +// CredentialRepresentation credentialRepresentation = credentials.get(0); +// credentialRepresentation.getSecretData(); +// credentialRepresentation.getValue(); + + ////////////////////////////////// + + if (otpUtil.verifyUserMailOtp(userRepresentationOptional.get().getId(), adminLoginDTO.getOtp())) { + TokenManager tokenManager = systemKeycloak.tokenManager(); + AccessTokenResponse accessTokenResponse = tokenManager.getAccessToken(); + + return UserTokenDetailsDTO.builder() + .accessToken(accessTokenResponse.getToken()) + .expiresIn(accessTokenResponse.getExpiresIn()) + .tokenType(accessTokenResponse.getTokenType()) + .scope(accessTokenResponse.getScope()) + .build(); + } else { + throw new OtpException("OTP mismatch"); + } + } else { + throw new OtpException("Unable to get user details"); + } + }else { + throw new OtpException("OTP details missing"); + } + } + + + + public BulkCustomUserResponseDTO addBulkUser(List bulkUserDTOList){ + + if (bulkUserDTOList == null || bulkUserDTOList.isEmpty()) { + throw new InvalidInputDataException("Invalid user data to process"); + } else if (bulkUserDTOList.size() > valueMapper.getBulkUserSizeLimit()) { + throw new InvalidInputDataException("User size limit crossed - Bulk user allowed size: " + valueMapper.getBulkUserSizeLimit()); + } else { + return processBulkUserData(bulkUserDTOList); + } + } + + public BulkCustomUserResponseDTO processBulkUserData(List bulkUserDTOList) { + BulkCustomUserResponseDTO bulkCustomUserResponseDTO = new BulkCustomUserResponseDTO(); + List succeedUserList = new ArrayList<>(); + List failedUserList = new ArrayList<>(); + + for (CustomUserDTO customUserDTO : bulkUserDTOList) { + CustomUserResponseDTO customUserResponseDTO = CustomUserResponseDTO.builder() + .email(customUserDTO.getEmail()) + .firstName(customUserDTO.getFirstName()) + .lastName(customUserDTO.getLastName()) + .roleName(customUserDTO.getRoleName()) + .build(); + + if (isUserExist(customUserDTO.getUsername())) { + LOGGER.error(">>> User is already exist in user management"); + customUserResponseDTO.setStatus("Faild to create user - User is already exist in user management DB"); + failedUserList.add(customUserResponseDTO); + } else { + UserRepresentation userRepresentation = new UserRepresentation(); + userRepresentation.setUsername(customUserDTO.getUsername()); + userRepresentation.setFirstName(customUserDTO.getFirstName()); + userRepresentation.setLastName(customUserDTO.getLastName()); + userRepresentation.setEmail(customUserDTO.getEmail()); + userRepresentation.setCredentials(Collections.singletonList(createPasswordCredentials(customUserDTO.getPassword()))); + userRepresentation.setEnabled(true); + + try { + Response response = getSystemUsersResource().create(userRepresentation); + + if (response.getStatus() == HttpStatus.CREATED.value()) { + String userId = assignCustomUserRole(customUserDTO); + persistUserDetailsWithCredentials(customUserDTO); + + customUserResponseDTO.setUserId(userId); + customUserResponseDTO.setStatus("User has been created successfully - mail in progress"); + succeedUserList.add(customUserResponseDTO); + } else { + LOGGER.error("Unable to create custom user, systemKeycloak response - " + response.getStatusInfo()); + + customUserResponseDTO.setStatus("Faild to create user - Unable to create user in keycloak: " + response.getStatus()); + failedUserList.add(customUserResponseDTO); +// throw new KeycloakUserException("Unable to create custom user in keycloak directory: " + response.getStatusInfo()); + } + } catch (Exception e) { + LOGGER.error("Unable to create custom user in systemKeycloak", e.getMessage()); + customUserResponseDTO.setStatus("Faild to create user"); + failedUserList.add(customUserResponseDTO); +// throw new KeycloakUserException("Unable to create custom user - error message: " + e.getMessage()); + } + } + } + + bulkCustomUserResponseDTO.setSucceedUser(succeedUserList); + bulkCustomUserResponseDTO.setFailedUser(failedUserList); + + processUserCreationMailNotification(bulkCustomUserResponseDTO); + + return bulkCustomUserResponseDTO; + } + + @Async + private void processUserCreationMailNotification(@NonNull BulkCustomUserResponseDTO bulkCustomUserResponseDTO) { + if (bulkCustomUserResponseDTO.getSucceedUser() != null && !bulkCustomUserResponseDTO.getSucceedUser().isEmpty()) { + for (CustomUserResponseDTO customUserResponseDTO : bulkCustomUserResponseDTO.getSucceedUser()) { + + CustomUserDTO customUserDTO = CustomUserDTO.builder() + .email(customUserResponseDTO.getEmail()) + .firstName(customUserResponseDTO.getFirstName()) + .lastName(customUserResponseDTO.getLastName()) + .roleName(customUserResponseDTO.getRoleName()) + .build(); + + + mailService.sendUserCreationNotification(customUserDTO); + } + } + } + + /** + * @param customUserDTO + */ + private String assignCustomUserRole(CustomUserDTO customUserDTO) { + List userRepresentationList = getUserDetails(customUserDTO.getUsername()); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream().findFirst(); + + if (userRepresentationOptional.isPresent()) { + List roleToAdd = new LinkedList<>(); + + UserResource user = systemKeycloak + .realm(valueMapper.getRealm()) + .users() + .get(userRepresentationOptional.get().getId()); + + roleToAdd.add(systemKeycloak + .realm(valueMapper.getRealm()) + .roles() + .get(customUserDTO.getRoleName()) + .toRepresentation() + ); + user.roles().realmLevel().add(roleToAdd); + + return userRepresentationOptional.get().getId(); + } else { + throw new RoleNotFoundException("Unable to find role"); + } + } else { + throw new RoleNotFoundException("Unable to find role"); + } + } + + + /** + * Password is being saved as plain text - need to refactor. + * + * @param customUserDTO + * @throws Exception + */ + public void persistUserDetailsWithCredentials(@NonNull CustomUserDTO customUserDTO) throws Exception { + UserCredential userCredential = UserCredential.builder() + .userName(customUserDTO.getUsername()) + .password(cipherEncoder.encodeText(customUserDTO.getPassword())) + .build(); + + userCredentialRepository.save(userCredential); + } + + /** + * @param adminDTO + * @throws Exception + */ + public void generateCustomUserOtp(CustomUsernameDTO customUsernameDTO) { + if (customUsernameDTO != null && !StringUtils.isEmpty(customUsernameDTO.getUsername())) { + String username = customUsernameDTO.getUsername(); + + if (!isUserExist(username)) { + throw new UserNotFoundException("User is not available in User Management System"); + } + + List userRepresentationList = getUserDetails(username); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> username.equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + + if (userRepresentationOptional.isPresent()) { + UserRepresentation userRepresentation = userRepresentationOptional.get(); + + UserDetails userDetails = UserDetails.builder() + .userId(userRepresentation.getId()) + .userName(userRepresentation.getUsername()) + .firstName(userRepresentation.getFirstName()) + .lastName(userRepresentation.getLastName()) + .email(userRepresentation.getEmail()) + .enabled(userRepresentation.isEnabled()) + .build(); + + mailService.sendOtpMail(userDetails); + } + } else { + throw new UserNotFoundException("User is not available in Keycloak System"); + } + } else { + throw new InvalidInputDataException("Invalid input data"); + } + } + + /** + * @param customUserLoginDTO + * @return + * @throws Exception + */ + public UserTokenDetailsDTO getCustomUserTokenByOtp(CustomUserLoginDTO customUserLoginDTO) throws Exception { + if (customUserLoginDTO != null && !StringUtils.isEmpty(customUserLoginDTO.getEmail())) { + String username = customUserLoginDTO.getEmail(); + + List userRepresentationList = getUserDetails(username); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> username.equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + + if (!userRepresentationOptional.isPresent()) { + throw new OtpException("Username missing while verifying OTP"); + } + + if (otpUtil.verifyUserMailOtp(userRepresentationOptional.get().getId(), customUserLoginDTO.getOtp())) { + try { + List roleRepresentationList = getSystemUsersResource() + .get(userRepresentationOptional.get().getId()) + .roles().realmLevel().listEffective(); + + TokenManager tokenManager = keycloakConfig + .getUserKeycloak(customUserLoginDTO.getEmail(), + getCustomUserCredentail(customUserLoginDTO.getEmail())) + .tokenManager(); + + AccessTokenResponse accessTokenResponse = tokenManager.getAccessToken(); + + return UserTokenDetailsDTO.builder() + .accessToken(accessTokenResponse.getToken()) + .expiresIn(accessTokenResponse.getExpiresIn()) + .refreshToken(accessTokenResponse.getRefreshToken()) + .refreshExpiresIn(accessTokenResponse.getRefreshExpiresIn()) + .tokenType(accessTokenResponse.getTokenType()) + .scope(accessTokenResponse.getScope()) + .userRepresentation(userRepresentationOptional.get()) + .roleRepresentationList(roleRepresentationList) + .build(); + } catch (NotAuthorizedException e) { + throw new AuthorizationException("Credentials have authorization issue"); + } catch (Exception e) { + throw new KeycloakUserException("Unable to get user detils - Update user"); + } + } else { + throw new OtpException("OTP mismatch"); + } + } else { + throw new OtpException("Unable to get user details"); + } + }else { + throw new OtpException("OTP details missing"); + } + } + + + /** + * Password is being saved as plain text - Need to refactor in future + * @param username + * @return + */ + private @NonNull String getCustomUserCredentail(@NonNull String username) { + Optional userCredentialOptional = userCredentialRepository.findByUserName(username); + + if (userCredentialOptional.isPresent()) { + return cipherEncoder.decodeText(userCredentialOptional.get().getPassword()); + } else { + throw new UserNotFoundException("User is not configured properly in User management system"); + } + } + + public void deleteBulkUSer(List customUserDeleteDTOList) { + if (customUserDeleteDTOList != null && !customUserDeleteDTOList.isEmpty()) { + for (CustomUserDeleteDTO customUserDeleteDTO : customUserDeleteDTOList) { + deleteUser(customUserDeleteDTO.getEmail()); + } + } + } + + public void deleteUser(String username){ + List userRepresentationList = getUserDetails(username); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> username.equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + + if (!userRepresentationOptional.isPresent()) { + throw new UserNotFoundException("Unable to find user in keycloak " + username); + } + + settleUserDeletionInDB(username); + + UsersResource usersResource = getSystemUsersResource(); + usersResource.get(userRepresentationOptional.get().getId()).remove(); + } + + + } + + private void settleUserDeletionInDB(@NonNull String username) { + Optional userCredentialOptional = userCredentialRepository.findByUserName(username); + + if (!userCredentialOptional.isPresent()) { + throw new UserNotFoundException("Unable to fine user in User Management service " ); + } else { + userCredentialRepository.delete(userCredentialOptional.get()); + } + } + + /** + * @param customUserUpdateDTO + */ + public void updateUser(CustomUserUpdateDTO customUserUpdateDTO){ + List userRepresentationList = getUserDetails(customUserUpdateDTO.getUsername()); + + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> customUserUpdateDTO.getUsername().equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + + if (!userRepresentationOptional.isPresent()) { + throw new UserNotFoundException("Unable to find user in keycloak " + customUserUpdateDTO.getUsername()); + } + + UserRepresentation user = new UserRepresentation(); + user.setFirstName(customUserUpdateDTO.getFirstName()); + user.setLastName(customUserUpdateDTO.getLastName()); + + UserResource userResource = getSystemUsersResource().get(userRepresentationOptional.get().getId()); + userResource.update(user); + + assignRole(customUserUpdateDTO.getRoleNames(), userRepresentationOptional.get().getId()); + } + } + + private void assignRole(List roleNames, String userId) { + if (roleNames != null && !roleNames.isEmpty()) { + List roleToAdd = new LinkedList<>(); + + for (String roleName : roleNames) { + try { + + RoleRepresentation roleRepresentation = systemKeycloak.realm(valueMapper.getRealm()) + .roles() + .get(roleName) + .toRepresentation(); + + roleToAdd.add(roleRepresentation); + } catch (NotFoundException exception) { + throw new RoleNotFoundException("Role name list is not valid"); + } + } + + UserResource user = getSystemUsersResource().get(userId); + + List roleRepresentationList = user.roles().realmLevel().listEffective(); + user.roles().realmLevel().remove(roleRepresentationList); + user.roles().realmLevel().add(roleToAdd); + } + } + + public CustomUserResponseDTO createCustomUser(CustomUserDTO customUserDTO) { + if (customUserDTO != null && !StringUtils.isEmpty(customUserDTO.getUsername())) { + if (isUserExist(customUserDTO.getUsername())) { + throw new UserConflictException("User is already exist in user management in DB"); + } + + CustomUserResponseDTO customUserResponseDTO = CustomUserResponseDTO.builder() + .email(customUserDTO.getEmail()) + .firstName(customUserDTO.getFirstName()) + .lastName(customUserDTO.getLastName()) + .roleName(customUserDTO.getRoleName()) + .build(); + + UserRepresentation userRepresentation = new UserRepresentation(); + userRepresentation.setUsername(customUserDTO.getUsername()); + userRepresentation.setFirstName(customUserDTO.getFirstName()); + userRepresentation.setLastName(customUserDTO.getLastName()); + userRepresentation.setEmail(customUserDTO.getEmail()); + userRepresentation.setCredentials(Collections.singletonList(createPasswordCredentials(customUserDTO.getPassword()))); + userRepresentation.setEnabled(true); + + try { + Response response = getSystemUsersResource().create(userRepresentation); + + if (response.getStatus() == HttpStatus.CREATED.value()) { + String userId = assignCustomUserRole(customUserDTO); + persistUserDetailsWithCredentials(customUserDTO); + + customUserResponseDTO.setUserId(userId); + customUserResponseDTO.setStatus("User has been created successfully - mail in progress"); + mailService.sendUserCreationNotification(customUserDTO); + + return customUserResponseDTO; + } else { + LOGGER.error("Unable to create user, systemKeycloak response - " + response.getStatusInfo()); + throw new KeycloakUserException("Unable to create user in keycloak directory: " + response.getStatusInfo()); + } + } catch (Exception e) { + LOGGER.error("Unable to create user in systemKeycloak", e.getMessage()); + throw new KeycloakUserException("Unable to create user - error message: " + e.getMessage()); + } + } else { + throw new InvalidInputDataException("Invalid input for user creation"); + } + } + + + public boolean isUserExist(@NonNull String username) { + Optional userCredentialOptional = userCredentialRepository.findByUserName(username); + if (userCredentialOptional.isPresent()) { + return true; + } else { + return false; + } + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/utils/CipherEncoder.java b/java/user-management/src/main/java/dev/sunbirdrc/utils/CipherEncoder.java new file mode 100644 index 000000000..db0658f70 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/utils/CipherEncoder.java @@ -0,0 +1,97 @@ +package dev.sunbirdrc.utils; + +import dev.sunbirdrc.config.PropertiesValueMapper; +import dev.sunbirdrc.exception.CipherEncoderException; +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.*; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.spec.KeySpec; + + +@Component +public class CipherEncoder { + private static final Logger LOGGER = LoggerFactory.getLogger(CipherEncoder.class); + @Autowired + private PropertiesValueMapper valueMapper; + + private static byte[] IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + private static IvParameterSpec IV_SPEC = new IvParameterSpec(IV); + + /** + * @param text + * @return + */ + public String encodeText(String text) { + if (StringUtils.hasText(text)) { + byte[] keyBytes = valueMapper.getCustomUserCredentialSecretKey().getBytes(); + SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); + + try { + Cipher cipher = Cipher.getInstance(valueMapper.getCustomUserCipherProviderAlgorithm()); + + cipher.init(Cipher.ENCRYPT_MODE, getKey(), IV_SPEC); + byte[] cipherText = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8)); + + return Base64.encodeBase64URLSafeString(cipherText); + + } catch (Exception e) { + throw new CipherEncoderException("Invalid input while encoding"); + } + } else { + throw new CipherEncoderException("Invalid input while encoding"); + } + } + + /** + * @param text + * @return + */ + public String decodeText(String text) { + if (StringUtils.hasText(text)) { + byte[] keyBytes = valueMapper.getCustomUserCredentialSecretKey().getBytes(); + SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); + + try { + Cipher cipher = Cipher.getInstance(valueMapper.getCustomUserCipherProviderAlgorithm()); + + cipher.init(Cipher.DECRYPT_MODE, getKey(), IV_SPEC); + + String decodeStr = URLDecoder.decode(text, StandardCharsets.UTF_8); + byte[] base64decodedToken = Base64.decodeBase64(decodeStr.getBytes(StandardCharsets.UTF_8)); + byte[] decryptedText = cipher.doFinal(base64decodedToken); + + return new String(decryptedText); + + } catch (Exception e) { + throw new CipherEncoderException("Invalid input while encoding"); + } + } else { + throw new CipherEncoderException("Invalid input while encoding"); + } + } + + private Key getKey() throws Exception { + SecretKeyFactory factory = SecretKeyFactory.getInstance(UserConstant.SECRET_KEY_FACTORY_ALGO); + + KeySpec spec = new PBEKeySpec(valueMapper.getCustomUserCredentialSecretKey().toCharArray(), + UserConstant.CUSTOM_USER_KEY_SALT.getBytes(), 65536, 128); + + SecretKey tmp = factory.generateSecret(spec); + SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); + return secret; + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/utils/OtpUtil.java b/java/user-management/src/main/java/dev/sunbirdrc/utils/OtpUtil.java new file mode 100644 index 000000000..72f3a98da --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/utils/OtpUtil.java @@ -0,0 +1,80 @@ +package dev.sunbirdrc.utils; + +import dev.sunbirdrc.config.PropertiesValueMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; + +@Component +public class OtpUtil { + + @Autowired + private PropertiesValueMapper propMapping; + + @Autowired + private RedisUtil redisUtil; + + /** + * @param userId + * @return + */ + public Optional generateAndPersistOTP(String userId, TimeUnit timeUnit) throws Exception { + Integer otp = null; + + if (StringUtils.hasText(userId)) { + otp = ThreadLocalRandom.current().nextInt(100000, 999999); + redisUtil.putValueWithExpireTime(userId, String.valueOf(otp), propMapping.getOtpTtlDuration(), timeUnit); + } else { + throw new Exception("Invalid user id to generate OTP"); + } + + return Optional.ofNullable(otp); + } + + /** + * @param userId + * @param otp + * @return + */ + public boolean verifyUserMailOtp(String userId, String otp) { + if (!StringUtils.isEmpty(userId) && otp != null && !otp.equals(0)) { + String cachedOtp = redisUtil.getValue(userId); + + return otp.equals(cachedOtp); + } + + return false; + } + + + /** + * @return + * @throws Exception + */ + public TimeUnit getOtpTimeUnit() throws Exception { + TimeUnit timeUnit = null; + + switch (propMapping.getOtpTimeUnit()) { + case "SECOND": + timeUnit = TimeUnit.SECONDS; + break; + case "MINUTE": + timeUnit = TimeUnit.MINUTES; + break; + case "HOUR": + timeUnit = TimeUnit.HOURS; + break; + case "DAY": + timeUnit = TimeUnit.DAYS; + break; + default: + throw new Exception("Invalid time unit value"); + } + + return timeUnit; + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/utils/RedisUtil.java b/java/user-management/src/main/java/dev/sunbirdrc/utils/RedisUtil.java new file mode 100644 index 000000000..f276d894a --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/utils/RedisUtil.java @@ -0,0 +1,36 @@ +package dev.sunbirdrc.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.types.RedisClientInfo; +import org.springframework.stereotype.Component; + +import java.util.concurrent.TimeUnit; + +@Component +public class RedisUtil { + Logger logger = LoggerFactory.getLogger(this.getClass()); + @Autowired + @Qualifier("customRedis") + private RedisTemplate customRedis; + + public void putValue(String key, String value) { + customRedis.opsForValue().set(key, value); + } + + public void putValueWithExpireTime(String key, String value, long timeout, TimeUnit unit) { + RedisClientInfo redisClientInfo = customRedis.getClientList().get(0); + + logger.info(">>>>>>>>>>>>>>> redis client info: " + redisClientInfo); + logger.info(">>>>>>>>>>>>>>>>> address: " + redisClientInfo.getAddressPort() ); + + customRedis.opsForValue().set(key, value, timeout, unit); + } + + public String getValue(String key) { + return customRedis.opsForValue().get(key); + } +} diff --git a/java/user-management/src/main/java/dev/sunbirdrc/utils/UserConstant.java b/java/user-management/src/main/java/dev/sunbirdrc/utils/UserConstant.java new file mode 100644 index 000000000..41d3a6189 --- /dev/null +++ b/java/user-management/src/main/java/dev/sunbirdrc/utils/UserConstant.java @@ -0,0 +1,17 @@ +package dev.sunbirdrc.utils; + +public class UserConstant { + private UserConstant(){} + + public final static String VERIFY_MAIL_ACTION = "VERIFY_EMAIL"; + public final static String UPDATE_PASSWORD_ACTION = "UPDATE_PASSWORD"; + public final static String ADMIN_ROLE = "admin"; + public final static String ROLL_NO = "roll No"; + public final static String INSTITUTE_ID = "institute id"; + public final static String INSTITUTE_NAME = "institute name"; + public final static String PHONE_NUMBER = "phone no"; + public final static String STUDENT = "Student"; + + public final static String CUSTOM_USER_KEY_SALT = "#UPSMF#"; + public final static String SECRET_KEY_FACTORY_ALGO = "PBKDF2WithHmacSHA1"; +} diff --git a/java/user-management/src/main/resources/application.properties b/java/user-management/src/main/resources/application.properties new file mode 100644 index 000000000..46fb7f5c9 --- /dev/null +++ b/java/user-management/src/main/resources/application.properties @@ -0,0 +1,76 @@ +server.port=8001 + +#keycloak.auth-server-url=http://localhost:8080/auth +#keycloak.resource=demo-app +#keycloak.public-client=true + +spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry} +spring.datasource.username=${connectionInfo_username:postgres} +spring.datasource.password=${connectionInfo_password:postgres} + +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=update + +sunbirdrc.url=${sunbirdrc_url:http://localhost:8081} +spring.mail.host=smtp.gmail.com +spring.mail.port=465 +spring.mail.username=upsmf.otp@upsmfac.org +spring.mail.password=####### +spring.mail.properties.mail.smtp.ssl.enable = true + +# Other properties +spring.mail.properties.mail.debug=true +spring.mail.properties.mail.transport.protocol=smtp +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.connectiontimeout=50000000 +spring.mail.properties.mail.smtp.timeout=15000000 +spring.mail.properties.mail.smtp.writetimeout=150000000 + +# TLS , port 587 +spring.mail.properties.mail.smtp.starttls.enable=true + +#Keycloak config +keycloak.server.url=http://localhost:8080/auth +keycloak.realm=sunbird-rc +keycloak.confidential.client.id=admin-api +keycloak.public.client.id=admin-cli +keycloak.client.secret=f0b65ce0-b00e-4923-b4cb-ef897ca6f59c +#keycloak.client.secret=95d172f6-8b9a-4083-b6dc-ddc422ff1c36 +keycloak.username=admin +keycloak.password=admin +keycloak.token.url=http://localhost:8080/auth/realms/sunbird-rc/protocol/openid-connect/token + +spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/auth/realms/sunbird-rc + +#Mail config +otp.mail.verification.subject = OTP Verification Mail +otp.mail.verification.personal.name = UPSMF User +otp.mail.verification.from.address = upsmf.otp@upsmfac.org + +custom.user.creation.subject = User Creation Notification +custom.user.creation.personal.name = UPSM Creator +custom.user.creation.from.address = upsmf.otp@upsmfac.org + +#OTP config - time unit details - SECOND, MINUTE, HOUR, DAY +otp.ttl.duration=10 +otp.time.unit=HOUR + +#Redis Config +#spring.redis.host=127.0.0.2 +#spring.redis.password=password +#spring.redis.port=6379 + +custom.redis.host=127.0.0.1 +custom.redis.port=6379 + +logging.level.org.springframework.web=TRACE +logging.level.org.keycloak=TRACE + +#server.error.include-message=always +#server.error.include-binding-errors=always + +custom.user.login.url=http://localhost:8001/api/v1/login +bulk.user.size.limit=10 + +custom.user.credential.secret.key=dXBzbWZfdXNlcl9jcmVkX3NlY3JldA +custom.user.cipher.provider.algorithm=AES/CBC/PKCS5Padding diff --git a/java/user-management/src/main/resources/templates/otp-verification-mail.ftl b/java/user-management/src/main/resources/templates/otp-verification-mail.ftl new file mode 100644 index 000000000..fd51bd917 --- /dev/null +++ b/java/user-management/src/main/resources/templates/otp-verification-mail.ftl @@ -0,0 +1,16 @@ + + +

Hi ${userFirstName} ${userLastName}

+ +

Use the following one-time password (OTP) to complete identity verification.

+ +

${otp}

+ +

If you didn't initiate this action or if you think you received this email by mistake, please contact support@upsmf.com.

+

This OTP will be valid for ${otpDuration} ${timeUnit}

+ +

Regards,

+

${signature}

+

${location}

+ + diff --git a/java/user-management/src/main/resources/templates/user-creation-notification-mail.ftl b/java/user-management/src/main/resources/templates/user-creation-notification-mail.ftl new file mode 100644 index 000000000..2e6053cd2 --- /dev/null +++ b/java/user-management/src/main/resources/templates/user-creation-notification-mail.ftl @@ -0,0 +1,13 @@ + + +

Hi ${userFirstName} ${userLastName}

+ +

Your account has been created. Please find below link for login

+ +

${loginLInk}

+ + +

Regards,

+

${signature}

+ + From 18fb1e751b36230a6f479ab48d95c22020db5404 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Fri, 18 Aug 2023 19:09:41 +0530 Subject: [PATCH 21/43] digilocker implementation --- .../registry/config/SecurityConfig.java | 4 +- .../controller/RegistryEntityController.java | 396 ++++++++++++---- .../digilocker/pulldoc/DocDetailsType.java | 23 +- .../digilocker/pulldoc/PullDocRequest.java | 19 + .../service/ElasticSearchService.java | 8 +- .../registry/service/ICertificateService.java | 2 +- .../registry/service/ISearchService.java | 12 +- .../service/impl/CertificateServiceImpl.java | 48 +- .../registry/util/ClaimRequestClient.java | 29 +- .../registry/util/DateParsingExample.java | 18 + .../registry/util/DigiLockerUtils.java | 153 +++++- .../sunbirdrc/registry/util/DocDetails.java | 22 +- .../src/main/resources/application.yml | 2 +- .../resources/public/_schemas/Student.json | 29 +- .../_schemas/studentForeignVerification.json | 6 +- .../public/_schemas/studentFromUP.json | 129 ++++-- .../public/_schemas/studentFromUPDegree.json | 435 ++++++++++++++++++ .../public/_schemas/studentGoodStanding.json | 8 +- .../public/_schemas/studentOutsideUp.json | 29 +- .../RegistryEntityControllerTest.java | 4 +- .../config/config.go | 4 +- .../config/application-default.yml | 6 +- .../pkg/services/mail_service.go | 7 +- 23 files changed, 1194 insertions(+), 199 deletions(-) create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/DateParsingExample.java create mode 100644 java/registry/src/main/resources/public/_schemas/studentFromUPDegree.json diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SecurityConfig.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SecurityConfig.java index a93880853..17488176b 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SecurityConfig.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SecurityConfig.java @@ -62,10 +62,10 @@ protected void configure(HttpSecurity http) throws Exception { .antMatchers("/**/invite", "/health", "/error", "/_schemas/**", "/**/templates/**", "/**/*.json", "/**/verify", "/swagger-ui", "/**/search", "/**/attestation/**", - "/api/docs/swagger.json","/api/docs/*.json", "/plugin/**", "/swagger-ui.html") + "/api/docs/swagger.json","/api/docs/*.json", "/plugin/**", "/swagger-ui.html","/api/v1/pullUriRequest/*","/api/v1/pullDocUriRequest/*") .permitAll() .and() - .addFilterBefore(schemaFilter, WebAsyncManagerIntegrationFilter.class) + //.addFilterBefore(schemaFilter, WebAsyncManagerIntegrationFilter.class) .authorizeRequests() .anyRequest() .authenticated(); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 84cd13469..49e1c25f4 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -10,6 +10,8 @@ import dev.sunbirdrc.pojos.PluginResponseMessage; import dev.sunbirdrc.pojos.Response; import dev.sunbirdrc.pojos.ResponseParams; +import dev.sunbirdrc.registry.dao.Credential; +import dev.sunbirdrc.registry.dao.Learner; import dev.sunbirdrc.registry.digilocker.pulldoc.PullDocRequest; import dev.sunbirdrc.registry.digilocker.pulldoc.PullDocResponse; import dev.sunbirdrc.registry.digilocker.pulluriresponse.Person; @@ -23,6 +25,7 @@ import dev.sunbirdrc.registry.middleware.util.Constants; import dev.sunbirdrc.registry.middleware.util.JSONUtil; import dev.sunbirdrc.registry.middleware.util.OSSystemFields; +import dev.sunbirdrc.registry.model.dto.MailDto; import dev.sunbirdrc.registry.service.FileStorageService; import dev.sunbirdrc.registry.service.impl.CertificateServiceImpl; import dev.sunbirdrc.registry.transform.Configuration; @@ -52,6 +55,7 @@ import javax.servlet.http.HttpServletRequest; import java.io.IOException; +import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.*; @@ -63,13 +67,17 @@ public class RegistryEntityController extends AbstractController { private static final String TRANSACTION_ID = "transactionId"; private static Logger logger = LoggerFactory.getLogger(RegistryEntityController.class); + + @Value("${Logo.imgBaseUri:https://casa.upsmfac.org/UploadedFiles/Student/}") + private String imgBaseUri; @Value("${GCS_SERVICE_URL:https://casa.upsmfac.org/UploadedFiles/Student/}") public static final String GCS_SERVICE_URL = "http://34.100.212.156:8082/"; @Value("${digilocker_hmackey:}") - public static final String DIGILOCKER_KEY = "vTV3Jl81kXDOca70TT2+P/YAb5DXnS+DDr/ArlFhow0="; + public static final String DIGILOCKER_KEY = "84600d73-e618-4c80-a347-6b51147103ee"; @Autowired private CertificateServiceImpl certificateService; - + @Value("${Logo.imgFormat:.jpg}") + private String imgFormat; @Autowired private FileStorageService fileStorageService; @@ -571,13 +579,14 @@ public ResponseEntity getEntityType(@PathVariable String entityName, // JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); String templateUrlFromRequest = getTemplateUrlFromRequest(request, entityName); - + String fileName = ""; return new ResponseEntity<>(certificateService.getCertificate(node, entityName, entityId, request.getHeader(HttpHeaders.ACCEPT), templateUrlFromRequest, - JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)) + JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)), + fileName, false ), HttpStatus.OK); } catch (Exception exception) { exception.printStackTrace(); @@ -590,9 +599,9 @@ private String getTemplateUrlFromRequest(HttpServletRequest request, String enti String template = Template; if(entityName.equalsIgnoreCase("StudentForeignVerification")){ - return "StudentForeignVerificationTemp"; + return "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate"; } else if (entityName.equalsIgnoreCase("StudentGoodstanding")) { - return "StudentGoodStandingTemp"; + return "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding"; } if (externalTemplatesEnabled && !StringUtils.isEmpty(request.getHeader(template))) { @@ -912,20 +921,79 @@ public ResponseEntity getSignedEntityByToken(@PathVariable String entity public ResponseEntity getAttestationCertificate(HttpServletRequest request, @PathVariable String entityName, @PathVariable String entityId, @PathVariable String attestationName, @PathVariable String attestationId) { ResponseParams responseParams = new ResponseParams(); + Object certificate = null; + boolean wc = false; try { checkEntityNameInDefinitionManager(entityName); String readerUserId = getUserId(entityName, request); - JsonNode node = registryHelper.readEntity(readerUserId, entityName, entityId, false, null, false) - .get(entityName).get(attestationName); + JsonNode jsonNode = registryHelper.readEntity(readerUserId, entityName, entityId, false, null, false) + .get(entityName); + JsonNode node = jsonNode.get(attestationName); + String fileName = getFileNameOfCredentials(node); + JsonNode credentialsType = node.get("credType"); + generateImageURL(jsonNode); JsonNode attestationNode = getAttestationSignedData(attestationId, node); - return new ResponseEntity<>(certificateService.getCertificate(attestationNode, + certificate = certificateService.getCertificate(attestationNode, entityName, entityId, request.getHeader(HttpHeaders.ACCEPT), getTemplateUrlFromRequest(request, entityName), - getAttestationNode(attestationId, node) - ), HttpStatus.OK); + getAttestationNode(attestationId, node), + fileName, wc + ); + return new ResponseEntity<>(certificate, HttpStatus.OK); + } catch (RecordNotFoundException re) { + createSchemaNotFoundResponse(re.getMessage(), responseParams); + Response response = new Response(Response.API_ID.GET, "ERROR", responseParams); + try { + return new ResponseEntity<>(objectMapper.writeValueAsString(response), HttpStatus.NOT_FOUND); + } catch (JsonProcessingException e) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + } catch (AttestationNotFoundException e) { + logger.error(e.getMessage()); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } catch (Exception e) { + e.printStackTrace(); + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + } + + @GetMapping(value = "/api/v2/{entityName}/{entityId}/attestation/{attestationName}/{attestationId}", + produces = {MediaType.APPLICATION_PDF_VALUE, MediaType.TEXT_HTML_VALUE, Constants.SVG_MEDIA_TYPE, MediaType.APPLICATION_JSON_VALUE}) + public ResponseEntity getAttestationCertificateGCS(HttpServletRequest request, @PathVariable String entityName, @PathVariable String entityId, + @PathVariable String attestationName, @PathVariable String attestationId) { + ResponseParams responseParams = new ResponseParams(); + Object certificate = null; + try { + String checkIfAlreadyExists = "issuance/"+entityId+".pdf"; + certificate = certificateService.getCred(checkIfAlreadyExists); + if(certificate == null || request.getHeader("correction")==null) + { + checkEntityNameInDefinitionManager(entityName); + String readerUserId = getUserId(entityName, request); + JsonNode jsonNode = registryHelper.readEntity(readerUserId, entityName, entityId, false, null, false) + .get(entityName); + JsonNode node = jsonNode.get(attestationName); + String fileName = getFileNameOfCredentials(node); + boolean wc = false; + JsonNode attestationNode = getAttestationSignedData(attestationId, node); + certificate = certificateService.getCertificate(attestationNode, + entityName, + entityId, + request.getHeader(HttpHeaders.ACCEPT), + getTemplateUrlFromRequest(request, entityName), + getAttestationNode(attestationId, node), + fileName, wc + ); + if(certificate!=null){ + String url = getCredUrl(fileName, certificate); + if(url != null){ + shareCredentials(node, url); + }} + } + return new ResponseEntity<>(certificate, HttpStatus.OK); } catch (RecordNotFoundException re) { createSchemaNotFoundResponse(re.getMessage(), responseParams); Response response = new Response(Response.API_ID.GET, "ERROR", responseParams); @@ -942,6 +1010,8 @@ public ResponseEntity getAttestationCertificate(HttpServletRequest reque return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } + + @RequestMapping(value = "/api/v1/{entityName}/{entityId}/revoke", method = RequestMethod.POST) public ResponseEntity revokeACredential ( HttpServletRequest request, @@ -1002,13 +1072,10 @@ private JsonNode getAttestationNode1(String attestationId, JsonNode node) { * @param entityName * @return */ + @CrossOrigin (origins = "*") @RequestMapping(value = "/api/v1/pullUriRequest/{entityName}", method = RequestMethod.POST, produces = {MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_PDF_VALUE, MediaType.TEXT_HTML_VALUE, Constants.SVG_MEDIA_TYPE}) public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest request, @PathVariable String entityName) { - - //String entityName = "RegCertificate"; - take entity name from input - TODO - // call template TODO - String templateurl = null; String statusCode = "1"; Scanner scanner = null; try { @@ -1016,82 +1083,46 @@ public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest re } catch (IOException e) { throw new RuntimeException(e); } - String xmlString = null; + String searchQuery = null; if(scanner!=null){ Scanner scanner1 = scanner.useDelimiter("\\A"); if(scanner1.hasNext()) - xmlString = scanner1.next(); + searchQuery = scanner1.next(); } DocDetails docDetails = null; // Map to JAXB - xmlString = DigiLockerUtils.getXmlString(xmlString); - //request.set - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.SEARCH, "OK", responseParams); - String osid = null; - JsonNode result = null; - try{ - String userId = registryHelper.getUserId(request, entityName); - JsonNode responseFromDb = registryHelper.searchEntitiesByUserId(entityName, userId, null); - JsonNode entities = responseFromDb.get(entityName); - } catch (Exception e) { - statusCode = "0"; - e.printStackTrace(); - return new ResponseEntity<>(statusCode, HttpStatus.INTERNAL_SERVER_ERROR); - } - - -// ResponseEntity objectResponseEntity = getObjectResponseEntity(entityName, request, null, responseParams, response); - -// try { -// result = registryHelper.getRequestedUserDetailsCustom(request, entityName, xmlString); -// if (result != null && result.get(entityName) != null && result.get(entityName).size() > 0) { -// ArrayNode responseFromDb = registryHelper.fetchFromDBUsingEsResponse(entityName, (ArrayNode) result.get(entityName)); -// if(responseFromDb!=null && responseFromDb.size() > 0){ -// osid = responseFromDb.get(0).get("osid").asText(); -// } -// } -// } catch (Exception e) { -// statusCode = "0"; -// e.printStackTrace(); -// return new ResponseEntity<>(statusCode, HttpStatus.INTERNAL_SERVER_ERROR); -// } + ObjectNode searchNode = DigiLockerUtils.getJsonQuery(searchQuery); + JsonNode result = searchEntity(searchNode, entityName); + JsonNode jsonNode = result.get(entityName); + String osid = jsonNode!=null?jsonNode.get(0).get("osid").asText():null; if(osid!=null) { try { - String readerUserId = getUserId(entityName, request); - JsonNode node = registryHelper.readEntity(readerUserId, entityName, osid, false, null, false) - .get(entityName); - String fileName = DigiLockerUtils.getDocUri(); - Object certificate = null; - JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); - certificate = certificateService.getCred(fileName + ".PDF"); - - if(certificate == null){ - certificate = certificateService.getCertificateForDGL(signedNode, - entityName, - osid, - MediaType.APPLICATION_PDF_VALUE, - getTemplateUrlFromRequest(request, entityName), - JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)), fileName - ); - - certificateService.saveToGCS(certificate, fileName); + String uri = DigiLockerUtils.getDocUri(); + String fileName = "issuance/"+osid+".pdf"; + Object certificate = certificateService.getCred(fileName); + if(certificate!=null){ + certificateService.saveforDGL(certificate, uri); + Person person = DigiLockerUtils.getPersonDetail(result, entityName); + PullURIResponse pullResponse = DigiLockerUtils.getPullUriResponse(uri, statusCode, osid, certificate, person); + String responseString = DigiLockerUtils.convertJaxbToString(pullResponse); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_XML); + return new ResponseEntity<>(responseString, headers, HttpStatus.OK); + }else{ + statusCode = "0"; + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); } - Person person = DigiLockerUtils.getPersonDetail(result, entityName); - PullURIResponse pullResponse = DigiLockerUtils.getPullUriResponse(fileName, statusCode, osid, certificate, person); - String responseString = DigiLockerUtils.convertJaxbToString(pullResponse); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_XML); - return new ResponseEntity<>(responseString, headers, HttpStatus.OK); + } catch (Exception exception) { statusCode = "0"; exception.printStackTrace(); - return new ResponseEntity<>(statusCode, HttpStatus.BAD_REQUEST); + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); } } else{ - return new ResponseEntity<>(statusCode, HttpStatus.FORBIDDEN); + statusCode = "0"; + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); } } @@ -1105,12 +1136,9 @@ public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest re @RequestMapping(value = "/api/v1/pullDocUriRequest/{entityName}", method = RequestMethod.POST, produces = {MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_XML_VALUE}) public ResponseEntity pullDocURI(HttpServletRequest request) { - - String entityName = "StudentFromUP"; //- take entity name from input - TODO String statusCode = "1"; Scanner scanner = null; - String hmac = request.getHeader("x-digilocker-hmac"); - + String hmac = request.getHeader("hmac"); try { scanner = new Scanner(request.getInputStream(), "UTF-8"); } catch (IOException e) { @@ -1122,8 +1150,6 @@ public ResponseEntity pullDocURI(HttpServletRequest request) { if(scanner1.hasNext()) xmlString = scanner1.next(); } - - // GET Request xml and create object PullDocRequest pullDocRequest = null; try { pullDocRequest = DigiLockerUtils.processPullDocRequest(xmlString); @@ -1131,31 +1157,46 @@ public ResponseEntity pullDocURI(HttpServletRequest request) { throw new RuntimeException(e); } boolean isValidReq = DigiLockerUtils.verifyHmac(pullDocRequest.getTs(), DIGILOCKER_KEY, hmac); - if(!isValidReq){ +// if(isValidReq){ +// statusCode = "0"; +// HttpHeaders headers = new HttpHeaders(); +// headers.setContentType(MediaType.APPLICATION_XML); +// return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); +// } + String fullName = pullDocRequest.getDocDetails().getFullName(); + String dob = pullDocRequest.getDocDetails().getDob(); + JsonNode searchNode = DigiLockerUtils.getQuryNode(fullName, dob); + JsonNode result = searchEntityForDGL((ObjectNode)searchNode); + if(result==null){ statusCode = "0"; - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_XML); - return new ResponseEntity<>(statusCode, HttpStatus.FORBIDDEN); + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); } String credName = pullDocRequest.getDocDetails().getUri(); + credName = "issuance/"+credName+".pdf"; byte[] cred = certificateService.getCred(credName); - JsonNode result = null; + // get stident by osid String osid = pullDocRequest.getTxn(); - try { - result = registryHelper.getUserInfoFromRegistryByOsId(request, entityName, osid); - Person person = DigiLockerUtils.getPersonDetail(result, entityName); - PullDocResponse pullDocResponse = DigiLockerUtils.getDocPullUriResponse(osid,statusCode, cred,person); - Object responseString = DigiLockerUtils.convertJaxbToPullDoc(pullDocResponse); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_XML); - return new ResponseEntity<>(responseString, headers, HttpStatus.OK); - } catch (Exception e) { + if(cred!=null){ + try { + //DigiLockerUtils.getPersonDetail(result, "entityName"); + Person person = new Person(); + person.setDob(dob); + person.setDob(fullName); + PullDocResponse pullDocResponse = DigiLockerUtils.getDocPullUriResponse(osid,statusCode, cred,person); + Object responseString = DigiLockerUtils.convertJaxbToPullDoc(pullDocResponse); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_XML); + return new ResponseEntity<>(responseString, headers, HttpStatus.OK); + } catch (Exception e) { + statusCode = "0"; + e.printStackTrace(); + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); + } + }else{ statusCode = "0"; - e.printStackTrace(); - return new ResponseEntity<>(statusCode, HttpStatus.FORBIDDEN); + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); } - } /** @@ -1165,7 +1206,8 @@ public ResponseEntity pullDocURI(HttpServletRequest request) { * @param request * @return */ - @RequestMapping(value = "/api/v1/{entityName}/{entityId}/upload/multi-files", method = RequestMethod.PUT) + @CrossOrigin(origins = "*") + @RequestMapping(value = "/api/v1/{entityName}/{entityId}/upload/multi-files", method = RequestMethod.POST) public ResponseEntity putMultiEntityFiles( @PathVariable String entityName, @PathVariable String entityId, @@ -1183,10 +1225,13 @@ public ResponseEntity putMultiEntityFiles( try { List fileUrlList = certificateService.uploadMultiEntityDocFiles(files, entityName, entityId); + StringBuffer fileString = new StringBuffer(); + for (String str :fileUrlList ) { + fileString.append(str+","); + } Response response = new Response(Response.API_ID.CREATE, HttpStatus.OK.name(), responseParams); - response.setResult(fileUrlList); - + response.setResult(fileString.toString()); responseParams.setErrmsg(""); responseParams.setStatus(Response.Status.SUCCESSFUL); @@ -1202,6 +1247,7 @@ public ResponseEntity putMultiEntityFiles( } } + @CrossOrigin(origins = "*") @RequestMapping(value = "/api/v1/{entityName}/{entityId}/upload/file", method = RequestMethod.PUT) public ResponseEntity putSingleEntityFile( @PathVariable String entityName, @@ -1239,4 +1285,152 @@ public ResponseEntity putSingleEntityFile( } } + private String getFileNameOfCredentials(JsonNode node) { + StringBuffer fileName = new StringBuffer(); + String name = node.get(0).get("entityId").toString().replace(" ",""); + name = name.replace("\"",""); + fileName.append(name); + return fileName.toString(); + } + + private void trackCred(JsonNode node, String fileName) { + try { + // Track Credentials creation + JsonNode name = node.get("name"); + JsonNode credentialsType = node.get("credType"); + JsonNode course = node.get("course"); + JsonNode rollNumber = node.get("rollNumber"); + JsonNode regNumber = node.get("regNumber"); + + Learner learner = new Learner(); + learner.setName(name!=null?name.asText():null); + learner.setEnrollmentNumber(regNumber!=null?regNumber.asText():""); + learner.setRollNumber(rollNumber!=null?rollNumber.asText():""); + + Credential cred = new Credential(); + cred.setCourse(course!=null?course.asText():""); + cred.setCredentialName(credentialsType!=null?credentialsType.asText():""); + cred.setCredentialURL(fileName); + List list = new ArrayList<>(); + list.add(cred); + learner.setCredentialsList(list); + certificateService.trackCredentials(learner); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private String generateImageURL(JsonNode rootNode) { + JsonNode rollNumber = rootNode.get("finalYearRollNo"); + JsonNode enrollmentNumber = rootNode.get("enrollmentNumber"); + JsonNode examYear = rootNode.get("examYear"); + ObjectNode node = (ObjectNode) rootNode; + String url = imgBaseUri; + if (examYear != null) + url = url.concat(examYear.asText()); + if (enrollmentNumber != null) { + url = url.concat("/E" + enrollmentNumber.asText()); + } else if (rollNumber != null) { + url = url.concat("/rp" + rollNumber.asText()); + node.put("candidatePic", url); + } + logger.debug("Generated Img url::" + url); + return url; + } + + @Nullable + private String getCredUrl(final String entityId, Object certificate) throws Exception { + String url = null; + try { + url = getCertificate(entityId, certificate); + } catch (Exception e) { + throw new Exception(e); + } + return url; + } + + @Nullable + private String getCertificate(String entityId, Object certificate) throws Exception { + String url = null; + if (certificate != null) { + logger.info("Credentials generation for EntityId:"+entityId); + url = certificateService.saveToGCS(certificate, entityId); + logger.debug("Final url credentials:"+url); + } + return url; + } + private void shareCredentials(JsonNode node, String url) { + try { + // Mail Send Functionality -Start + JsonNode email = node.get("email"); + JsonNode name = node.get("name"); + JsonNode credentialsType = node.get("credType"); + MailDto mail = new MailDto(); + if (mail != null && name != null) { + mail.setName(name.asText()); + mail.setEmailAddress(email.asText()); + mail.setCertificate(url); + if (credentialsType != null) { + mail.setCredentialsType(credentialsType.asText()); + } + certificateService.shareCertificateMail(mail); + // Mail Send Functionality End + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public JsonNode searchEntityForDGL(ObjectNode searchNode) { + JsonNode result = null; + String[] entityArr = {"StudentFromUP","StudentOutSideUP"}; + for (String entityName: entityArr) { + try { + ArrayNode entity = JsonNodeFactory.instance.arrayNode(); + entity.add(entityName); + searchNode.set(ENTITY_TYPE, entity); + checkEntityNameInDefinitionManager(entityName); + if (definitionsManager.getDefinition(entityName).getOsSchemaConfiguration().getEnableSearch()) { + result = registryHelper.searchEntity(searchNode); + watch.stop("RegistryController.searchEntity"); + if(result!=null || result.size() > 0) + return result; + } else { + watch.stop("RegistryController.searchEntity"); + logger.error("Searching on entity {} not allowed", entityName); + } + } catch (RecordNotFoundException e) { + return null; + } catch (Exception e) { + logger.error("Exception in controller while searching entities !", e); + } + } + + return result; + } + + public JsonNode searchEntity(ObjectNode searchNode, String entityName) { + JsonNode result = null; + try { + ArrayNode entity = JsonNodeFactory.instance.arrayNode(); + entity.add(entityName); + searchNode.set(ENTITY_TYPE, entity); + checkEntityNameInDefinitionManager(entityName); + if (definitionsManager.getDefinition(entityName).getOsSchemaConfiguration().getEnableSearch()) { + result = registryHelper.searchEntity(searchNode); + watch.stop("RegistryController.searchEntity"); + return result; + } else { + watch.stop("RegistryController.searchEntity"); + logger.error("Searching on entity {} not allowed", entityName); + } + } catch (RecordNotFoundException e) { + return null; + } catch (Exception e) { + logger.error("Exception in controller while searching entities !", e); + } + return result; + } + + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java index a31c2e8dc..a25de5fe5 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java @@ -6,7 +6,9 @@ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DocDetailsType", propOrder = { "uri", - "digiLockerId" + "digiLockerId", + "fullName", + "dob" }) public class DocDetailsType { @@ -14,6 +16,25 @@ public class DocDetailsType { protected String digiLockerId; + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getDob() { + return dob; + } + + public void setDob(String dob) { + this.dob = dob; + } + + protected String fullName; + + protected String dob; public String getUri() { return uri; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocRequest.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocRequest.java index 2cfc76d67..a3be753e0 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocRequest.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/PullDocRequest.java @@ -16,6 +16,25 @@ public class PullDocRequest { protected String orgId; protected String format; + public String getKeyhash() { + return keyhash; + } + + public void setKeyhash(String keyhash) { + this.keyhash = keyhash; + } + + public String getHmac() { + return hmac; + } + + public void setHmac(String hmac) { + this.hmac = hmac; + } + + protected String keyhash; + protected String hmac; + public DocDetailsType getDocDetails() { return docDetails; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java index 726c66d9d..d4b701e33 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ElasticSearchService.java @@ -58,7 +58,7 @@ public class ElasticSearchService implements ISearchService { @Override public JsonNode search(JsonNode inputQueryNode) throws IOException { - logger.debug("search request body = " + inputQueryNode); + logger.debug("search request body = " + inputQueryNode); SearchQuery searchQuery = getSearchQuery(inputQueryNode, offset, limit); @@ -89,8 +89,12 @@ public JsonNode search(JsonNode inputQueryNode) throws IOException { } try { - auditService.auditElasticSearch( new AuditRecord().setUserId(apiMessage.getUserID()), + String userID = apiMessage.getUserID(); + if (userID != null) { + auditService.auditElasticSearch(new AuditRecord().setUserId(userID), searchQuery.getEntityTypes(), inputQueryNode); + logger.info("No Audit Entry for Search::"+searchQuery.getEntityTypes()); + } } catch (Exception e) { logger.error("Exception while auditing " + e); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ICertificateService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ICertificateService.java index 4336fa9eb..409bdd3ef 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ICertificateService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ICertificateService.java @@ -4,5 +4,5 @@ import dev.sunbirdrc.pojos.HealthIndicator; public interface ICertificateService extends HealthIndicator { - Object getCertificate(JsonNode certificateData, String entityName, String entityId, String mediaType, String templateUrl, JsonNode entity); + Object getCertificate(JsonNode certificateData, String entityName, String entityId, String mediaType, String templateUrl, JsonNode entity, String fileName, boolean wc); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ISearchService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ISearchService.java index fcb7096de..220c660b4 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/ISearchService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/ISearchService.java @@ -62,12 +62,12 @@ default SearchQuery getSearchQuery(JsonNode inputQueryNode, int offset, int limi filterList.add(freeTextFilter); } -// try { -// searchQuery.setLimit(inputQueryNode.get("limit").asInt()); -// searchQuery.setOffset(inputQueryNode.get("offset").asInt()); -// } catch (Exception e) { -// logger.warn("Populates SearchQuery for limit/offset(optional): {}", e.getMessage()); -// } + try { + searchQuery.setLimit(inputQueryNode.get("limit").asInt()); + searchQuery.setOffset(inputQueryNode.get("offset").asInt()); + } catch (Exception e) { + logger.warn("Populates SearchQuery for limit/offset(optional): {}", e.getMessage()); + } searchQuery.setFilters(filterList); return searchQuery; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java index d6a964580..b78070670 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java @@ -2,9 +2,11 @@ import com.fasterxml.jackson.databind.JsonNode; import dev.sunbirdrc.pojos.ComponentHealthInfo; +import dev.sunbirdrc.registry.dao.Learner; import dev.sunbirdrc.registry.middleware.util.Constants; import dev.sunbirdrc.registry.model.dto.BarCode; import dev.sunbirdrc.registry.model.dto.FileDto; +import dev.sunbirdrc.registry.model.dto.MailDto; import dev.sunbirdrc.registry.service.ICertificateService; import dev.sunbirdrc.registry.util.ClaimRequestClient; import org.jetbrains.annotations.NotNull; @@ -62,9 +64,9 @@ public CertificateServiceImpl(@Value("${certificate.templateBaseUrl}") String te } @Override - public Object getCertificate(JsonNode certificateData, String entityName, String entityId, String mediaType, String templateUrl, JsonNode entity) { + public Object getCertificate(JsonNode certificateData, String entityName, String entityId, String mediaType, String templateUrl, JsonNode entity, String fileName, boolean wc) { try { - String finalTemplateUrl = inferTemplateUrl(entityName, mediaType, templateUrl); + String finalTemplateUrl = inferTemplateUrl(entityName, mediaType, templateUrl, wc); Map requestBody = new HashMap(){{ put("templateUrl", finalTemplateUrl); @@ -72,6 +74,7 @@ public Object getCertificate(JsonNode certificateData, String entityName, String put("entityId", entityId); put("entityName", entityName); put("entity", entity); + put("credentialsFileName",fileName); }}; HttpHeaders headers = new HttpHeaders(); headers.set("Accept", mediaType); @@ -85,7 +88,7 @@ public Object getCertificate(JsonNode certificateData, String entityName, String public Object getCertificateForDGL(JsonNode certificateData, String entityName, String entityId, String mediaType, String templateUrl, JsonNode entity, String fileName) { try { - String finalTemplateUrl = inferTemplateUrl(entityName, mediaType, templateUrl); + String finalTemplateUrl = inferTemplateUrl(entityName, mediaType, templateUrl, false); Map requestBody = new HashMap(){{ put("templateUrl", finalTemplateUrl); @@ -106,9 +109,13 @@ public Object getCertificateForDGL(JsonNode certificateData, String entityName, } @NotNull - private String inferTemplateUrl(String entityName, String mediaType, String templateUrl) { + private String inferTemplateUrl(String entityName, String mediaType, String templateUrl, boolean wc) { if (templateUrl == null) { - templateUrl = templateBaseUrl + entityName + getFileExtension(mediaType); + if(wc) + templateUrl = templateBaseUrl + entityName+"-wc.html"; + else{ + templateUrl = templateBaseUrl + entityName+".html"; + } } return templateUrl; } @@ -154,7 +161,14 @@ public String saveToGCS(Object certificate, String entityId) { logger.info("Uploading File GCP complete"); return url; } - +//saveFileToGCSForDGL +public String saveforDGL(Object certificate, String entityId) { + String url = null; + logger.info("Uploading File GCP."); + url = claimRequestClient.saveFileToGCSForDGL(certificate, entityId); + logger.info("Uploading File GCP complete"); + return url; +} public BarCode getBarCode(BarCode barCode) { BarCode node = null; try { @@ -232,4 +246,26 @@ public String uploadSingleEntityDocFiles(MultipartFile file, String entityName, return fileUrl.get(); } + + public void trackCredentials(Learner learner) { + try { + logger.info("Track Certificate start"); + claimRequestClient.saveCredentials(learner); + logger.info("Track Certificate end"); + } catch (Exception e) { + logger.error("Track certificate failed", e); + } + + } + + public void shareCertificateMail(MailDto mail) { + try { + logger.info("Sharing Certificate start"); + claimRequestClient.sendMail(mail); + logger.info("Sharing Certificate end"); + } catch (Exception e) { + logger.error("Get certificate failed", e); + } + + } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index d1c738af9..739aae38d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -123,6 +123,33 @@ public String getFilename() { return url; } + public String saveFileToGCSForDGL(Object certificate, String entityId) { + String fileName = entityId; + logger.info("Credentials File Name."+fileName); + String url = null; + byte[] bytes = convertObtToByte(certificate); + HttpHeaders headers = new HttpHeaders(); + if(bytes!=null){ + ByteArrayResource resource = new ByteArrayResource(bytes) { + @Override + public String getFilename() { + return fileName; + } + }; + ResponseEntity response = uploadFileToGCS(headers, resource); + switch (response.getStatusCode()){ + case OK: + url=response.getBody(); + break; + default: + break; + + } + } + logger.debug("Save to GCS successfully ..."+url); + return url; + } + @Nullable private ResponseEntity uploadFileToGCS(HttpHeaders headers, ByteArrayResource resource) { headers.setContentType(MediaType.MULTIPART_FORM_DATA); @@ -183,7 +210,7 @@ public byte[] getCredentials(String fileName) { // Add any required headers here headers.set("accept", "*/*"); ResponseEntity response = restTemplate.exchange( - builder.toUriString(), HttpMethod.GET, null, byte[].class, queryParams, headers + builder.toUriString(), HttpMethod.POST, null, byte[].class, queryParams, headers ); logger.info("end getCredentials ..."); return response.getBody(); } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DateParsingExample.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DateParsingExample.java new file mode 100644 index 000000000..bc88c4ee9 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DateParsingExample.java @@ -0,0 +1,18 @@ +package dev.sunbirdrc.registry.util; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +public class DateParsingExample { + public static void formatDate(String inputDateString) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + try { + LocalDate localDate = LocalDate.parse(inputDateString, formatter); + System.out.println("Parsed LocalDate: " + localDate); + } catch (DateTimeParseException e) { + System.out.println("Parsing error: " + e.getMessage()); + } + } +} + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java index 1034d70ab..91f2a336a 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java @@ -1,12 +1,27 @@ package dev.sunbirdrc.registry.util; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import dev.sunbirdrc.pojos.Response; +import dev.sunbirdrc.pojos.ResponseParams; import dev.sunbirdrc.registry.digilocker.pulldoc.*; import dev.sunbirdrc.registry.digilocker.pulluriresponse.*; import dev.sunbirdrc.registry.digilocker.pulluriresponse.DocDetails; +import dev.sunbirdrc.registry.exception.RecordNotFoundException; import dev.sunbirdrc.registry.middleware.util.DateUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -22,10 +37,12 @@ import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.List; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.*; + +import static dev.sunbirdrc.registry.middleware.util.Constants.ENTITY_TYPE; public class DigiLockerUtils { @@ -43,10 +60,10 @@ public static Person getPersonDetail(JsonNode result, String entityName) { JsonNode gender = regCertificate.get("gender"); if (gender != null) person.setGender(gender.asText()); - JsonNode dateOfBirth = regCertificate.get("dob"); + JsonNode dateOfBirth = regCertificate.get("dateOfBirth"); if (dateOfBirth != null) person.setDob(dateOfBirth.asText()); - JsonNode mobile = regCertificate.get("contact"); + JsonNode mobile = regCertificate.get("phoneNumber"); if (mobile != null) person.setPhone(mobile.asText()); } @@ -76,10 +93,15 @@ public static PullDocRequest processPullDocRequest(String xml) throws Exception{ Element docDetailsElement = (Element) rootElement.getElementsByTagName("DocDetails").item(0); // Get the values of URI and DigiLockerId elements String uri = docDetailsElement.getElementsByTagName("URI").item(0).getTextContent(); + String name = docDetailsElement.getElementsByTagName("FullName").item(0).getTextContent(); + String dob = docDetailsElement.getElementsByTagName("DOB").item(0).getTextContent(); String digiLockerId = docDetailsElement.getElementsByTagName("DigiLockerId").item(0).getTextContent(); docDetails.setUri(uri); docDetails.setDigiLockerId(digiLockerId); + docDetails.setDob(dob); + docDetails.setFullName(name); request.setDocDetails(docDetails); + // Print the values logger.info("URI: " + uri); logger.info("DigiLockerId: " + digiLockerId); @@ -101,10 +123,10 @@ public static PullDocRequest processPullDocRequest(String xml) throws Exception{ request.setFormat(attributeValue); break; case "keyhash": - request.setFormat(attributeValue); + request.setKeyhash(attributeValue); break; - case "x-digilocker-hmac": - request.setFormat(attributeValue); + case "hmac": + request.setHmac(attributeValue); break; default: break; @@ -153,11 +175,9 @@ public static String getXmlString(String xmlString) { if(docDetails.getName()!=null) sb.append("\"name\""+":"+"\""+docDetails.getName()+"\""+","); if(docDetails.getMobile()!=null) - sb.append("\"mobile\""+":"+"\""+docDetails.getMobile()+"\""+","); -// if(docDetails.getDateOfBirth()!=null) -// sb.append("\"dob\""+":"+"\""+docDetails.getDateOfBirth()+"\""+","); + sb.append("\"phoneNumber\""+":"+"\""+docDetails.getMobile()+"\""+","); if(docDetails.getFinalYearRollNo()!=null) - sb.append("\"finalYearRollNo\""+":"+"\""+docDetails.getFinalYearRollNo()+"\""); + sb.append("\"email\""+":"+"\""+docDetails.getFinalYearRollNo()+"\""); sb.append("}"); xmlString = sb.toString(); } catch (JAXBException e) { @@ -165,6 +185,27 @@ public static String getXmlString(String xmlString) { } return xmlString; } + + public static ObjectNode getJsonQuery(String xmlString) { + dev.sunbirdrc.registry.util.DocDetails docDetails; + JsonNode jsonNode = null; + ObjectMapper objectMapper = new ObjectMapper(); + ObjectNode objectNode = objectMapper.createObjectNode();; + try { + JAXBContext jaxbContext = JAXBContext.newInstance(PullURIRequest.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + PullURIRequest pullUriRequest = (PullURIRequest) jaxbUnmarshaller.unmarshal(new StringReader(xmlString)); + // Access DocDetails using getDocDetails() + docDetails = pullUriRequest.getDocDetails(); + jsonNode = getSearchNode(docDetails.getName(),docDetails.getMobile(), docDetails.getEmail()); + jsonNode.fields().forEachRemaining(entry -> objectNode.set(entry.getKey(), entry.getValue())); + } catch (JAXBException e) { + e.printStackTrace(); + } + return objectNode; + } + + public static PullURIResponse getPullUriResponse(String certUri, String status, String txn, Object certificate, Person person) { List personList = new ArrayList(); personList.add(person); @@ -191,6 +232,78 @@ public static PullURIResponse getPullUriResponse(String certUri, String status, } + + private static JsonNode getSearchNode(String name,String phoneNumber, String email){ + String searchNode = "{\n" + + " \"filters\": {\n" + + " \"email\": {\n" + + " \"contains\": \"" + email + + "\"\n" + + " },\n" + + " \"phoneNumber\": {\n" + + " \"eq\": \"" +phoneNumber+ + "\"\n" + + " },\n" + + " \"name\": {\n" + + " \"eq\": \"" +name+ + "\"\n" + + " }\n" + + " },\n" + + " \"limit\": 1,\n" + + " \"offset\": 0\n" + + "}"; + ObjectMapper objectMapper = new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); + JsonFactory factory = mapper.getFactory(); + JsonNode actualObj = null; + try { + JsonParser parser = factory.createParser(searchNode); + actualObj = mapper.readTree(parser); + // ((ObjectNode) actualObj.get("filters")).put("email",email); + } catch (IOException e) { + logger.error(e.getMessage()); + } + return actualObj; + } + + + public static JsonNode getQuryNode(String name,String dob){ + String formattedDateString = formatDate(dob); + String searchNode = "{\n" + + " \"filters\": {\n" + + " \"dateOfBirth\": {\n" + + " \"eq\": \"" + + formattedDateString +"\""+ + "\n" + + " },\n" + + " \"name\": {\n" + + " \"eq\": \"" + + name + + "\"\n" + + " }\n" + + " },\n" + + " \"limit\": 1,\n" + + " \"offset\": 0\n" + + "}"; + ObjectMapper objectMapper = new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); + JsonFactory factory = mapper.getFactory(); + JsonNode actualObj = null; + try { + JsonParser parser = factory.createParser(searchNode); + actualObj = mapper.readTree(parser); + // ((ObjectNode) actualObj.get("filters")).put("email",email); + } catch (IOException e) { + logger.error(e.getMessage()); + } + return actualObj; + } + + public static void main(String[] args) { + System.out.println( getQuryNode("Mr Rahu","1990-01-01")); + + } + public static PullDocResponse getDocPullUriResponse(String osId, String status, byte[] bytes, Person person) { Object content = convertJaxbToBase64XmlString(person); //ResponseStatus @@ -274,7 +387,7 @@ public static boolean isValidHmac(String receivedHashValue, String secretKey,Str public static boolean verifyHmac(String data, String secretKey, String hmacKey) { try { Mac mac = Mac.getInstance("HmacSHA256"); - SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"); + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "SHA-256"); mac.init(secretKeySpec); byte[] calculatedHash = mac.doFinal(data.getBytes()); // Decode the received hash value from Base64 @@ -287,6 +400,18 @@ public static boolean verifyHmac(String data, String secretKey, String hmacKey) } } + public static String formatDate(String inputDateString) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + LocalDate localDate = null; + try { + localDate = LocalDate.parse(inputDateString, formatter); + System.out.println("Parsed LocalDate: " + localDate); + } catch (DateTimeParseException e) { + System.out.println("Parsing error: " + e.getMessage()); + } + return localDate.toString(); + } + private byte[] hexEncode(byte[] data) { char[] hexChars = new char[data.length * 2]; for (int i = 0; i < data.length; i++) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java index 485f61baf..7456974a3 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DocDetails.java @@ -7,21 +7,18 @@ public class DocDetails { private String uID; private String digiLockerId; private String mobile; + private String email; private String name; private String finalYearRollNo; private String docType; - public String getFinalYearRollNo() { - return finalYearRollNo; - } - public void setFinalYearRollNo(String finalYearRollNo) { - this.finalYearRollNo = finalYearRollNo; + public String getEmail() { + return email; } - - - - + public void setEmail(String email) { + this.email = email; + } private String entityName; @@ -58,6 +55,13 @@ public void setName(String name) { this.name = name; } + public String getFinalYearRollNo() { + return finalYearRollNo; + } + + public void setFinalYearRollNo(String finalYearRollNo) { + this.finalYearRollNo = finalYearRollNo; + } diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 143429a40..096d4c988 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -55,7 +55,7 @@ registry: system: base: ${registry_system_base:http://localhost:8081/} rootEntity: - type: ${registry_rootentity_type:Regulator} + type: ${registry_rootentity_type:User} schema: url: ${registry_schema_url:/src/main/resources/public/_schemas} attestationPolicy: diff --git a/java/registry/src/main/resources/public/_schemas/Student.json b/java/registry/src/main/resources/public/_schemas/Student.json index 190fc06e5..6db88137d 100644 --- a/java/registry/src/main/resources/public/_schemas/Student.json +++ b/java/registry/src/main/resources/public/_schemas/Student.json @@ -315,7 +315,34 @@ ], "certificateTemplates": { "svg": "https://raw.githubusercontent.com/aniket-aditya/sunbird-rc/main/rc-demo-template.svg", - "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html", + "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html", + "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" } } } diff --git a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json index 69fc9badd..abb4d7d85 100644 --- a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json +++ b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json @@ -91,11 +91,7 @@ "title": "dob" }, "doc-proof": { - "type": "array", - "items": { - "type": "string" - }, - "title": "All Document Proof" + "type": "string", "title": "doc-proof" }, "candidatePic": { "$id": "#/properties/candidatePic", diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 312134dd9..aab868fe7 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -71,8 +71,41 @@ "joiningYear": {"type": "string", "title": "joiningYear"}, "passingMonth": {"type": "string", "title": "passingMonth"}, "passingYear": {"type": "string","title": "passingYear"}, + "examYear": {"type": "string","title": "examYear"}, "examBody":{"type": "string","title": "examBody"}, - "paymentStatus":{"type": "string","title": "paymentStatus"} + "centerCode": {"type": "string","title": "centerCode"}, + "paymentStatus":{"type": "string","title": "paymentStatus"}, + "credType":{"type": "string","title": "credType", "enum":[ + "ANM_DIPLOMA", + "ANM_REG", + "BABY_DIPLOMA", + "BABY_REG", + "BSC_NURSING", + "DEGREE", + "ETCA_REG", + "ETCA_DIPLOMA", + "ETCT_REG", + "ETCT_DIPLOMA", + "GNM_REG", + "GNM_DIPLOMA", + "PHARMACY_DIPLOMA", + "GOODSTANDING_REG", + "FOREIGN_REG", + "MSC_REG", + "PBBSC_REG", + "SANITATION_REG", + "SANITATION_DIPLOMA", + "PHYSIOTHERAPY_DIPLOMA", + "OPTOMETRY_REG", + "OPTOMETRY_DIPLOMA", + "OTTECHNICIAN_REG", + "OTTECHNICIAN_DIPLOMA", + "CARDIOLOGY_REG", + "CARDIOLOGY_DIPLOMA", + "BLOOD_TRANSFUSION_REG", + "BLOOD_TRANSFUSION_DIPLOMA" + ]}, + "doc-url":{"type": "string","title": "doc-url"} } } }, @@ -86,7 +119,7 @@ } ], "inviteRoles": ["anonymous"], - "roles": ["Regulator"], + "roles": ["StudentFromUP"], "attestationPolicies": [ { "name": "studentVerification", @@ -117,7 +150,11 @@ "passingYear": "$.passingYear", "finalYearRollNo": "$.finalYearRollNo", "examBody": "$.examBody", - "paymentStatus": "$.paymentStatus" + "examYear": "$.examYear", + "centerCode": "$.centerCode", + "paymentStatus": "$.paymentStatus", + "credType": "$.credType", + "doc-url": "$.doc-url" }, "credentialTemplate": { "@context": [ @@ -253,6 +290,18 @@ "name": "schema:Text" } }, + "examYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#examYear", + "@context": { + "name": "schema:Text" + } + }, + "centerCode":{ + "@id": "https://github.com/sunbird-specs/vc-specs#centerCode", + "@context": { + "name": "schema:Text" + } + }, "finalYearRollNo": { "@id": "https://github.com/sunbird-specs/vc-specs#finalYearRollNo", "@context": { @@ -276,6 +325,18 @@ "@context": { "name": "schema:Text" } + }, + "credType": { + "@id": "https://github.com/sunbird-specs/vc-specs#credType", + "@context": { + "name": "schema:Text" + } + }, + "doc-url": { + "@id": "https://github.com/sunbird-specs/vc-specs#doc-url", + "@context": { + "name": "schema:Text" + } } } ], @@ -307,41 +368,45 @@ "finalYearRollNo": "{{finalYearRollNo}}", "feeReciptNo": "{{feeReciptNo}}", "examBody": "{{examBody}}", - "paymentStatus": "{{paymentStatus}}" + "examYear": "{{examYear}}", + "centerCode": "{{centerCode}}", + "paymentStatus": "{{paymentStatus}}", + "credType":"{{credType}}", + "doc-url": "{{doc-url}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } } ], "certificateTemplates": { - "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", - "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", - "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", - "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", - "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html", - "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html", - "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", - "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", - "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", - "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", - "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", + "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/degree", + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", + "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding", + "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate", + "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r", + "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r", + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate" } } } diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUPDegree.json b/java/registry/src/main/resources/public/_schemas/studentFromUPDegree.json new file mode 100644 index 000000000..aef3830a7 --- /dev/null +++ b/java/registry/src/main/resources/public/_schemas/studentFromUPDegree.json @@ -0,0 +1,435 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema", + "type": "object", + "properties": { + "studentFromUPDegree": { + "$ref": "#/definitions/studentFromUPDegree" + } + }, + "required": [ + "studentFromUPDegree" + ], + "title": "studentFromUPDegree", + "definitions": { + "studentFromUPDegree": { + "$id": "#/properties/studentFromUPDegree", + "type": "object", + "title": "studentFromUPDegree", + "required": [ + "name", + "phoneNumber", + "email", + "council" + ], + "uniqueIndexFields": [ + "phoneNumber" + ], + "properties": { + "name": { + "type": "string" + }, + "phoneNumber": { + "type": "string" + }, + "email": { + "type": "string" + }, + "council": { + "type": "string" + }, + "mothersName": { + "type": "string", + "title": "motherName" + }, + "fathersName": { + "type": "string", + "title": "fatherName" + }, + "feeReceiptNo": { + "type": "string", + "title": "feeReceiptNo" + }, + "university": { + "type": "string", + "title": "university" + }, + "gender": { + "type": "string", + "title": "gender", + "enum": [ + "male", + "female" + ] + }, + "address": { + "type": "string", + "title": "address" + }, + "state": { + "type": "string", + "title": "State", + "enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] + }, + "district": { + "type": "string", + "title": "district" + }, + "country": { + "type": "string", + "title": "country" + }, + "pincode": { + "type": "string", + "title": "pincode" + }, + "candidatePic": { + "type": "string", + "title": "candidatePic" + }, + "courseName": { + "type": "string", + "title": "courseName" + }, + "nursingCollage": { + "type": "string", + "title": "nursingCollage" + }, + "joiningMonth": { + "type": "string", + "title": "joiningMonth" + }, + "joiningYear": { + "type": "string", + "title": "joiningYear" + }, + "passingMonth": { + "type": "string", + "title": "passingMonth" + }, + "passingYear": { + "type": "string", + "title": "passingYear" + }, + "examBody": { + "type": "string", + "title": "examBody" + }, + "paymentStatus": { + "type": "string", + "title": "paymentStatus" + } + } + } + }, + "_osConfig": { + "inviteRoles": [ + "anonymous" + ], + "roles": [ + "StudentFromUP" + ], + "attestationPolicies": [ + { + "name": "studentVerification", + "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", + "type": "MANUAL", + "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", + "attestationProperties": { + "name": "$.name", + "email": "$.email", + "phoneNumber": "$.phoneNumber", + "council": "$.council", + "mothersName": "$.mothersName", + "fathersName": "$.fathersName", + "feeReceiptNo": "$.feeReceiptNo", + "university": "$.university", + "gender": "$.gender", + "address": "$.address", + "state": "$.state", + "district": "$.district", + "country": "$.country", + "pincode": "$.pincode", + "candidatePic": "$.candidatePic", + "courseName": "$.courseName", + "nursingCollage": "$.nursingCollage", + "joiningMonth": "$.joiningMonth", + "joiningYear": "$.joiningYear", + "passingMonth": "$.passingMonth", + "passingYear": "$.passingYear", + "finalYearRollNo": "$.finalYearRollNo", + "examBody": "$.examBody", + "paymentStatus": "$.paymentStatus" + }, + "credentialTemplate": { + "@context": [ + "https://www.w3.org/2018/credentials/v1", + { + "@version": 1.1, + "@protected": true, + "SkillCertificate": { + "@id": "https://github.com/sunbird-specs/vc-specs#SkillCertificate", + "@context": { + "id": "@id", + "@version": 1.1, + "@protected": true, + "skills": "schema:Text" + } + }, + "Person": { + "@id": "https://github.com/sunbird-specs/vc-specs#Person", + "@context": { + "name": "schema:Text" + } + }, + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", + "@context": { + "name": "schema:Text" + } + }, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + } + }, + "council": { + "@id": "https://github.com/sunbird-specs/vc-specs#council", + "@context": { + "name": "schema:Text" + } + }, + "mothersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", + "@context": { + "name": "schema:Text" + } + }, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + } + }, + "feeReceiptNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#feeReceiptNo", + "@context": { + "name": "schema:Text" + } + }, + "university": { + "@id": "https://github.com/sunbird-specs/vc-specs#university", + "@context": { + "name": "schema:Text" + } + }, + "gender": { + "@id": "https://github.com/sunbird-specs/vc-specs#gender", + "@context": { + "name": "schema:Text" + } + }, + "address": { + "@id": "https://github.com/sunbird-specs/vc-specs#address", + "@context": { + "name": "schema:Text" + } + }, + "state": { + "@id": "https://github.com/sunbird-specs/vc-specs#state", + "@context": { + "name": "schema:Text" + } + }, + "district": { + "@id": "https://github.com/sunbird-specs/vc-specs#district", + "@context": { + "name": "schema:Text" + } + }, + "country": { + "@id": "https://github.com/sunbird-specs/vc-specs#country", + "@context": { + "name": "schema:Text" + } + }, + "pincode": { + "@id": "https://github.com/sunbird-specs/vc-specs#pincode", + "@context": { + "name": "schema:Text" + } + }, + "candidatePic": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", + "@context": { + "name": "schema:Text" + } + }, + "nursingCollage": { + "@id": "https://github.com/sunbird-specs/vc-specs#nursingCollage", + "@context": { + "name": "schema:Text" + } + }, + "courseName": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseName", + "@context": { + "name": "schema:Text" + } + }, + "joiningMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningMonth", + "@context": { + "name": "schema:Text" + } + }, + "joiningYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#joiningYear", + "@context": { + "name": "schema:Text" + } + }, + "passingMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingMonth", + "@context": { + "name": "schema:Text" + } + }, + "passingYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingYear", + "@context": { + "name": "schema:Text" + } + }, + "finalYearRollNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#finalYearRollNo", + "@context": { + "name": "schema:Text" + } + }, + "examBody": { + "@id": "https://github.com/sunbird-specs/vc-specs#examBody", + "@context": { + "name": "schema:Text" + } + }, + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "@context": { + "name": "schema:Text" + } + }, + "feeReciptNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#feeReciptNo", + "@context": { + "name": "schema:Text" + } + } + } + ], + "type": [ + "VerifiableCredential" + ], + "issuanceDate": "2021-08-27T10:57:57.237Z", + "credentialSubject": { + "type": "Person", + "name": "{{name}}", + "council": "{{council}}", + "email": "{{email}}", + "phoneNumber": "{{phoneNumber}}", + "mothersName": "{{mothersName}}", + "fathersName": "{{fathersName}}", + "feeReceiptNo": "{{feeReceiptNo}}", + "university": "{{university}}", + "gender": "{{gender}}", + "address": "{{address}}", + "state": "{{state}}", + "district": "{{district}}", + "country": "{{country}}", + "pincode": "{{pincode}}", + "candidatePic": "{{candidatePic}}", + "courseName": "{{courseName}}", + "nursingCollage": "{{nursingCollage}}", + "joiningMonth": "{{joiningMonth}}", + "joiningYear": "{{joiningYear}}", + "passingMonth": "{{passingMonth}}", + "passingYear": "{{passingYear}}", + "finalYearRollNo": "{{finalYearRollNo}}", + "feeReciptNo": "{{feeReciptNo}}", + "examBody": "{{examBody}}", + "paymentStatus": "{{paymentStatus}}" + }, + "issuer": "did:web:sunbirdrc.dev/vc/skill" + } + } + ], + "certificateTemplates": { + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html", + "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html", + "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html" + } + } +} diff --git a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json index 864f1f529..176b01294 100644 --- a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json +++ b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json @@ -91,11 +91,7 @@ "title": "workPlace" }, "doc-proof": { - "type": "array", - "items": { - "type": "string" - }, - "title": "All Document Proof" + "type": "string", "title": "All Document Proof" }, "paymentStatus": { "$id": "#/properties/paymentStatus", @@ -114,7 +110,7 @@ } ], "inviteRoles": ["anonymous"], - "roles": ["StudentGoodstanding"], + "roles": ["Regulator"], "attestationPolicies": [ { "name": "StudentGoodStandingVerification", diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json index 4e27c0c36..52ed190a6 100644 --- a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -433,7 +433,34 @@ } ], "certificateTemplates": { - "StudentOutsideUPTemp": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/nursingANM.html" + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", + "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/degree", + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", + "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding", + "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate", + "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r", + "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r", + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", + "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate" } } } \ No newline at end of file diff --git a/java/registry/src/test/java/dev/sunbirdrc/registry/controller/RegistryEntityControllerTest.java b/java/registry/src/test/java/dev/sunbirdrc/registry/controller/RegistryEntityControllerTest.java index 200043d46..0a1f5a9d0 100644 --- a/java/registry/src/test/java/dev/sunbirdrc/registry/controller/RegistryEntityControllerTest.java +++ b/java/registry/src/test/java/dev/sunbirdrc/registry/controller/RegistryEntityControllerTest.java @@ -89,7 +89,7 @@ public void testGetAttestationCertificate_success() throws Exception { JsonNode node = new ObjectMapper().readTree(response); Mockito.when(registryHelper.readEntity("anonymous", "Institute", "123", false, null, false)) .thenReturn(node); - Mockito.when(certificateService.getCertificate(node, "Institute", "123", "application/pdf", "http://dummy.com", node)) + Mockito.when(certificateService.getCertificate(node, "Institute", "123", "application/pdf", "http://dummy.com", node,"", false)) .thenReturn(""); mockMvc.perform( MockMvcRequestBuilders @@ -159,7 +159,7 @@ public void testGetAttestationCertificate_failureIfRecordNotFound() throws Excep JsonNode node = new ObjectMapper().readTree(response); Mockito.when(registryHelper.readEntity("anonymous", "Institute", "123", false, null, false)) .thenReturn(node); - Mockito.when(certificateService.getCertificate(node, "Institute", "123", "application/pdf", "http://dummy.com", node)) + Mockito.when(certificateService.getCertificate(node, "Institute", "123", "application/pdf", "http://dummy.com", node,"", false)) .thenThrow(new NullPointerException("")); mockMvc.perform( MockMvcRequestBuilders diff --git a/services/digilocker-certificate-api/config/config.go b/services/digilocker-certificate-api/config/config.go index abeacf7f5..b99b891be 100644 --- a/services/digilocker-certificate-api/config/config.go +++ b/services/digilocker-certificate-api/config/config.go @@ -13,7 +13,7 @@ var Config = struct { Keycloak struct { TokenURL string `env:"KEYCLOAK_TOKEN_URL" default:"http://keycloak:8080/auth/realms/sunbird-rc/protocol/openid-connect/token"` ClientId string `env:"KEYCLOAK_CLIENT_ID" default:"admin-api"` - ClientSecret string `env:"KEYCLOAK_CLIENT_SECRET" default:"**"` + ClientSecret string `env:"KEYCLOAK_CLIENT_SECRET" default:"2b65f70c-bd02-4d5c-95d9-5341225aa849"` } Digilocker struct { IDPrefix string `env:"DIGILOCKER_DOC_ID_PREFIX" default:"dev.sunbirdrc.vc"` @@ -21,7 +21,7 @@ var Config = struct { AuthHMACKey string `env:"DIGILOCKER_HMAC_AUTHKEY" default:"***"` } Registry struct { - URL string `env:"REGISTRY_URL" default:"https://demo-education-registry.xiv.in/registry/"` + URL string `env:"REGISTRY_URL" default:"https://localhost:8081/"` } LogLevel string `env:"LOG_LEVEL" yaml:"log_level" default:"DEBUG"` Host string `env:"HOST" yaml:"host" default:"0.0.0.0"` diff --git a/services/notification-service/config/application-default.yml b/services/notification-service/config/application-default.yml index 12c09de20..929969a37 100644 --- a/services/notification-service/config/application-default.yml +++ b/services/notification-service/config/application-default.yml @@ -1,5 +1,5 @@ kafka: - bootstrapServers: localhost + bootstrapServers: kafka certifyTopic: certify notifyTopic: notify enable: true @@ -11,8 +11,8 @@ smsapi: requestTemplate: '{"sender": "AppName","route": "4","country": "91","unicode": 1,"sms": [{"message": "{{.message}}","to": ["{{.to}}"]}],"DLT_TE_ID": "templateId"}' emailsmtp: - fromAddress: from@gmail.com - password: secret + fromAddress: upsmf.otp@upsmfac.org + password: enable: true flagr: diff --git a/services/notification-service/pkg/services/mail_service.go b/services/notification-service/pkg/services/mail_service.go index 14f82f7f6..46fccfc92 100644 --- a/services/notification-service/pkg/services/mail_service.go +++ b/services/notification-service/pkg/services/mail_service.go @@ -1,9 +1,10 @@ package services import ( - "github.com/sunbirdrc/notification-service/config" - log "github.com/sirupsen/logrus" "net/smtp" + + log "github.com/sirupsen/logrus" + "github.com/sunbirdrc/notification-service/config" ) func SendEmail(recipientEmail string, mailSubject string, mailBody string) error { @@ -16,7 +17,7 @@ func SendEmail(recipientEmail string, mailSubject string, mailBody string) error "Subject: " + mailSubject + "\n\n" + mailBody - err := smtp.SendMail("smtp.gmail.com:587", + err := smtp.SendMail("smtp.gmail.com:465", smtp.PlainAuth("", from, pass, "smtp.gmail.com"), from, []string{recipientEmail}, []byte(msg)) From f01aaac2f6d5af3a2588808dae6ed206c6975c9d Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Mon, 21 Aug 2023 17:11:30 +0530 Subject: [PATCH 22/43] credType updates --- .../claim/controller/ClaimsController.java | 5 + .../dev/sunbirdrc/claim/entity/Claim.java | 13 +++ .../sunbirdrc/claim/service/ClaimService.java | 1 + .../sunbirdrc/pojos/PluginRequestMessage.java | 1 + .../pojos/PluginRequestMessageCreator.java | 3 +- .../pojos/PluginResponseMessage.java | 2 + .../dev/sunbirdrc/pojos/dto/ClaimDTO.java | 10 ++ .../controller/RegistryClaimsController.java | 2 + .../controller/RegistryEntityController.java | 13 +-- .../digilocker/pulldoc/DocDetailsRs.java | 93 ++++++++++++++++++- .../digilocker/pulldoc/DocDetailsType.java | 4 +- .../registry/helper/RegistryHelper.java | 2 +- .../model/dto/AttestationRequest.java | 1 + .../registry/service/FileStorageService.java | 2 +- .../registry/util/DigiLockerUtils.java | 35 ++++--- .../registry/util/HashKeyVerifier.java | 48 ++++++++++ .../public/_schemas/studentFromUP.json | 10 +- .../public/_schemas/studentGoodStanding.json | 2 +- 18 files changed, 208 insertions(+), 39 deletions(-) create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/HashKeyVerifier.java diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/ClaimsController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/ClaimsController.java index 7ee733ef3..cc15a8f21 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/ClaimsController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/ClaimsController.java @@ -6,6 +6,7 @@ import dev.sunbirdrc.claim.service.ClaimService; import dev.sunbirdrc.claim.service.ClaimsAuthorizer; import dev.sunbirdrc.pojos.dto.ClaimDTO; +import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -73,7 +74,11 @@ public ResponseEntity getClaimById(@RequestHeader HttpHeaders @RequestMapping(value = "/api/v1/claims", method = RequestMethod.POST) public ResponseEntity save(@RequestBody ClaimDTO claimDTO) { + JSONObject jsonObject = new JSONObject(claimDTO.getPropertyData()); + String credType1 = jsonObject.get("credType").toString(); + claimDTO.setCredtype(credType1); logger.info("Adding new claimDTO {} ", claimDTO.toString()); + logger.info("Cred Type new claimDTO {} ", claimDTO.getCredtype()); Claim savedClaim = claimService.save(Claim.fromDTO(claimDTO)); claimService.addNotes(claimDTO.getNotes(), savedClaim, claimDTO.getRequestorName()); return new ResponseEntity<>(savedClaim, HttpStatus.OK); diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java index a16d9a875..6e2efc748 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java @@ -25,6 +25,17 @@ public class Claim { private String id; @Column private String entity; + + public String getCredType() { + return credType; + } + + public void setCredType(String credType) { + this.credType = credType; + } + + @Column + private String credType; @Column private String entityId; @Column @@ -127,6 +138,7 @@ public String toString() { ", propertyURI='" + propertyURI + '\'' + ", status='" + status + '\'' + ", condition='" + conditions + '\'' + + ", credType='" + credType + '\'' + '}'; } @@ -165,6 +177,7 @@ public static Claim fromDTO(ClaimDTO claimDTO) { claim.setPropertyData(claimDTO.getPropertyData()); claim.setAttestationId(claimDTO.getAttestationId()); claim.setAttestationName(claimDTO.getAttestationName()); + claim.setCredType(claimDTO.getCredtype()); return claim; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java index c556dd42c..515abda95 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java @@ -98,6 +98,7 @@ public Claim attestClaim(String claimId, JsonNode requestBody) { } private Claim updateClaim(JsonNode requestBody, Claim claim) { + logger.info("CredType"+claim.getCredType()); JsonNode attestorNode = requestBody.get(ATTESTOR_INFO); if(requestBody.has(NOTES)) { addNotes(requestBody.get(NOTES).asText(), claim, EntityUtil.getFullNameOfTheEntity(attestorNode)); diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginRequestMessage.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginRequestMessage.java index f229d3167..a99bf18ba 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginRequestMessage.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginRequestMessage.java @@ -35,6 +35,7 @@ public class PluginRequestMessage { private String userId; private Map> propertiesOSID; private String emailId; + private String credType; public Optional getActorName() { // sample names did:plugin:aadhar, did:plugin:claim, diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginRequestMessageCreator.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginRequestMessageCreator.java index 827308c00..e7603e53c 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginRequestMessageCreator.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginRequestMessageCreator.java @@ -13,7 +13,7 @@ public static PluginRequestMessage create(String propertyData, String userId, String entityId, JsonNode additionalInput, String status, String name, String attestorPlugin, String attestorEntity, - String attestorSignin, Map> propertiesOSID, String emailId) { + String attestorSignin, Map> propertiesOSID, String emailId, String credType) { PluginRequestMessage pluginRequestMessage = new PluginRequestMessage(); pluginRequestMessage.setPolicyName(name); @@ -30,6 +30,7 @@ public static PluginRequestMessage create(String propertyData, pluginRequestMessage.setUserId(userId); pluginRequestMessage.setPropertiesOSID(propertiesOSID); pluginRequestMessage.setEmailId(emailId); + pluginRequestMessage.setCredType(credType); return pluginRequestMessage; } diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginResponseMessage.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginResponseMessage.java index 6be9f52da..45313bd46 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginResponseMessage.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/PluginResponseMessage.java @@ -36,6 +36,8 @@ public class PluginResponseMessage { private String userId; private Map> propertiesOSID; private String emailId; + + private String credType; @Builder.Default private List files = new ArrayList<>(); } diff --git a/java/pojos/src/main/java/dev/sunbirdrc/pojos/dto/ClaimDTO.java b/java/pojos/src/main/java/dev/sunbirdrc/pojos/dto/ClaimDTO.java index e93df9310..ddd9805ae 100644 --- a/java/pojos/src/main/java/dev/sunbirdrc/pojos/dto/ClaimDTO.java +++ b/java/pojos/src/main/java/dev/sunbirdrc/pojos/dto/ClaimDTO.java @@ -14,6 +14,16 @@ public class ClaimDTO { private String attestationId; private String attestationName; + public String getCredtype() { + return credtype; + } + + public void setCredtype(String credtype) { + this.credtype = credtype; + } + + private String credtype; + public String getRequestorName() { return requestorName; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java index 633db4f7c..68ba73b5c 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java @@ -130,6 +130,7 @@ private ObjectNode generateAdditionInput(String claimId, String entityName, Obje additionalInputs.set("attestorInfo", attestorInfo); additionalInputs.set("action", action); additionalInputs.set("notes", notes); + // additionalInputs.set("credType", entityName); additionalInputs.put("claimId", claimId); return additionalInputs; } @@ -159,6 +160,7 @@ public ResponseEntity riseAttestation(HttpServletRequest request, @Reque } attestationRequest.setUserId(userId); attestationRequest.setEmailId(emailId); + attestationRequest.setCredType(request.getHeader("credType")); String attestationOSID = registryHelper.triggerAttestation(attestationRequest, attestationPolicy); response.setResult(Collections.singletonMap("attestationOSID", attestationOSID)); } catch (Exception exception) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 49e1c25f4..909e3458d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -1100,11 +1100,12 @@ public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest re try { String uri = DigiLockerUtils.getDocUri(); String fileName = "issuance/"+osid+".pdf"; - Object certificate = certificateService.getCred(fileName); + byte[] certificate = certificateService.getCred(fileName); if(certificate!=null){ certificateService.saveforDGL(certificate, uri); Person person = DigiLockerUtils.getPersonDetail(result, entityName); - PullURIResponse pullResponse = DigiLockerUtils.getPullUriResponse(uri, statusCode, osid, certificate, person); + String encodedCertificate = Base64.getEncoder().encodeToString(certificate); + PullURIResponse pullResponse = DigiLockerUtils.getPullUriResponse(uri, statusCode, osid, encodedCertificate, person); String responseString = DigiLockerUtils.convertJaxbToString(pullResponse); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); @@ -1183,7 +1184,7 @@ public ResponseEntity pullDocURI(HttpServletRequest request) { Person person = new Person(); person.setDob(dob); person.setDob(fullName); - PullDocResponse pullDocResponse = DigiLockerUtils.getDocPullUriResponse(osid,statusCode, cred,person); + PullDocResponse pullDocResponse = DigiLockerUtils.getDocPullUriResponse(pullDocRequest, statusCode, cred, person); Object responseString = DigiLockerUtils.convertJaxbToPullDoc(pullDocResponse); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); @@ -1206,8 +1207,8 @@ public ResponseEntity pullDocURI(HttpServletRequest request) { * @param request * @return */ - @CrossOrigin(origins = "*") - @RequestMapping(value = "/api/v1/{entityName}/{entityId}/upload/multi-files", method = RequestMethod.POST) + + @RequestMapping(value = "/api/v1/{entityName}/{entityId}/upload/multi-files", method = RequestMethod.PUT) public ResponseEntity putMultiEntityFiles( @PathVariable String entityName, @PathVariable String entityId, @@ -1247,7 +1248,7 @@ public ResponseEntity putMultiEntityFiles( } } - @CrossOrigin(origins = "*") + @RequestMapping(value = "/api/v1/{entityName}/{entityId}/upload/file", method = RequestMethod.PUT) public ResponseEntity putSingleEntityFile( @PathVariable String entityName, diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRs.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRs.java index 4758d1dac..ef0cefedb 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRs.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsRs.java @@ -5,11 +5,99 @@ @XmlRootElement(name = "DocDetails") public class DocDetailsRs { + private String docType; + + private String digiLockerId; + + private String uid; + + private String fullName; + + private String dob; + + private String trackingId; + private String mobile; + + private String udf1; + + private String uri; private Object docContent; + private Object dataContent; - @XmlElement(name = "DocContent") + public String getDocType() { + return docType; + } + + public void setDocType(String docType) { + this.docType = docType; + } + + public String getDigiLockerId() { + return digiLockerId; + } + + public void setDigiLockerId(String digiLockerId) { + this.digiLockerId = digiLockerId; + } + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getDob() { + return dob; + } + + public void setDob(String dob) { + this.dob = dob; + } + + public String getTrackingId() { + return trackingId; + } + + public void setTrackingId(String trackingId) { + this.trackingId = trackingId; + } + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getUdf1() { + return udf1; + } + + public void setUdf1(String udf1) { + this.udf1 = udf1; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + public Object getDocContent() { return docContent; } @@ -18,7 +106,6 @@ public void setDocContent(Object docContent) { this.docContent = docContent; } - @XmlElement(name = "DataContent") public Object getDataContent() { return dataContent; } @@ -27,5 +114,5 @@ public void setDataContent(Object dataContent) { this.dataContent = dataContent; } - } + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java index a25de5fe5..2da15054d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/digilocker/pulldoc/DocDetailsType.java @@ -13,7 +13,9 @@ public class DocDetailsType { protected String uri; + protected String fullName; + protected String dob; protected String digiLockerId; public String getFullName() { @@ -32,9 +34,7 @@ public void setDob(String dob) { this.dob = dob; } - protected String fullName; - protected String dob; public String getUri() { return uri; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index efc9107dd..6e27e4f39 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java @@ -428,7 +428,7 @@ public String triggerAttestation(AttestationRequest attestationRequest, Attestat attestationRequest.getEmailId(), attestationRequest.getEntityId(), attestationRequest.getAdditionalInput(), Action.RAISE_CLAIM.name(), attestationPolicy.getName(), attestationPolicy.getAttestorPlugin(), attestationPolicy.getAttestorEntity(), attestationPolicy.getAttestorSignin(), - attestationRequest.getPropertiesOSID(), attestationRequest.getEmailId()); + attestationRequest.getPropertiesOSID(), attestationRequest.getEmailId(),attestationRequest.getCredType()); PluginRouter.route(message); return attestationOSID; diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/AttestationRequest.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/AttestationRequest.java index 89dfea935..9961f7197 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/AttestationRequest.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/AttestationRequest.java @@ -22,4 +22,5 @@ public class AttestationRequest { private Map> propertiesOSID; private JsonNode propertyData; private String emailId; + private String credType; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java index a2541025b..d51e63586 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/FileStorageService.java @@ -56,7 +56,7 @@ public DocumentsResponse saveAndFetchFileNames(MultipartFile[] files, String req for (MultipartFile file : files) { String fileName = getFileName(file.getOriginalFilename()); try { - String objectName = objectPath + "/" + fileName; + String objectName = "/"+objectPath + "/" + fileName; save(file.getInputStream(), objectName); documentsResponse.addDocumentLocation(objectName); } catch (Exception e) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java index 91f2a336a..2a2be2a93 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/DigiLockerUtils.java @@ -4,24 +4,13 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import dev.sunbirdrc.pojos.Response; -import dev.sunbirdrc.pojos.ResponseParams; import dev.sunbirdrc.registry.digilocker.pulldoc.*; import dev.sunbirdrc.registry.digilocker.pulluriresponse.*; import dev.sunbirdrc.registry.digilocker.pulluriresponse.DocDetails; -import dev.sunbirdrc.registry.exception.RecordNotFoundException; import dev.sunbirdrc.registry.middleware.util.DateUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -29,6 +18,7 @@ import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; +import javax.servlet.http.HttpServletRequest; import javax.xml.bind.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -42,8 +32,6 @@ import java.time.format.DateTimeParseException; import java.util.*; -import static dev.sunbirdrc.registry.middleware.util.Constants.ENTITY_TYPE; - public class DigiLockerUtils { public static final String HMAC_SHA_256 = "HmacSHA256"; @@ -304,20 +292,18 @@ public static void main(String[] args) { } - public static PullDocResponse getDocPullUriResponse(String osId, String status, byte[] bytes, Person person) { + public static PullDocResponse getDocPullUriResponse(PullDocRequest pullDocRequest, String status, byte[] bytes, Person person) { Object content = convertJaxbToBase64XmlString(person); //ResponseStatus PullDocResponse resp = new PullDocResponse(); ResponseStatus responseStatus = new ResponseStatus(); responseStatus.setStatus(status); - responseStatus.setTxn(osId); - responseStatus.setTs(DateUtil.getTimeStamp()); + responseStatus.setTxn(pullDocRequest.getTxn()); + responseStatus.setTs(pullDocRequest.getTs()); resp.setResponseStatus(responseStatus); - DocDetailsRs docDetails = new DocDetailsRs(); docDetails.setDataContent(content); - //dataCont.setContent(content); - + docDetails.setDigiLockerId(pullDocRequest.getDocDetails().getDigiLockerId()); docDetails.setDocContent(Base64.getEncoder().encodeToString(bytes)); resp.setDocDetails(docDetails); return resp; @@ -426,4 +412,15 @@ public boolean validateHMAC(byte[] actualHMAC, byte[] expectedHMAC) { return Arrays.equals(actualHMAC, expectedHMAC); } + public byte[] getHMACFromRequest(HttpServletRequest request) { + String hmacDigest = request.getHeader("x-digilocker-hmac"); + try { + byte[] hmacSignByteArray = Base64.getDecoder().decode(hmacDigest); + return hmacSignByteArray; + } catch (IllegalArgumentException e) { + System.err.println("Error while decoding hmac digest: " + e.getMessage()); + return null; + } + } + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/HashKeyVerifier.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/HashKeyVerifier.java new file mode 100644 index 000000000..c35c6f598 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/HashKeyVerifier.java @@ -0,0 +1,48 @@ +package dev.sunbirdrc.registry.util; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class HashKeyVerifier { + public static void main(String[] args) { + String originalData = "sample11-1aa1-11a1-10a0-digilockerid"; // The data that was originally hashed + String providedHash = "NzkyODIyYmNjZDkyYmY4MWI4MzM0YTBjZmMwZmJmODUyODgzYzE4ZDZkYTg3MGNlZmJmODNlYTkxY2FmZDEyMQ=="; // The hash value provided for verification + + try { + String algorithm = "SHA-256"; // Choose the appropriate hashing algorithm + + // Create a MessageDigest instance + MessageDigest digest = MessageDigest.getInstance(algorithm); + + // Convert the original data to bytes and hash it + byte[] hashedBytes = digest.digest(originalData.getBytes(StandardCharsets.UTF_8)); + + // Convert the hashed bytes to a hexadecimal string + String generatedHash = bytesToHex(hashedBytes); + + // Compare the generated hash with the provided hash + if (providedHash.equals(generatedHash)) { + System.out.println("Hashes match: Valid hash key"); + } else { + System.out.println("Hashes do not match: Invalid hash key"); + } + + } catch (NoSuchAlgorithmException e) { + System.err.println("Unsupported hashing algorithm: " + e.getMessage()); + } + } + + // Helper method to convert bytes to hexadecimal string + private static String bytesToHex(byte[] bytes) { + StringBuilder hexString = new StringBuilder(); + for (byte b : bytes) { + String hex = Integer.toHexString(0xFF & b); + if (hex.length() == 1) { + hexString.append('0'); + } + hexString.append(hex); + } + return hexString.toString(); + } +} + diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index aab868fe7..c48b1ea2c 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -105,7 +105,7 @@ "BLOOD_TRANSFUSION_REG", "BLOOD_TRANSFUSION_DIPLOMA" ]}, - "doc-url":{"type": "string","title": "doc-url"} + "docproof":{"type": "string","title": "docproof"} } } }, @@ -154,7 +154,7 @@ "centerCode": "$.centerCode", "paymentStatus": "$.paymentStatus", "credType": "$.credType", - "doc-url": "$.doc-url" + "docproof": "$.docproof" }, "credentialTemplate": { "@context": [ @@ -332,8 +332,8 @@ "name": "schema:Text" } }, - "doc-url": { - "@id": "https://github.com/sunbird-specs/vc-specs#doc-url", + "docproof": { + "@id": "https://github.com/sunbird-specs/vc-specs#docproof", "@context": { "name": "schema:Text" } @@ -372,7 +372,7 @@ "centerCode": "{{centerCode}}", "paymentStatus": "{{paymentStatus}}", "credType":"{{credType}}", - "doc-url": "{{doc-url}}" + "docproof": "{{docproof}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json index 176b01294..769be1ee9 100644 --- a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json +++ b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json @@ -110,7 +110,7 @@ } ], "inviteRoles": ["anonymous"], - "roles": ["Regulator"], + "roles": ["StudentGoodstanding"], "attestationPolicies": [ { "name": "StudentGoodStandingVerification", From bb3acf34920d619bed42164f482714225cb2b6e4 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 22 Aug 2023 07:32:37 +0530 Subject: [PATCH 23/43] course api --- .../claim/controller/CoursesController.java | 45 +++++++++++++++++++ .../dev/sunbirdrc/claim/entity/Courses.java | 25 +++++++++++ .../claim/repository/CoursesRepository.java | 8 ++++ .../claim/service/CoursesService.java | 32 +++++++++++++ .../_schemas/studentForeignVerification.json | 10 ++--- .../public/_schemas/studentGoodStanding.json | 2 +- .../public/_schemas/studentNursingArmy.json | 2 +- .../public/_schemas/studentOutsideUp.json | 4 +- services/certificate-api/configs/config.js | 2 +- 9 files changed, 120 insertions(+), 10 deletions(-) create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Courses.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java new file mode 100644 index 000000000..28e832590 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java @@ -0,0 +1,45 @@ +package dev.sunbirdrc.claim.controller; + +import dev.sunbirdrc.claim.entity.Courses; +import dev.sunbirdrc.claim.service.CoursesService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/api/v1/courses") +public class CoursesController { + + private CoursesService coursesService; + + @Autowired + public CoursesController(CoursesService coursesService) { + this.coursesService = coursesService; + } + + @GetMapping + public ResponseEntity> getAllCourses() { + List courses = coursesService.getAllCourses(); + return ResponseEntity.ok(courses); + } + + @GetMapping("/{id}") + public ResponseEntity getCourseById(@PathVariable Long id) { + Optional course = coursesService.getCourseById(id); + + if (course.isPresent()) { + return ResponseEntity.ok(course.get()); + } else { + return ResponseEntity.notFound().build(); + } + } + + @PostMapping + public ResponseEntity createCourse(@RequestBody Courses course) { + Courses savedCourse = coursesService.createCourse(course); + return ResponseEntity.ok(savedCourse); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Courses.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Courses.java new file mode 100644 index 000000000..3db428b7d --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Courses.java @@ -0,0 +1,25 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Courses { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "shortName") + private String shortName; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java new file mode 100644 index 000000000..942c07272 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java @@ -0,0 +1,8 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.Courses; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CoursesRepository extends JpaRepository { +} + diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java new file mode 100644 index 000000000..1a72beb26 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java @@ -0,0 +1,32 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.entity.Courses; +import dev.sunbirdrc.claim.repository.CoursesRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class CoursesService { + + private CoursesRepository coursesRepository; + + @Autowired + public CoursesService(CoursesRepository coursesRepository) { + this.coursesRepository = coursesRepository; + } + + public List getAllCourses() { + return coursesRepository.findAll(); + } + + public Optional getCourseById(Long id) { + return coursesRepository.findById(id); + } + + public Courses createCourse(Courses course) { + return coursesRepository.save(course); + } +} diff --git a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json index abb4d7d85..90745ea79 100644 --- a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json +++ b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json @@ -90,8 +90,8 @@ "type": "string", "title": "dob" }, - "doc-proof": { - "type": "string", "title": "doc-proof" + "docproof": { + "type": "string", "title": "docproof" }, "candidatePic": { "$id": "#/properties/candidatePic", @@ -140,7 +140,7 @@ "date": "$.date", "validityOfRegistration": "$.validityOfRegistration", "dob": "$.dob", - "doc-proof": "$.doc-proof", + "docproof": "$.docproof", "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { @@ -242,8 +242,8 @@ "name": "schema:Text" } }, - "doc-proof": { - "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "docproof": { + "@id": "https://github.com/sunbird-specs/vc-specs#docproof", "@context": { "name": "schema:Text" } diff --git a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json index 769be1ee9..5f29b8d48 100644 --- a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json +++ b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json @@ -113,7 +113,7 @@ "roles": ["StudentGoodstanding"], "attestationPolicies": [ { - "name": "StudentGoodStandingVerification", + "name": "studentVerification", "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", "type": "MANUAL", "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", diff --git a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json index eed1fabe6..71c202b35 100644 --- a/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json +++ b/java/registry/src/main/resources/public/_schemas/studentNursingArmy.json @@ -226,7 +226,7 @@ "roles": ["StudentNursingArmy"], "attestationPolicies": [ { - "name": "studentArmyVerification", + "name": "studentVerification", "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", "type": "MANUAL", "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json index 52ed190a6..542a9e808 100644 --- a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -240,10 +240,10 @@ } ], "inviteRoles": ["anonymous"], - "roles": ["StudentOutsideUP"], + "roles": ["StudentOutsideUP","StudentFromUP"], "attestationPolicies": [ { - "name": "studentOutsideUPVerification", + "name": "studentVerification", "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", "type": "MANUAL", "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", diff --git a/services/certificate-api/configs/config.js b/services/certificate-api/configs/config.js index dc0e557ea..a49240ce8 100644 --- a/services/certificate-api/configs/config.js +++ b/services/certificate-api/configs/config.js @@ -2,7 +2,7 @@ const CUSTOM_TEMPLATE_DELIMITERS = process.env.CUSTOM_TEMPLATE_DELIMITERS?.split const PUPPETEER_EXECUTABLE_PATH = process.env.PUPPETEER_EXECUTABLE_PATH || "" const ENABLE_CUSTOM_QR_CODE_CANVAS = process.env.ENABLE_CUSTOM_QR_CODE_CANVAS || false const QR_TYPE = process.env.QR_TYPE || 'W3C-VC'; -const CERTIFICATE_DOMAIN_URL = process.env.CERTIFICATE_DOMAIN_URL || "https://dev.sunbirded.org"; +const CERTIFICATE_DOMAIN_URL = process.env.CERTIFICATE_DOMAIN_URL || "https://registration.uphrh.in:8082/"; module.exports = { CUSTOM_TEMPLATE_DELIMITERS, PUPPETEER_EXECUTABLE_PATH, From 2a543228dd945ce0cba51c498a15a7e8b144f769 Mon Sep 17 00:00:00 2001 From: rkrahu Date: Tue, 22 Aug 2023 11:16:48 +0530 Subject: [PATCH 24/43] Sending pending item mail to foreign council Regulator through cron job --- java/claim/pom.xml | 8 ++ .../claim/config/PropertyMapper.java | 6 + .../claim/contants/AttributeNames.java | 6 + .../claim/controller/EmailController.java | 7 - .../claim/controller/FileController.java | 13 +- .../sunbirdrc/claim/dto/PendingMailDTO.java | 7 + .../dev/sunbirdrc/claim/entity/Regulator.java | 35 +++++ .../sunbirdrc/claim/quartz/JobCreator.java | 93 ++++++++++++ .../claim/quartz/MailingJobExecutor.java | 28 ++++ .../claim/quartz/SchedulerConfig.java | 72 ++++++++++ .../claim/quartz/SchedulerJobFactory.java | 24 ++++ .../claim/repository/RegulatorRepository.java | 15 ++ .../claim/repository/RegulatorRowMapper.java | 23 +++ .../sunbirdrc/claim/service/EmailService.java | 132 ++++++++++++++++-- .../sunbirdrc/claim/service/FileService.java | 3 + .../claim/service/FileServiceImpl.java | 43 ++++++ .../claim/service/RegulatorService.java | 44 ++++++ .../src/main/resources/application.properties | 28 ++++ .../resources/templates/pending-item-mail.ftl | 41 +++++- .../controller/RegistryEntityController.java | 25 ---- .../registry/util/ClaimRequestClient.java | 11 -- 21 files changed, 604 insertions(+), 60 deletions(-) create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Regulator.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/quartz/JobCreator.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/quartz/MailingJobExecutor.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/quartz/SchedulerConfig.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/quartz/SchedulerJobFactory.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/RegulatorRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/RegulatorRowMapper.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/RegulatorService.java diff --git a/java/claim/pom.xml b/java/claim/pom.xml index 39b13a0c3..8f153ffe0 100644 --- a/java/claim/pom.xml +++ b/java/claim/pom.xml @@ -52,6 +52,10 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-data-jdbc + org.springframework.cloud spring-cloud-gcp-starter-vision @@ -158,6 +162,10 @@ org.freemarker freemarker + + org.springframework.boot + spring-boot-starter-quartz + diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java index b5302aa38..d56b98715 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java @@ -12,4 +12,10 @@ public class PropertyMapper { @Value("${foreign.pending.item.subject}") private String foreignPendingItemSubject; + + @Value("${up.council.name}") + private String upCouncilName; + + @Value("${regulator.table.name}") + private String regulatorTableName; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/contants/AttributeNames.java b/java/claim/src/main/java/dev/sunbirdrc/claim/contants/AttributeNames.java index d76ba5e3e..95442cce4 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/contants/AttributeNames.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/contants/AttributeNames.java @@ -14,4 +14,10 @@ public class AttributeNames { public static final String CONTENT = "content"; public static final String TOTAL_PAGES = "totalPages"; public static final String TOTAL_ELEMENTS = "totalElements"; + + public static final String JPG = "JPG"; + public static final String JPEG = "JPEG"; + public static final String PNG = "PNG"; + public static final String GIF = "GIF"; + public static final String PDF = "PDF"; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java index da3f0d72d..c8bcfa046 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java @@ -119,11 +119,4 @@ public ResponseEntity sendCertificateMail(@RequestBody CertificateMailDt return new ResponseEntity<>("Mail is sending", HttpStatus.OK); } - @RequestMapping(value = "/api/v1/sendPendingForeignItemMail", method = RequestMethod.POST) - public ResponseEntity sendPendingItemMail(@RequestHeader HttpHeaders headers, - @RequestBody PendingMailDTO pendingMailDTO) { - emailService.sendPendingMail(pendingMailDTO); - return new ResponseEntity<>("Mail is sending", HttpStatus.OK); - } - } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java index 7376d439a..aa63ea487 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java @@ -45,9 +45,16 @@ public ResponseEntity downloadFile( ByteArrayResource resource = fileService.downloadFile(fileName); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "filename=\"" + fileName + "\""); - return ResponseEntity.ok(). - contentType(MediaType.APPLICATION_PDF). - headers(headers).body(resource); + + try { + MediaType mediaType = fileService.getFileMediaType(fileName); + + return ResponseEntity.ok() + .contentType(mediaType) + .headers(headers).body(resource); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.EXPECTATION_FAILED); + } } /** diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java index 50c3cf3d0..525c7e7c3 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java @@ -1,9 +1,11 @@ package dev.sunbirdrc.claim.dto; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +@Builder @Data @AllArgsConstructor @NoArgsConstructor @@ -12,4 +14,9 @@ public class PendingMailDTO { private String emailAddress; private String council; private String itemName; + private String refNo; + private String regulatorName; + private String regulatorEmail; + private String course; + private String registrationNumber; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Regulator.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Regulator.java new file mode 100644 index 000000000..38a84c99c --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Regulator.java @@ -0,0 +1,35 @@ +package dev.sunbirdrc.claim.entity; + + +import dev.sunbirdrc.claim.model.ClaimStatus; +import dev.sunbirdrc.pojos.dto.ClaimDTO; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.GenericGenerator; + +import javax.persistence.*; +import java.util.Date; + +@Data +@AllArgsConstructor +@NoArgsConstructor +//@Entity//(name = "\"V_Regulator\"") +//@Table(name = "\"V_Regulator\"") +public class Regulator { + @Id + @GeneratedValue(strategy = GenerationType.TABLE) + private String ID; + @Column + private String name; + @Column + private String phoneNumber; + @Column + private String council; + @Column + private String email; + @Column + private String osOwner; + @Column + private String osid; +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/JobCreator.java b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/JobCreator.java new file mode 100644 index 000000000..1d9804377 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/JobCreator.java @@ -0,0 +1,93 @@ +package dev.sunbirdrc.claim.quartz; + +import lombok.extern.slf4j.Slf4j; +import org.quartz.CronTrigger; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.SimpleTrigger; +import org.springframework.context.ApplicationContext; +import org.springframework.scheduling.quartz.CronTriggerFactoryBean; +import org.springframework.scheduling.quartz.JobDetailFactoryBean; +import org.springframework.scheduling.quartz.QuartzJobBean; +import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; +import org.springframework.stereotype.Component; + +import java.text.ParseException; +import java.util.Date; + +@Slf4j +@Component +public class JobCreator { + + /** + * Create Quartz Job. + * + * @param jobClass Class whose executeInternal() method needs to be called. + * @param isDurable Job needs to be persisted even after completion. if true, job will be persisted, not otherwise. + * @param context Spring application context. + * @param jobName Job name. + * @param jobGroup Job group. + * @return JobDetail object + */ + public JobDetail createJob(Class jobClass, boolean isDurable, + ApplicationContext context, String jobName, String jobGroup) { + JobDetailFactoryBean factoryBean = new JobDetailFactoryBean(); + factoryBean.setJobClass(jobClass); + factoryBean.setDurability(isDurable); + factoryBean.setApplicationContext(context); + factoryBean.setName(jobName); + factoryBean.setGroup(jobGroup); + + // set job data map + JobDataMap jobDataMap = new JobDataMap(); + jobDataMap.put(jobName + jobGroup, jobClass.getName()); + factoryBean.setJobDataMap(jobDataMap); + + factoryBean.afterPropertiesSet(); + + return factoryBean.getObject(); + } + + /** + * Create cron trigger. + * + * @param triggerName Trigger name. + * @param startTime Trigger start time. + * @param cronExpression Cron expression. + * @param misFireInstruction Misfire instruction (what to do in case of misfire happens). + * @return {@link CronTrigger} + */ + public CronTrigger createCronTrigger(String triggerName, Date startTime, String cronExpression, int misFireInstruction) { + CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean(); + factoryBean.setName(triggerName); + factoryBean.setStartTime(startTime); + factoryBean.setCronExpression(cronExpression); + factoryBean.setMisfireInstruction(misFireInstruction); + try { + factoryBean.afterPropertiesSet(); + } catch (ParseException e) { + log.error(e.getMessage(), e); + } + return factoryBean.getObject(); + } + + /** + * Create simple trigger. + * + * @param triggerName Trigger name. + * @param startTime Trigger start time. + * @param repeatTime Job repeat period mills + * @param misFireInstruction Misfire instruction (what to do in case of misfire happens). + * @return {@link SimpleTrigger} + */ + public SimpleTrigger createSimpleTrigger(String triggerName, Date startTime, Long repeatTime, int misFireInstruction) { + SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean(); + factoryBean.setName(triggerName); + factoryBean.setStartTime(startTime); + factoryBean.setRepeatInterval(repeatTime); + factoryBean.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY); + factoryBean.setMisfireInstruction(misFireInstruction); + factoryBean.afterPropertiesSet(); + return factoryBean.getObject(); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/MailingJobExecutor.java b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/MailingJobExecutor.java new file mode 100644 index 000000000..6b4d092d3 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/MailingJobExecutor.java @@ -0,0 +1,28 @@ +package dev.sunbirdrc.claim.quartz; + +import dev.sunbirdrc.claim.service.EmailService; +import lombok.extern.slf4j.Slf4j; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.quartz.QuartzJobBean; +import org.springframework.stereotype.Component; + +import java.util.Date; + +@Slf4j +@Component +public class MailingJobExecutor extends QuartzJobBean { + + @Autowired + private EmailService emailService; + + @Override + protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { + log.info(">>>>>>>>>>>> Mail for foreign council job started :: " + new Date(System.currentTimeMillis()) + " <<<<<<<<<<<<<<<<"); + + emailService.sendForeignPendingItemMail(); + + log.info(">>>>>>>>>>>> Mail for foreign council has been completed :: " + new Date(System.currentTimeMillis()) + " <<<<<<<<<<<<<<<<"); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/SchedulerConfig.java b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/SchedulerConfig.java new file mode 100644 index 000000000..6a2c87631 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/SchedulerConfig.java @@ -0,0 +1,72 @@ +package dev.sunbirdrc.claim.quartz; + +import org.quartz.JobDetail; +import org.quartz.SimpleTrigger; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.quartz.QuartzProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.quartz.CronTriggerFactoryBean; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; + +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +public class SchedulerConfig { + @Autowired + private DataSource dataSource; + + @Autowired + private ApplicationContext applicationContext; + + @Autowired + private QuartzProperties quartzProperties; + + @Autowired + private JobCreator jobCreator; + + /** + * create scheduler factory + */ + @Bean + public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("searchJobTrigger") Trigger searchJobTrigger) { + + SchedulerJobFactory jobFactory = new SchedulerJobFactory(); + jobFactory.setApplicationContext(applicationContext); + + Properties properties = new Properties(); + properties.putAll(quartzProperties.getProperties()); + + SchedulerFactoryBean factory = new SchedulerFactoryBean(); + factory.setOverwriteExistingJobs(true); + factory.setDataSource(dataSource); + factory.setQuartzProperties(properties); + factory.setJobFactory(jobFactory); + factory.setTriggers(searchJobTrigger); + return factory; + } + + @Bean(name = "searchJobTrigger") + public CronTriggerFactoryBean sampleJobTrigger(@Qualifier("quartzJobDetail") JobDetail jobDetail, + @Value("${samplejob.frequency}") String frequency) { + return createCronTrigger(jobDetail, frequency); + } + + private static CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String cronExpression) { + CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean(); + factoryBean.setJobDetail(jobDetail); + factoryBean.setCronExpression(cronExpression); + factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW); + return factoryBean; + } + + @Bean + public JobDetail quartzJobDetail() { + return jobCreator.createJob(MailingJobExecutor.class, true, applicationContext, "Send mail", "Mail Event Group"); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/SchedulerJobFactory.java b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/SchedulerJobFactory.java new file mode 100644 index 000000000..db35e10ab --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/SchedulerJobFactory.java @@ -0,0 +1,24 @@ +package dev.sunbirdrc.claim.quartz; + +import org.quartz.spi.TriggerFiredBundle; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.scheduling.quartz.SpringBeanJobFactory; + +public class SchedulerJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { + + private AutowireCapableBeanFactory beanFactory; + + @Override + public void setApplicationContext(final ApplicationContext context) { + beanFactory = context.getAutowireCapableBeanFactory(); + } + + @Override + protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { + final Object job = super.createJobInstance(bundle); + beanFactory.autowireBean(job); + return job; + } +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/RegulatorRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/RegulatorRepository.java new file mode 100644 index 000000000..bfb33a1ae --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/RegulatorRepository.java @@ -0,0 +1,15 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.Claim; +import dev.sunbirdrc.claim.entity.Regulator; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +//@Repository +public interface RegulatorRepository {//extends JpaRepository { + List findByCouncil(String council); + + List findByCouncilNot(String council); +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/RegulatorRowMapper.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/RegulatorRowMapper.java new file mode 100644 index 000000000..25d684de6 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/RegulatorRowMapper.java @@ -0,0 +1,23 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.Regulator; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class RegulatorRowMapper implements RowMapper { + @Override + public Regulator mapRow(ResultSet rs, int rowNum) throws SQLException { + return new Regulator( + rs.getString("ID"), + rs.getString("name"), + rs.getString("phoneNumber"), + rs.getString("council"), + rs.getString("email"), + rs.getString("osOwner"), + rs.getString("osid") + + ); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java index 1777c7096..2e9859ef0 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java @@ -1,20 +1,27 @@ package dev.sunbirdrc.claim.service; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import dev.sunbirdrc.claim.config.PropertyMapper; import dev.sunbirdrc.claim.controller.EmailController; import dev.sunbirdrc.claim.dto.CertificateMailDto; import dev.sunbirdrc.claim.dto.MailDto; import dev.sunbirdrc.claim.dto.PendingMailDTO; +import dev.sunbirdrc.claim.entity.Claim; +import dev.sunbirdrc.claim.entity.Regulator; import dev.sunbirdrc.claim.exception.ClaimMailException; +import dev.sunbirdrc.claim.model.ClaimStatus; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; +import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.FileSystemResource; +import org.springframework.lang.NonNull; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; @@ -29,9 +36,8 @@ import javax.mail.internet.MimeMessage; import java.io.File; import java.io.IOException; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; +import java.util.*; +import java.util.stream.Collectors; @Service("emailService") public class EmailService @@ -51,6 +57,12 @@ public class EmailService @Autowired private PropertyMapper propertyMapper; + + @Autowired + private ClaimService claimService; + + @Autowired + private RegulatorService regulatorService; /** * This method will send compose and send the message @@ -178,7 +190,8 @@ private String generateAttachedCertificateMailContent(CertificateMailDto certifi } @Async - public void sendPendingMail(PendingMailDTO pendingMailDTO) { + public void sendPendingMail(@NonNull List pendingMailDTOList, @NonNull String regulatorName, + @NonNull String regulatorEmail) { try { MimeMessage mimeMessage = mailSender.createMimeMessage(); @@ -186,9 +199,10 @@ public void sendPendingMail(PendingMailDTO pendingMailDTO) { MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); - mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(),pendingMailDTO.getName())); - mimeMessageHelper.setTo(pendingMailDTO.getEmailAddress()); - mimeMessageHelper.setText(generateCertificateMailContent(pendingMailDTO), true); + mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(), + "Pending Action Item")); + mimeMessageHelper.setTo(regulatorEmail); + mimeMessageHelper.setText(generatePendingMailContent(pendingMailDTOList, regulatorName), true); mailSender.send(mimeMessageHelper.getMimeMessage()); } catch (Exception e) { @@ -202,13 +216,13 @@ public void sendPendingMail(PendingMailDTO pendingMailDTO) { * @param mailDto * @return */ - private String generateCertificateMailContent(PendingMailDTO pendingMailDTO) { + private String generatePendingMailContent(@NonNull List pendingMailDTOList, + @NonNull String regulatorName) { String processedTemplateString = null; Map mailMap = new HashMap<>(); - mailMap.put("name", pendingMailDTO.getName()); - mailMap.put("council", pendingMailDTO.getCouncil()); - mailMap.put("itemName", pendingMailDTO.getItemName()); + mailMap.put("candidates", pendingMailDTOList); + mailMap.put("regulatorName", regulatorName); try { freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); @@ -224,4 +238,100 @@ private String generateCertificateMailContent(PendingMailDTO pendingMailDTO) { } return processedTemplateString; } + + public void sendForeignPendingItemMail() { + if (!regulatorService.isRegulatorTableExist()) { + logger.error(">>>>>>>>>>> Unable to find regulator table in database: No further process will be occurred"); + return; + } + + List allClaimList = claimService.findAll(); + + if (allClaimList != null && !allClaimList.isEmpty()) { + List foreignCouncilNames = getPendingForeignCouncilList(allClaimList); + + for (String foreignCouncilName : foreignCouncilNames) { + + List foreignCouncilClaims = allClaimList.stream() + .filter(claim -> foreignCouncilName.equalsIgnoreCase(getCouncilName(claim.getPropertyData()))) + .collect(Collectors.toList()); + + List pendingMailDTOList = collectEntityDetailsForMail(foreignCouncilClaims); + + List regulatorList = regulatorService.findByCouncil(foreignCouncilName); + + for (Regulator regulator : regulatorList) { + sendPendingMail(pendingMailDTOList, regulator.getName(), regulator.getEmail()); + } + } + } + } + + /** + * @param claimList + * @return + */ + private @NonNull List getPendingForeignCouncilList(@NonNull List claimList) { + List councilList = claimList.stream() + .filter(claim -> !propertyMapper.getUpCouncilName() + .equalsIgnoreCase(getCouncilName(claim.getPropertyData())) + ) + .filter(claim -> ClaimStatus.OPEN.name().equalsIgnoreCase(claim.getStatus())) + .map(claim -> getCouncilName(claim.getPropertyData())) + .distinct() + .collect(Collectors.toList()); + + if (councilList == null) { + logger.error(">>>>>>>> Unale to find any pending foreign council list"); + return Collections.emptyList(); + } else { + return councilList; + } + } + + private @NonNull List collectEntityDetailsForMail(@NonNull List claimList) { + List pendingMailDTOList = new ArrayList<>(); + + try { + for (Claim claim : claimList) { + String propertyData = claim.getPropertyData(); + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(propertyData); + + PendingMailDTO pendingMailDTO = PendingMailDTO.builder() + .course(jsonNode.get("courseName") != null ? jsonNode.get("courseName").asText() : "") + .emailAddress(jsonNode.get("email") != null ? jsonNode.get("email").asText() : "") + .refNo(jsonNode.get("refNo") != null ? jsonNode.get("refNo").asText() : "") + .name(jsonNode.get("name") != null ? jsonNode.get("name").asText() : "") + .registrationNumber(jsonNode.get("registrationNumber") != null ? jsonNode.get("registrationNumber").asText() : "") + .build(); + + pendingMailDTOList.add(pendingMailDTO); + } + } catch (Exception e) { + logger.error(">>>>>>>>>>> Unable to read council name from claim property data", e); + } + + + return pendingMailDTOList; + } + + private @NonNull String getCouncilName(String propertyData) { + String council = ""; + if (StringUtils.isEmpty(propertyData)) { + logger.error(">>>>>>> Error while fetching council name from property data in Claim"); + } + + try { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(propertyData); + council = jsonNode.get("council").asText(); + } catch (Exception e) { + logger.error(">>>>>>>>>>> Unable to read council name from claim property data", e); + } + + return council; + } + + } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java index 3de1b64da..ffb6e8e3d 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileService.java @@ -2,6 +2,7 @@ import dev.sunbirdrc.claim.dto.FileDto; import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.MediaType; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @@ -14,4 +15,6 @@ public interface FileService { FileDto uploadFile(MultipartFile file) throws IOException; List uploadMultipleFile(MultipartFile[] files, String entityName, String entityId); + + MediaType getFileMediaType(String fileName) throws Exception; } \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java index fc6f5ae99..917047bf4 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/FileServiceImpl.java @@ -6,11 +6,14 @@ import dev.sunbirdrc.claim.exception.GCPFileUploadException; import dev.sunbirdrc.claim.utils.GCPBucketUtil; import lombok.RequiredArgsConstructor; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @@ -21,6 +24,9 @@ import java.util.ArrayList; import java.util.List; +import static dev.sunbirdrc.claim.contants.AttributeNames.*; +import static dev.sunbirdrc.claim.contants.AttributeNames.PDF; + @Service @RequiredArgsConstructor @@ -71,6 +77,7 @@ public List uploadMultipleFile(MultipartFile[] files, String entityName for (MultipartFile file : files) { FileDto fileDto = new FileDto(); String originalFileName = entityName + "_" + entityId + "_" + file.getOriginalFilename(); + originalFileName = StringUtils.deleteWhitespace(originalFileName); Path path = new File(originalFileName).toPath(); try { @@ -87,4 +94,40 @@ public List uploadMultipleFile(MultipartFile[] files, String entityName } return fileDtoList; } + + /** + * @param fileName + * @return + * @throws Exception + */ + @Override + public MediaType getFileMediaType(String fileName) throws Exception { + if (StringUtils.isEmpty(fileName)) { + LOGGER.error("File name is either empty or blank - while finding file type"); + throw new Exception("File name is either empty or blank - while finding file type"); + } + + MediaType mediaType = MediaType.APPLICATION_PDF; + + String extension = FilenameUtils.getExtension(fileName); + extension = StringUtils.upperCase(extension); + + switch (extension) { + case JPG: + case JPEG: + mediaType = MediaType.IMAGE_JPEG; + break; + case PNG: + mediaType = MediaType.IMAGE_PNG; + break; + case PDF: + mediaType = MediaType.APPLICATION_PDF; + break; + default: + LOGGER.error("File type not supported"); + throw new Exception("File type not supported"); + } + + return mediaType; + } } \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/RegulatorService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/RegulatorService.java new file mode 100644 index 000000000..56a205eff --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/RegulatorService.java @@ -0,0 +1,44 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.config.PropertyMapper; +import dev.sunbirdrc.claim.entity.Regulator; +import dev.sunbirdrc.claim.repository.RegulatorRowMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class RegulatorService { + + @Autowired + private PropertyMapper propertyMapper; + + @Autowired + private JdbcTemplate jdbcTemplate; + + public List findByCouncil(String council) { + try { + return jdbcTemplate.query("SELECT * FROM \"V_Regulator\" where council=?", new RegulatorRowMapper(), + council); + + } catch (IncorrectResultSizeDataAccessException e) { + return null; + } + } + + public List findAll() { + return jdbcTemplate.query("SELECT * from \"V_Regulator\"", new RegulatorRowMapper()); + } + + public boolean isRegulatorTableExist() { + String sqlQuery = "SELECT count(*) FROM information_schema.tables WHERE table_name = '" + + propertyMapper.getRegulatorTableName() + "'"; + + Integer tableCount = jdbcTemplate.queryForObject(sqlQuery, Integer.class); + + return tableCount > 0; + } +} diff --git a/java/claim/src/main/resources/application.properties b/java/claim/src/main/resources/application.properties index fba93dc51..caaba96c9 100644 --- a/java/claim/src/main/resources/application.properties +++ b/java/claim/src/main/resources/application.properties @@ -6,6 +6,7 @@ spring.datasource.password=${connectionInfo_password:postgres} spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect spring.jpa.hibernate.ddl-auto=update +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true sunbirdrc.url=${sunbirdrc_url:http://localhost:8081} @@ -46,4 +47,31 @@ spring.servlet.multipart.max-request-size=10MB simple.mail.message.from = r.kishor.rahu@gmail.com foreign.pending.item.subject = Pending Item +#Pending Item config +up.council.name = upsmfac +regulator.table.name = V_Regulator + +#---------------------------- QUARTZ CONFIGS ---------------------------- +samplejob.frequency=0 40 15 ? * * * +#samplejob.frequency=0 */5 * ? * * + +quartz.enabled=true +spring.quartz.job-store-type=jdbc +spring.quartz.jdbc.initialize-schema=never + +spring.quartz.properties.org.quartz.scheduler.instanceName=quartz-mail-event +spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO +#spring.quartz.properties.org.quartz.scheduler.instanceIdGenerator.class=com.helixz.quartz.demo.component.CustomQuartzInstanceIdGenerator +spring.quartz.properties.org.quartz.threadPool.threadCount=20 +spring.quartz.properties.org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX +#spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate +spring.quartz.properties.org.quartz.jobStore.useProperties=true +spring.quartz.properties.org.quartz.jobStore.misfireThreshold=60000 +spring.quartz.properties.org.quartz.jobStore.tablePrefix=qrtz_ +spring.quartz.properties.org.quartz.jobStore.isClustered=true +spring.quartz.properties.org.quartz.plugin.shutdownHook.class=org.quartz.plugins.management.ShutdownHookPlugin +spring.quartz.properties.org.quartz.plugin.shutdownHook.cleanShutdown=TRUE +spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate +#------------------------------------------------------ + diff --git a/java/claim/src/main/resources/templates/pending-item-mail.ftl b/java/claim/src/main/resources/templates/pending-item-mail.ftl index 876281666..9214a878c 100644 --- a/java/claim/src/main/resources/templates/pending-item-mail.ftl +++ b/java/claim/src/main/resources/templates/pending-item-mail.ftl @@ -1,10 +1,45 @@ + + + + -

Hi ${name}

+

Hi ${regulatorName}

+ +

Following candidate has applied for registration certificate from your institution as claimed by candidate.

-

We have pending item for ${council}, which have been requested

+

Candidate list:

+

+ + + + + + + + + <#list candidates as candidate > + + + + + + + + +
NameCourseReference NumberRegistration NumberEmail
${candidate.name} ${candidate.course}${candidate.refNo}${candidate.registrationNumber}${candidate.emailAddress}
+

-
Item name:

${itemName}

+
your response awaited

Thank you,

< Registration Credential Issuing Authority >

diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index c3defa319..de6c9d53e 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -1244,30 +1244,5 @@ public ResponseEntity putSingleEntityFile( } } - @RequestMapping(value = "/api/v1/{entityName}/sendPendingForeignItemMail", method = RequestMethod.POST) - public ResponseEntity sendPendingForeignItemMail(@PathVariable String entityName, - @RequestBody PendingMailDTO pendingMailDTO, - HttpServletRequest request) { - - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.SEND, "OK", responseParams); - - try { - registryHelper.authorizeInviteEntity(request, entityName); - - String mailStatus = claimRequestClient.sendPendingForeignItemMail(pendingMailDTO); - - response.setResult(mailStatus); - responseParams.setStatus(Response.Status.SUCCESSFUL); - - } catch (Exception exception) { - logger.error("Exception : {}", exception.getMessage()); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(exception.getMessage()); - return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); - } - - return new ResponseEntity<>(response, HttpStatus.OK); - } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index dcf69acd4..badafa294 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -49,8 +49,6 @@ public class ClaimRequestClient { private static final String CLAIM_MULTI_FILE_UPLOAD = "/api/v1/files/upload/multiple"; private static String URL_APPENDER = "/"; - private static final String MAIL_SEND_PENDING_FOREIGN_ITEM_URL = "/api/v1/sendPendingForeignItemMail"; - ClaimRequestClient(@Value("${claims.url}") String claimRequestUrl, RestTemplate restTemplate) { this.claimRequestUrl = claimRequestUrl; this.restTemplate = restTemplate; @@ -218,13 +216,4 @@ public List uploadCLaimMultipleFiles(@NonNull MultipartFile[] files, St return fileDtoList; } - public String sendPendingForeignItemMail(PendingMailDTO pendingMailDTO) { - String mailStatus = restTemplate.postForObject( - claimRequestUrl + MAIL_SEND_PENDING_FOREIGN_ITEM_URL, pendingMailDTO, String.class); - logger.info("Pending foreign item mail status: " + mailStatus); - return mailStatus; - } - - - } From 037b69a1103b4619beb7c67ec70daa64590ba019 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 22 Aug 2023 12:52:56 +0530 Subject: [PATCH 25/43] student verification --- .../public/_schemas/studentForeignVerification.json | 3 ++- .../public/_schemas/studentGoodStanding.json | 13 +++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json index 90745ea79..db1bd861d 100644 --- a/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json +++ b/java/registry/src/main/resources/public/_schemas/studentForeignVerification.json @@ -274,7 +274,8 @@ "refNo": "{{refNo}}", "date": "{{date}}", "registrationNumber": "{{registrationNumber}}", - "workPlace": "{{workPlace}}" + "workPlace": "{{workPlace}}", + "docproof": "{{docproof}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json index 5f29b8d48..6cde1dd01 100644 --- a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json +++ b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json @@ -90,7 +90,7 @@ "type": "string", "title": "workPlace" }, - "doc-proof": { + "docproof": { "type": "string", "title": "All Document Proof" }, "paymentStatus": { @@ -113,7 +113,7 @@ "roles": ["StudentGoodstanding"], "attestationPolicies": [ { - "name": "studentVerification", + "name": "studentGoodstandingVerification", "conditions": "(ATTESTOR#$.council#.contains(REQUESTER#$.council#))", "type": "MANUAL", "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", @@ -130,7 +130,7 @@ "registrationNumber": "$.registrationNumber", "workPlace": "$.workPlace", "council":"$.council", - "doc-proof": "$.doc-proof", + "docproof": "$.docproof", "paymentStatus": "$.paymentStatus" }, "credentialTemplate": { @@ -220,8 +220,8 @@ "name": "schema:Text" } }, - "doc-proof": { - "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "docproof": { + "@id": "https://github.com/sunbird-specs/vc-specs#docproof", "@context": { "name": "schema:Text" } @@ -249,7 +249,8 @@ "professionalQualification": "{{professionalQualification}}", "trainingCenter": "{{trainingCenter}}", "registrationNumber": "{{registrationNumber}}", - "workPlace": "{{workPlace}}" + "workPlace": "{{workPlace}}", + "docproof": "{{docproof}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } From d36344d989bf571eabf30d057e16cb2af05bb044 Mon Sep 17 00:00:00 2001 From: rkrahu Date: Tue, 22 Aug 2023 13:10:26 +0530 Subject: [PATCH 26/43] Cred Type addition in pending action item. --- .../main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java | 2 +- .../java/dev/sunbirdrc/claim/service/EmailService.java | 2 +- .../java/dev/sunbirdrc/claim/service/RegulatorService.java | 7 ++++--- .../src/main/resources/templates/pending-item-mail.ftl | 4 ++-- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java index 525c7e7c3..b54401151 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java @@ -17,6 +17,6 @@ public class PendingMailDTO { private String refNo; private String regulatorName; private String regulatorEmail; - private String course; + private String credType; private String registrationNumber; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java index 2e9859ef0..ca5515935 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java @@ -299,7 +299,7 @@ public void sendForeignPendingItemMail() { JsonNode jsonNode = objectMapper.readTree(propertyData); PendingMailDTO pendingMailDTO = PendingMailDTO.builder() - .course(jsonNode.get("courseName") != null ? jsonNode.get("courseName").asText() : "") + .credType(jsonNode.get("credType") != null ? jsonNode.get("credType").asText() : "") .emailAddress(jsonNode.get("email") != null ? jsonNode.get("email").asText() : "") .refNo(jsonNode.get("refNo") != null ? jsonNode.get("refNo").asText() : "") .name(jsonNode.get("name") != null ? jsonNode.get("name").asText() : "") diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/RegulatorService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/RegulatorService.java index 56a205eff..678549a1a 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/RegulatorService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/RegulatorService.java @@ -21,8 +21,8 @@ public class RegulatorService { public List findByCouncil(String council) { try { - return jdbcTemplate.query("SELECT * FROM \"V_Regulator\" where council=?", new RegulatorRowMapper(), - council); + return jdbcTemplate.query("SELECT * FROM \"" + propertyMapper.getRegulatorTableName() + + "\" where council=?", new RegulatorRowMapper(), council); } catch (IncorrectResultSizeDataAccessException e) { return null; @@ -30,7 +30,8 @@ public List findByCouncil(String council) { } public List findAll() { - return jdbcTemplate.query("SELECT * from \"V_Regulator\"", new RegulatorRowMapper()); + return jdbcTemplate.query("SELECT * from \"" + propertyMapper.getRegulatorTableName() + "\"", + new RegulatorRowMapper()); } public boolean isRegulatorTableExist() { diff --git a/java/claim/src/main/resources/templates/pending-item-mail.ftl b/java/claim/src/main/resources/templates/pending-item-mail.ftl index 9214a878c..5f786b2d1 100644 --- a/java/claim/src/main/resources/templates/pending-item-mail.ftl +++ b/java/claim/src/main/resources/templates/pending-item-mail.ftl @@ -22,7 +22,7 @@ - + @@ -30,7 +30,7 @@ <#list candidates as candidate > - + From 9f2d0168eaa3bf033f7e1483e4b185f05e54d11d Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 22 Aug 2023 14:24:53 +0530 Subject: [PATCH 27/43] review changes --- .../dev/sunbirdrc/claim/controller/CoursesController.java | 2 +- .../java/dev/sunbirdrc/claim/controller/FileController.java | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java index 28e832590..15cbb5a67 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java @@ -20,7 +20,7 @@ public CoursesController(CoursesService coursesService) { this.coursesService = coursesService; } - @GetMapping + @GetMapping("/") public ResponseEntity> getAllCourses() { List courses = coursesService.getAllCourses(); return ResponseEntity.ok(courses); diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java index 7376d439a..267339141 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/FileController.java @@ -17,7 +17,7 @@ import java.util.List; @RestController -@RequestMapping("/api/v1/files/") +@RequestMapping("/api/v1/files") @RequiredArgsConstructor public class FileController { @@ -26,7 +26,7 @@ public class FileController { @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) - @RequestMapping("upload") + @RequestMapping("/upload") public ResponseEntity uploadFile( @RequestParam MultipartFile file) throws IOException { String fileUrl = null; @@ -38,7 +38,7 @@ public ResponseEntity uploadFile( return (ResponseEntity) ResponseEntity.status(HttpStatus.EXPECTATION_FAILED); } - @RequestMapping("download") + @RequestMapping("/download") @PostMapping(produces = {MediaType.APPLICATION_PDF_VALUE}) public ResponseEntity downloadFile( @RequestParam(value = "fileName", required = false) String fileName) { From abc8a4ca7f8b95b0f78997e47871d78399b3f51c Mon Sep 17 00:00:00 2001 From: rkrahu Date: Tue, 22 Aug 2023 14:47:21 +0530 Subject: [PATCH 28/43] Support direct call for send OTP and User creation mail. --- .../sunbirdrc/controller/UserController.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/java/user-management/src/main/java/dev/sunbirdrc/controller/UserController.java b/java/user-management/src/main/java/dev/sunbirdrc/controller/UserController.java index 249013317..5738d396a 100644 --- a/java/user-management/src/main/java/dev/sunbirdrc/controller/UserController.java +++ b/java/user-management/src/main/java/dev/sunbirdrc/controller/UserController.java @@ -2,6 +2,8 @@ import dev.sunbirdrc.dto.*; +import dev.sunbirdrc.entity.UserDetails; +import dev.sunbirdrc.service.MailService; import dev.sunbirdrc.service.UserService; import org.apache.commons.codec.binary.Base64; import org.springframework.beans.factory.annotation.Autowired; @@ -31,6 +33,9 @@ public class UserController { @Autowired private UserService userService; + @Autowired + private MailService mailService; + @PostMapping("/login") public ResponseEntity loginUser(@Valid @RequestBody UserLoginDTO userLoginDTO) { UserTokenDetailsDTO keycloakTokenDetailsDTO = userService.loginAndGenerateKeycloakToken(userLoginDTO); @@ -152,4 +157,26 @@ public ResponseEntity persistUserCredential(@RequestBody CustomUserDTO c return new ResponseEntity<>("Persist successfully", HttpStatus.OK); } + + @PostMapping("/keycloak/mail/sendOTP") + public ResponseEntity sendOTPMail(@RequestBody UserDetails userDetails) { + try { + mailService.sendOtpMail(userDetails); + } catch (Exception e) { + return new ResponseEntity<>("Failed to persist", HttpStatus.EXPECTATION_FAILED); + } + + return new ResponseEntity<>("Persist successfully", HttpStatus.OK); + } + + @PostMapping("/keycloak/mail/userCreate") + public ResponseEntity sendUserCreationMail(@RequestBody CustomUserDTO customUserDTO) { + try { + mailService.sendUserCreationNotification(customUserDTO); + } catch (Exception e) { + return new ResponseEntity<>("Failed to persist", HttpStatus.EXPECTATION_FAILED); + } + + return new ResponseEntity<>("Persist successfully", HttpStatus.OK); + } } From 54b2a9c2694f80fa2369eaf94ff1ab35ddf91ef8 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 22 Aug 2023 16:55:42 +0530 Subject: [PATCH 29/43] diploma change --- .../public/_schemas/studentFromUP.json | 24 ++++++++++++++++--- .../public/_schemas/studentGoodStanding.json | 2 +- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index c48b1ea2c..a8b3270ed 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -105,7 +105,9 @@ "BLOOD_TRANSFUSION_REG", "BLOOD_TRANSFUSION_DIPLOMA" ]}, - "docproof":{"type": "string","title": "docproof"} + "docproof":{"type": "string","title": "docproof"}, + "regNumber":{"type": "string","title": "regNumber"}, + "diplomaNumber":{"type": "string","title": "diplomaNumber"} } } }, @@ -154,7 +156,9 @@ "centerCode": "$.centerCode", "paymentStatus": "$.paymentStatus", "credType": "$.credType", - "docproof": "$.docproof" + "docproof": "$.docproof", + "regNumber": "$.regNumber", + "diplomaNumber": "$.diplomaNumber" }, "credentialTemplate": { "@context": [ @@ -337,6 +341,18 @@ "@context": { "name": "schema:Text" } + }, + "regNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#regNumber", + "@context": { + "name": "schema:Text" + } + }, + "diplomaNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#diplomaNumber", + "@context": { + "name": "schema:Text" + } } } ], @@ -372,7 +388,9 @@ "centerCode": "{{centerCode}}", "paymentStatus": "{{paymentStatus}}", "credType":"{{credType}}", - "docproof": "{{docproof}}" + "docproof": "{{docproof}}", + "regNumber": "{{regNumber}}", + "diplomaNumber": "{{diplomaNumber}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json index 6cde1dd01..d6b3a63ca 100644 --- a/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json +++ b/java/registry/src/main/resources/public/_schemas/studentGoodStanding.json @@ -28,7 +28,7 @@ "type": "string", "title": "name" }, - "marriedName": { + "marriedName": { "$id": "#/properties/marriedName", "type": "string", "title": "marriedName" From 37247757a977a47fd074d762c379aaec93d5fbb9 Mon Sep 17 00:00:00 2001 From: rkrahu Date: Wed, 23 Aug 2023 10:42:45 +0530 Subject: [PATCH 30/43] Send manual pending action item for foreign student --- .../claim/controller/EmailController.java | 6 +++ .../sunbirdrc/claim/service/EmailService.java | 47 +++++++++++++++++++ .../templates/manual-pending-item-mail.ftl | 12 +++++ .../controller/RegistryEntityController.java | 30 ++++++++++++ .../model/dto/ManualPendingMailDTO.java | 15 ++++++ .../registry/util/ClaimRequestClient.java | 14 ++++-- 6 files changed, 120 insertions(+), 4 deletions(-) create mode 100644 java/claim/src/main/resources/templates/manual-pending-item-mail.ftl create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/ManualPendingMailDTO.java diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java index c8bcfa046..d41cf3e54 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java @@ -119,4 +119,10 @@ public ResponseEntity sendCertificateMail(@RequestBody CertificateMailDt return new ResponseEntity<>("Mail is sending", HttpStatus.OK); } + @RequestMapping(value = "/api/v1/sendPendingForeignItemMail", method = RequestMethod.POST) + public ResponseEntity sendPendingItemMail(@RequestHeader HttpHeaders headers, + @RequestBody PendingMailDTO pendingMailDTO) { + emailService.sendManualPendingMail(pendingMailDTO); + return new ResponseEntity<>("Mail is sending", HttpStatus.OK); + } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java index ca5515935..6ded2a89c 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java @@ -333,5 +333,52 @@ public void sendForeignPendingItemMail() { return council; } + @Async + public void sendManualPendingMail(PendingMailDTO pendingMailDTO) { + + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + + MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + + mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); + mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(),pendingMailDTO.getName())); + mimeMessageHelper.setTo(pendingMailDTO.getEmailAddress()); + mimeMessageHelper.setText(generateManualPendingMailContent(pendingMailDTO), true); + + mailSender.send(mimeMessageHelper.getMimeMessage()); + } catch (Exception e) { + logger.error("Exception while sending mail: ", e); + throw new ClaimMailException("Exception while composing and sending mail with OTP"); + } + + } + + /** + * @param mailDto + * @return + */ + private String generateManualPendingMailContent(PendingMailDTO pendingMailDTO) { + String processedTemplateString = null; + + Map mailMap = new HashMap<>(); + mailMap.put("name", pendingMailDTO.getName()); + mailMap.put("council", pendingMailDTO.getCouncil()); + mailMap.put("itemName", pendingMailDTO.getItemName()); + + try { + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("manual-pending-item-mail.ftl"); + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + + } catch (TemplateException e) { + logger.error("TemplateException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } catch (IOException e) { + logger.error("IOException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } + return processedTemplateString; + } } diff --git a/java/claim/src/main/resources/templates/manual-pending-item-mail.ftl b/java/claim/src/main/resources/templates/manual-pending-item-mail.ftl new file mode 100644 index 000000000..9b7a765d5 --- /dev/null +++ b/java/claim/src/main/resources/templates/manual-pending-item-mail.ftl @@ -0,0 +1,12 @@ + + +

Hi ${name}

+ +

We have pending item for ${council}, which have been requested

+ +
Item name:

${itemName}

+ +

Thank you,

+

< Registration Credential Issuing Authority >

+ + \ No newline at end of file diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 909e3458d..c225777ed 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -26,11 +26,13 @@ import dev.sunbirdrc.registry.middleware.util.JSONUtil; import dev.sunbirdrc.registry.middleware.util.OSSystemFields; import dev.sunbirdrc.registry.model.dto.MailDto; +import dev.sunbirdrc.registry.model.dto.ManualPendingMailDTO; import dev.sunbirdrc.registry.service.FileStorageService; import dev.sunbirdrc.registry.service.impl.CertificateServiceImpl; import dev.sunbirdrc.registry.transform.Configuration; import dev.sunbirdrc.registry.transform.Data; import dev.sunbirdrc.registry.transform.ITransformer; +import dev.sunbirdrc.registry.util.ClaimRequestClient; import org.agrona.Strings; import dev.sunbirdrc.registry.util.DigiLockerUtils; import dev.sunbirdrc.registry.util.DocDetails; @@ -87,6 +89,9 @@ public class RegistryEntityController extends AbstractController { @Autowired private ViewTemplateManager viewTemplateManager; + @Autowired + private ClaimRequestClient claimRequestClient; + @Value("${authentication.enabled:true}") boolean securityEnabled; @Value("${certificate.enableExternalTemplates:false}") @@ -1433,5 +1438,30 @@ public JsonNode searchEntity(ObjectNode searchNode, String entityName) { return result; } + @RequestMapping(value = "/api/v1/{entityName}/sendPendingForeignItemMail", method = RequestMethod.POST) + public ResponseEntity sendPendingForeignItemMail(@PathVariable String entityName, + @RequestBody ManualPendingMailDTO pendingMailDTO, + HttpServletRequest request) { + + ResponseParams responseParams = new ResponseParams(); + Response response = new Response(Response.API_ID.SEND, "OK", responseParams); + + try { + registryHelper.authorizeInviteEntity(request, entityName); + + String mailStatus = claimRequestClient.sendPendingForeignItemMail(pendingMailDTO); + + response.setResult(mailStatus); + responseParams.setStatus(Response.Status.SUCCESSFUL); + + } catch (Exception exception) { + logger.error("Exception : {}", exception.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(exception.getMessage()); + return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); + } + + return new ResponseEntity<>(response, HttpStatus.OK); + } } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/ManualPendingMailDTO.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/ManualPendingMailDTO.java new file mode 100644 index 000000000..fcb67e61a --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/ManualPendingMailDTO.java @@ -0,0 +1,15 @@ +package dev.sunbirdrc.registry.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ManualPendingMailDTO { + private String name; + private String emailAddress; + private String council; + private String itemName; +} diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index 3c28fae27..8baa0a608 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -6,10 +6,7 @@ import dev.sunbirdrc.pojos.dto.ClaimDTO; import dev.sunbirdrc.registry.controller.RegistryController; import dev.sunbirdrc.registry.dao.Learner; -import dev.sunbirdrc.registry.model.dto.BarCode; -import dev.sunbirdrc.registry.model.dto.FileDto; -import dev.sunbirdrc.registry.model.dto.MailDto; -import dev.sunbirdrc.registry.model.dto.PendingMailDTO; +import dev.sunbirdrc.registry.model.dto.*; import lombok.NonNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -49,6 +46,8 @@ public class ClaimRequestClient { private static final String CLAIM_MULTI_FILE_UPLOAD = "/api/v1/files/upload/multiple"; private static String URL_APPENDER = "/"; + private static final String MAIL_SEND_PENDING_FOREIGN_ITEM_URL = "/api/v1/sendPendingForeignItemMail"; + ClaimRequestClient(@Value("${claims.url}") String claimRequestUrl, RestTemplate restTemplate) { this.claimRequestUrl = claimRequestUrl; this.restTemplate = restTemplate; @@ -243,4 +242,11 @@ public List uploadCLaimMultipleFiles(@NonNull MultipartFile[] files, St return fileDtoList; } + public String sendPendingForeignItemMail(ManualPendingMailDTO pendingMailDTO) { + String mailStatus = restTemplate.postForObject( + claimRequestUrl + MAIL_SEND_PENDING_FOREIGN_ITEM_URL, pendingMailDTO, String.class); + + logger.info("Pending foreign item mail status: " + mailStatus); + return mailStatus; + } } From 3b0e50e942bf1ae7783cbcea8779b86c2e446964 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Wed, 23 Aug 2023 11:28:21 +0530 Subject: [PATCH 31/43] claim get course --- .../claim/controller/CoursesController.java | 24 +++++++++++++++++++ .../dev/sunbirdrc/claim/entity/Courses.java | 9 +++++-- .../claim/repository/CoursesRepository.java | 14 +++++++++++ .../claim/service/CoursesService.java | 14 +++++++++++ 4 files changed, 59 insertions(+), 2 deletions(-) diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java index 15cbb5a67..e33eed2b8 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java @@ -37,6 +37,30 @@ public ResponseEntity getCourseById(@PathVariable Long id) { } } + @GetMapping("/category/{category}") + public ResponseEntity getCourseByName(@PathVariable String category) { + Optional course = coursesService.getCourseByCourse(category); + + if (course.isPresent()) { + return ResponseEntity.ok(course.get()); + } else { + return ResponseEntity.notFound().build(); + } + } + + @GetMapping("/diploma/{category}") + public ResponseEntity> getCourseByCategory(@PathVariable String category) { + List course = coursesService.getCourseByCategory(category); + return ResponseEntity.ok(course); + } + + @GetMapping("/course-short-name/{courseName}") + public ResponseEntity getCourseShortName(@PathVariable String courseName) { + courseName = courseName.replace(" ",""); + String course = coursesService.getCourseShortName(courseName); + return ResponseEntity.ok(course); + } + @PostMapping public ResponseEntity createCourse(@RequestBody Courses course) { Courses savedCourse = coursesService.createCourse(course); diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Courses.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Courses.java index 3db428b7d..9f01862da 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Courses.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Courses.java @@ -17,8 +17,13 @@ public class Courses { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @Column(name = "name") - private String name; + @Column(name = "category") + private String category; + @Column(name = "courseName") + private String courseName; + + @Column(name = "courseNameKey") + private String courseNameKey; @Column(name = "shortName") private String shortName; diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java index 942c07272..4c5e8c04a 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java @@ -1,8 +1,22 @@ package dev.sunbirdrc.claim.repository; +import dev.sunbirdrc.claim.entity.Course; import dev.sunbirdrc.claim.entity.Courses; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; +import java.util.Optional; public interface CoursesRepository extends JpaRepository { + Optional findByCategory(String category); + @Query("SELECT c.courseName FROM Courses c WHERE c.category = :value") + List findByFieldName(@Param("value") String value); + + @Query("SELECT c.shortName FROM Courses c WHERE c.courseName = :value") + String findByCouseName(@Param("value") String value); + + } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java index 1a72beb26..e1e20c4c3 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java @@ -26,7 +26,21 @@ public Optional getCourseById(Long id) { return coursesRepository.findById(id); } + public Optional getCourseByCourse(String category) { + return coursesRepository.findByCategory(category); + } + + public List getCourseByCategory(String category) { + return coursesRepository.findByFieldName(category); + } + + //findByCouseName + public String getCourseShortName(String courseName) { + return coursesRepository.findByCouseName(courseName); + } public Courses createCourse(Courses course) { return coursesRepository.save(course); } + + } From 5d3871fc8590043cddf783e1f085bfcd4e74ea7d Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Wed, 23 Aug 2023 17:24:54 +0530 Subject: [PATCH 32/43] outside up --- .../claim/controller/EventController.java | 41 ++ .../dev/sunbirdrc/claim/entity/Event.java | 31 + .../claim/repository/EventRepository.java | 7 + .../sunbirdrc/claim/service/EventService.java | 32 ++ .../registry/config/SecurityConfig.java | 2 +- .../controller/RegistryClaimsController.java | 31 +- .../sunbirdrc/registry/util/CommonUtils.java | 17 + .../public/_schemas/studentFromUP.json | 44 +- .../public/_schemas/studentOutsideUp.json | 540 +++++++++--------- 9 files changed, 465 insertions(+), 280 deletions(-) create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/controller/EventController.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/Event.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/EventRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/EventService.java create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/CommonUtils.java diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EventController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EventController.java new file mode 100644 index 000000000..3bc253816 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EventController.java @@ -0,0 +1,41 @@ +package dev.sunbirdrc.claim.controller; + +import dev.sunbirdrc.claim.entity.Event; +import dev.sunbirdrc.claim.service.EventService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/v1/api/events") +public class EventController { + private final EventService eventService; + + @Autowired + public EventController(EventService eventService) { + this.eventService = eventService; + } + + @PostMapping("/") + public ResponseEntity saveEvent(@RequestBody Event event) { + Event savedEvent = eventService.saveEvent(event); + return new ResponseEntity<>(savedEvent, HttpStatus.CREATED); + } + + @GetMapping("/") + public ResponseEntity> getAllEvents() { + List events = eventService.getAllEvents(); + return new ResponseEntity<>(events, HttpStatus.OK); + } + + @GetMapping("/{id}") + public ResponseEntity getEventById(@PathVariable Long id) { + Optional event = eventService.getEventById(id); + return event.map(value -> new ResponseEntity<>(value, HttpStatus.OK)) + .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Event.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Event.java new file mode 100644 index 000000000..f412ca9f3 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Event.java @@ -0,0 +1,31 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class Event { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "eid") + private String eid; + + @Column(name = "ets") + private Long ets; + + @Column(name = "ver") + private String ver; + + @Column(name = "mid") + private String mid; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/EventRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/EventRepository.java new file mode 100644 index 000000000..a7c4c79e3 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/EventRepository.java @@ -0,0 +1,7 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.Event; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface EventRepository extends JpaRepository { +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EventService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EventService.java new file mode 100644 index 000000000..2e9a11416 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EventService.java @@ -0,0 +1,32 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.entity.Event; +import dev.sunbirdrc.claim.repository.EventRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class EventService { + private final EventRepository eventRepository; + + @Autowired + public EventService(EventRepository eventRepository) { + this.eventRepository = eventRepository; + } + + public Event saveEvent(Event event) { + return eventRepository.save(event); + } + + public List getAllEvents() { + return eventRepository.findAll(); + } + + public Optional getEventById(Long id) { + return eventRepository.findById(id); + } +} + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SecurityConfig.java b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SecurityConfig.java index 17488176b..719432def 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/config/SecurityConfig.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/config/SecurityConfig.java @@ -59,7 +59,7 @@ protected void configure(HttpSecurity http) throws Exception { HttpSecurity httpConfig = http.csrf().disable(); if (authenticationEnabled) { httpConfig.authorizeRequests() - .antMatchers("/**/invite", "/health", "/error", + .antMatchers("/**/invite","/**/v2/{entityName}/claims", "/health", "/error", "/_schemas/**", "/**/templates/**", "/**/*.json", "/**/verify", "/swagger-ui", "/**/search", "/**/attestation/**", "/api/docs/swagger.json","/api/docs/*.json", "/plugin/**", "/swagger-ui.html","/api/v1/pullUriRequest/*","/api/v1/pullDocUriRequest/*") diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java index 68ba73b5c..e268a25a0 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryClaimsController.java @@ -12,6 +12,7 @@ import dev.sunbirdrc.registry.middleware.util.JSONUtil; import dev.sunbirdrc.registry.model.dto.AttestationRequest; import dev.sunbirdrc.registry.util.ClaimRequestClient; +import dev.sunbirdrc.registry.util.CommonUtils; import dev.sunbirdrc.registry.util.IDefinitionsManager; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; @@ -24,7 +25,9 @@ import org.springframework.web.client.HttpServerErrorException; import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import static dev.sunbirdrc.registry.middleware.util.Constants.USER_ID; @@ -61,18 +64,36 @@ public ResponseEntity getAllClaims(@PathVariable String entityName, Page @RequestMapping(value = "/api/v2/{entityName}/claims", method = RequestMethod.GET) public ResponseEntity getStudentsClaims(@PathVariable String entityName, Pageable pageable, HttpServletRequest request) { + List entityList = CommonUtils.getEntityName(); + ResponseEntity objectResponseEntity = null; + List list = new ArrayList(); + JsonNode claims = null; try { - JsonNode result = registryHelper.getRequestedUserDetails(request, entityName); - JsonNode claims = claimRequestClient.getStudentsClaims(result.get(entityName).get(0).get("email"), pageable, entityName); - logger.info("Received {} claims", claims.size()); - return new ResponseEntity<>(claims, HttpStatus.OK); + for (String entityName1:entityList) { + JsonNode result = registryHelper.getRequestedUserDetails(request, entityName1); + if(result!=null) { + JsonNode jsonNode = result.get(entityName1); + if(jsonNode!=null && jsonNode.size()>0) { + JsonNode email = jsonNode.get(0).get("email"); + if(email!=null) { + claims = claimRequestClient.getStudentsClaims(email, pageable, entityName1); + break; + } + logger.info("Received {} claims", claims.size()); + } + } + } + objectResponseEntity = new ResponseEntity<>(claims, HttpStatus.OK); } catch (Exception e) { logger.error("Fetching claims failed {}", e.getMessage()); e.printStackTrace(); - return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + return objectResponseEntity; } + + @RequestMapping(value = "/api/v1/{entityName}/claims/{claimId}", method = RequestMethod.GET) public ResponseEntity getClaim(@PathVariable String entityName, @PathVariable String claimId, HttpServletRequest request) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/CommonUtils.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/CommonUtils.java new file mode 100644 index 000000000..f696675fc --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/CommonUtils.java @@ -0,0 +1,17 @@ +package dev.sunbirdrc.registry.util; + +import java.util.ArrayList; +import java.util.List; + +public class CommonUtils { + + public static List getEntityName() { + List entityList = new ArrayList<>(); + entityList.add("StudentFromUP"); + entityList.add("StudentGoodstanding"); + entityList.add("StudentForeignVerification"); + entityList.add("StudentOutsideUP"); + return entityList; + } + +} diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index a8b3270ed..6c63e5db6 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -107,7 +107,11 @@ ]}, "docproof":{"type": "string","title": "docproof"}, "regNumber":{"type": "string","title": "regNumber"}, - "diplomaNumber":{"type": "string","title": "diplomaNumber"} + "diplomaNumber":{"type": "string","title": "diplomaNumber"}, + "nurseRegNo": {"type": "string","title": "nurseRegNo"}, + "nurseRegdate": {"type": "string","title": "nurseRegdate"}, + "courseState": {"type": "string","title": "courseState"}, + "courseCouncil": {"type": "string","title": "courseCouncil"} } } }, @@ -121,7 +125,7 @@ } ], "inviteRoles": ["anonymous"], - "roles": ["StudentFromUP"], + "roles": ["StudentFromUP","StudentOutsideUP"], "attestationPolicies": [ { "name": "studentVerification", @@ -158,7 +162,11 @@ "credType": "$.credType", "docproof": "$.docproof", "regNumber": "$.regNumber", - "diplomaNumber": "$.diplomaNumber" + "diplomaNumber": "$.diplomaNumber", + "nurseRegNo": "$.nurseRegNo", + "nurseRegDate": "$.nurseRegDate", + "courseState": "$.courseState", + "courseCouncil": "$.courseCouncil" }, "credentialTemplate": { "@context": [ @@ -353,6 +361,30 @@ "@context": { "name": "schema:Text" } + }, + "nurseRegNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#nurseRegNo", + "@context": { + "name": "schema:Text" + } + }, + "nurseRegDate": { + "@id": "https://github.com/sunbird-specs/vc-specs#nurseRegDate", + "@context": { + "name": "schema:Text" + } + }, + "courseState": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseState", + "@context": { + "name": "schema:Text" + } + }, + "courseCouncil": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseCouncil", + "@context": { + "name": "schema:Text" + } } } ], @@ -390,7 +422,11 @@ "credType":"{{credType}}", "docproof": "{{docproof}}", "regNumber": "{{regNumber}}", - "diplomaNumber": "{{diplomaNumber}}" + "diplomaNumber": "{{diplomaNumber}}", + "nurseRegNo": "{{nurseRegNo}}", + "nurseRegDate": "{{nurseRegDate}}", + "courseState": "{{courseState}}", + "courseCouncil": "{{courseCouncil}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json index 542a9e808..fd6bad2ce 100644 --- a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -1,11 +1,7 @@ { "$schema": "http://json-schema.org/draft-07/schema", "type": "object", - "properties": { - "StudentOutsideUP": { - "$ref": "#/definitions/StudentOutsideUP" - } - }, + "properties": { "StudentOutsideUP": { "$ref": "#/definitions/StudentOutsideUP" } }, "required": ["StudentOutsideUP"], "title": "StudentOutsideUP", "definitions": { @@ -14,224 +10,113 @@ "type": "object", "title": "StudentOutsideUP", "required": ["name", "phoneNumber", "email", "council"], + "uniqueIndexFields": ["phoneNumber"], "properties": { - "registrationType": { - "$id": "#/properties/registrationType", - "type": "string", - "title": "registrationType" - }, - "name": { - "type": "string" - }, - "phoneNumber": { - "type": "string" - }, - "email": { - "type": "string" - }, - "mothersName": { - "$id": "#/properties/mothersName", - "type": "string", - "title": "motherName" - }, - "fathersName": { - "$id": "#/properties/fathersName", - "type": "string", - "title": "fatherName" - }, - "dateOfBirth": { - "$id": "#/properties/dateOfBirth", - "type": "string", - "title": "dateOfBirth" - }, - "aadhaarNo": { - "$id": "#/properties/aadhaarNo", - "type": "string", - "title": "aadhaarNo" - }, - "barCode": { - "$id": "#/properties/barCode", - "type": "string", - "title": "barCode" - }, - "candidatePic": { - "$id": "#/properties/candidatePic", - "type": "string", - "title": "candidatePic" - }, - "gender": { - "$id": "#/properties/gender", - "type": "string", - "title": "gender", - "enum": ["male", "female"] - }, - "address": { - "type": "object", - "title": "address", - "required": [], - "properties": { - "address-text": { - "type": "string", - "title": "Plot" - }, - "state": { - "$id": "#/properties/state", - "type": "string", - "title": "State", - "enum": [ - "Andaman and Nicobar Islands", - "Andhra Pradesh", - "Arunachal Pradesh", - "Assam", - "Bihar", - "Chandigarh", - "Chhattisgarh", - "Dadra and Nagar Haveli", - "Daman and Diu", - "Delhi", - "Goa", - "Gujarat", - "Haryana", - "Himachal Pradesh", - "Jammu and Kashmir", - "Jharkhand", - "Karnataka", - "Kerala", - "Ladakh", - "Lakshadweep", - "Madhya Pradesh", - "Maharashtra", - "Manipur", - "Meghalaya", - "Mizoram", - "Nagaland", - "Odisha", - "Puducherry", - "Punjab", - "Rajasthan", - "Sikkim", - "Tamil Nadu", - "Telangana", - "Tripura", - "Uttar Pradesh", - "Uttarakhand", - "West Bengal" - ] - }, - "district": { - "$id": "#/properties/district", - "type": "string", - "title": "district" - }, - "country": { - "$id": "#/properties/country", - "type": "string", - "title": "country" - }, - "pincode": { - "$id": "#/properties/pincode", - "type": "string", - "title": "pincode" - } - } - }, - "courseName": { - "$id": "#/properties/courseName", - "type": "string", - "title": "courseName" - }, - "nursingCollage": { - "$id": "#/properties/nursingCollage", - "type": "string", - "title": "nursingCollage" - }, - "joiningMonth": { - "$id": "#/properties/joiningMonth", - "type": "string", - "title": "joiningMonth" - }, - "joiningYear": { - "$id": "#/properties/joiningYear", - "type": "string", - "title": "joiningYear" - }, - "passingMonth": { - "$id": "#/properties/passingMonth", - "type": "string", - "title": "passingMonth" - }, - "passingYear": { - "$id": "#/properties/passingYear", - "type": "string", - "title": "passingYear" - }, - "finalYearRollNo": { - "$id": "#/properties/finalYearRollNo", - "type": "string", - "title": "finalYearRollNo" - }, - "examBody": { - "$id": "#/properties/examBody", - "type": "string", - "title": "examBody" - }, - "courseState": { - "$id": "#/properties/courseState", - "type": "string", - "title": "courseState" - }, - "council": { - "$id": "#/properties/council", - "type": "string", - "title": "council" - }, - "registrationNo": { - "$id": "#/properties/registrationNo", - "type": "string", - "title": "registrationNo" - }, - "date": { - "$id": "#/properties/date", - "type": "string", - "title": "date" - } - } - }, - "nurseRegistration": { - "type": "object", - "properties": { - "nurseRegNo": { - "$id": "#/properties/nurseRegNo", - "type": "string", - "title": "nurseRegNo" - }, - "nurseRegDate": { - "$id": "#/properties/nurseRegDate", - "type": "string", - "title": "nurseRegDate" - }, - "date": { - "$id": "#/properties/date", - "type": "string", - "title": "date" - } + "name": { "type": "string" }, + "phoneNumber": { "type": "string" }, + "email": { "type": "string" }, + "council": { "type": "string" }, + "mothersName": {"type": "string", "title": "motherName"}, + "fathersName": { "type": "string","title": "fatherName"}, + "dateOfBirth": {"type": "string", "title": "dateOfBirth"}, + "aadhaarNo": {"type": "string", "title": "aadhaarNo"}, + "gender": {"type": "string", "title": "gender", "enum": ["male", "female"]}, + "address": {"type": "string", "title": "address"}, + "state": { "type": "string", "title": "State","enum": [ + "Andaman and Nicobar Islands", + "Andhra Pradesh", + "Arunachal Pradesh", + "Assam", + "Bihar", + "Chandigarh", + "Chhattisgarh", + "Dadra and Nagar Haveli", + "Daman and Diu", + "Delhi", + "Goa", + "Gujarat", + "Haryana", + "Himachal Pradesh", + "Jammu and Kashmir", + "Jharkhand", + "Karnataka", + "Kerala", + "Ladakh", + "Lakshadweep", + "Madhya Pradesh", + "Maharashtra", + "Manipur", + "Meghalaya", + "Mizoram", + "Nagaland", + "Odisha", + "Puducherry", + "Punjab", + "Rajasthan", + "Sikkim", + "Tamil Nadu", + "Telangana", + "Tripura", + "Uttar Pradesh", + "Uttarakhand", + "West Bengal" + ] }, + "district": {"type": "string", "title": "district"}, + "country": {"type": "string", "title": "country"}, + "pincode": {"type": "string", "title": "pincode"}, + "candidatePic": {"type": "string", "title": "candidatePic"}, + "courseName": {"type": "string","title": "courseName"}, + "nursingCollage": {"type": "string", "title": "nursingCollage"}, + "joiningMonth": {"type": "string","title": "joiningMonth"}, + "joiningYear": {"type": "string", "title": "joiningYear"}, + "passingMonth": {"type": "string", "title": "passingMonth"}, + "passingYear": {"type": "string","title": "passingYear"}, + "examYear": {"type": "string","title": "examYear"}, + "examBody":{"type": "string","title": "examBody"}, + "centerCode": {"type": "string","title": "centerCode"}, + "paymentStatus":{"type": "string","title": "paymentStatus"}, + "credType":{"type": "string","title": "credType", "enum":[ + "ANM_DIPLOMA", + "ANM_REG", + "BABY_DIPLOMA", + "BABY_REG", + "BSC_NURSING", + "DEGREE", + "ETCA_REG", + "ETCA_DIPLOMA", + "ETCT_REG", + "ETCT_DIPLOMA", + "GNM_REG", + "GNM_DIPLOMA", + "PHARMACY_DIPLOMA", + "GOODSTANDING_REG", + "FOREIGN_REG", + "MSC_REG", + "PBBSC_REG", + "SANITATION_REG", + "SANITATION_DIPLOMA", + "PHYSIOTHERAPY_DIPLOMA", + "OPTOMETRY_REG", + "OPTOMETRY_DIPLOMA", + "OTTECHNICIAN_REG", + "OTTECHNICIAN_DIPLOMA", + "CARDIOLOGY_REG", + "CARDIOLOGY_DIPLOMA", + "BLOOD_TRANSFUSION_REG", + "BLOOD_TRANSFUSION_DIPLOMA" + ]}, + "docproof":{"type": "string","title": "docproof"}, + "regNumber":{"type": "string","title": "regNumber"}, + "diplomaNumber":{"type": "string","title": "diplomaNumber"}, + "nurseRegNo": {"type": "string","title": "nurseRegNo"}, + "nurseRegdate": {"type": "string","title": "nurseRegdate"}, + "courseState": {"type": "string","title": "courseState"}, + "courseCouncil": {"type": "string","title": "courseCouncil"} } - }, - "doc-proof": { - "type": "array", - "items": { - "type": "string" - }, - "title": "All Document Proof" - }, - "paymentStatus": { - "$id": "#/properties/paymentStatus", - "type": "string", - "title": "paymentStatus" } }, - "_osConfig": { + "ownershipAttributes": [ { "email": "/email", @@ -249,24 +134,39 @@ "attestorPlugin": "did:internal:ClaimPluginActor?entity=Regulator", "attestationProperties": { "name": "$.name", + "email": "$.email", + "phoneNumber": "$.phoneNumber", + "council": "$.council", "mothersName": "$.mothersName", "fathersName": "$.fathersName", + "dateOfBirth": "$.dateOfBirth", + "aadhaarNo": "$.aadhaarNo", + "gender": "$.gender", + "address": "$.address", + "state":"$.state", + "district": "$.district", + "country": "$.country", + "pincode": "$.pincode", + "candidatePic": "$.candidatePic", "courseName": "$.courseName", + "nursingCollage": "$.nursingCollage", "joiningMonth": "$.joiningMonth", - "joiningYear": "$.joiningYear", - "passingMonth": "$.passingMonth", + "joiningYear": "$.joiningYear", + "passingMonth": "$.passingMonth", "passingYear": "$.passingYear", - "examBody": "$.examBody", "finalYearRollNo": "$.finalYearRollNo", - "courseState": "$.courseState", - "council": "$.council", - "registrationNo": "$.registrationNo", + "examBody": "$.examBody", + "examYear": "$.examYear", + "centerCode": "$.centerCode", + "paymentStatus": "$.paymentStatus", + "credType": "$.credType", + "docproof": "$.docproof", + "regNumber": "$.regNumber", + "diplomaNumber": "$.diplomaNumber", "nurseRegNo": "$.nurseRegNo", "nurseRegDate": "$.nurseRegDate", - "date": "$.date", - "doc-proof": "$.doc-proof", - "candidatePic": "$.candidatePic", - "paymentStatus": "$.paymentStatus" + "courseState": "$.courseState", + "courseCouncil": "$.courseCouncil" }, "credentialTemplate": { "@context": [ @@ -289,26 +189,91 @@ "name": "schema:Text" } }, - "trainedOn": { - "@id": "https://github.com/sunbird-specs/vc-specs#trainedOn", + "phoneNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#phoneNumber", "@context": { "name": "schema:Text" - } - }, + }}, + "email": { + "@id": "https://github.com/sunbird-specs/vc-specs#email", + "@context": { + "name": "schema:Text" + }}, + "council": { + "@id": "https://github.com/sunbird-specs/vc-specs#council", + "@context": { + "name": "schema:Text" + }}, "mothersName": { "@id": "https://github.com/sunbird-specs/vc-specs#mothersName", + "@context": { + "name": "schema:Text" + }}, + "fathersName": { + "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "@context": { + "name": "schema:Text" + }}, + "dateOfBirth": { + "@id": "https://github.com/sunbird-specs/vc-specs#dateOfBirth", + "@context": { + "name": "schema:Text" + }}, + "aadhaarNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#aadhaarNo", + "@context": { + "name": "schema:Text" + }}, + "gender": { + "@id": "https://github.com/sunbird-specs/vc-specs#gender", "@context": { "name": "schema:Text" } }, - "passingMonth": { - "@id": "https://github.com/sunbird-specs/vc-specs#passingMonth", + "address": { + "@id": "https://github.com/sunbird-specs/vc-specs#address", "@context": { "name": "schema:Text" } }, - "passingYear": { - "@id": "https://github.com/sunbird-specs/vc-specs#passingYear", + "state": { + "@id": "https://github.com/sunbird-specs/vc-specs#state", + "@context": { + "name": "schema:Text" + } + }, + "district": { + "@id": "https://github.com/sunbird-specs/vc-specs#district", + "@context": { + "name": "schema:Text" + } + }, + "country": { + "@id": "https://github.com/sunbird-specs/vc-specs#country", + "@context": { + "name": "schema:Text" + } + }, + "pincode": { + "@id": "https://github.com/sunbird-specs/vc-specs#pincode", + "@context": { + "name": "schema:Text" + } + }, + "candidatePic": { + "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", + "@context": { + "name": "schema:Text" + } + }, + "nursingCollage": { + "@id": "https://github.com/sunbird-specs/vc-specs#nursingCollage", + "@context": { + "name": "schema:Text" + } + }, + "courseName": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseName", "@context": { "name": "schema:Text" } @@ -325,20 +290,26 @@ "name": "schema:Text" } }, - "fathersName": { - "@id": "https://github.com/sunbird-specs/vc-specs#fathersName", + "passingMonth": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingMonth", "@context": { "name": "schema:Text" } }, - "courseName": { - "@id": "https://github.com/sunbird-specs/vc-specs#courseName", + "passingYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#passingYear", "@context": { "name": "schema:Text" } }, - "examBody": { - "@id": "https://github.com/sunbird-specs/vc-specs#examBody", + "examYear": { + "@id": "https://github.com/sunbird-specs/vc-specs#examYear", + "@context": { + "name": "schema:Text" + } + }, + "centerCode":{ + "@id": "https://github.com/sunbird-specs/vc-specs#centerCode", "@context": { "name": "schema:Text" } @@ -349,61 +320,72 @@ "name": "schema:Text" } }, - "date": { - "@id": "https://github.com/sunbird-specs/vc-specs#date", + "examBody": { + "@id": "https://github.com/sunbird-specs/vc-specs#examBody", "@context": { "name": "schema:Text" } }, - "courseState": { - "@id": "https://github.com/sunbird-specs/vc-specs#courseState", + "paymentStatus": { + "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", "@context": { "name": "schema:Text" } }, - "council": { - "@id": "https://github.com/sunbird-specs/vc-specs#council", + "feeReciptNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#feeReciptNo", "@context": { "name": "schema:Text" } }, - "registrationNo": { - "@id": "https://github.com/sunbird-specs/vc-specs#registrationNo", + "credType": { + "@id": "https://github.com/sunbird-specs/vc-specs#credType", "@context": { "name": "schema:Text" } }, - "nurseRegNo": { - "@id": "https://github.com/sunbird-specs/vc-specs#registrationNo", + "docproof": { + "@id": "https://github.com/sunbird-specs/vc-specs#docproof", "@context": { "name": "schema:Text" } }, - "nurseRegDate": { - "@id": "https://github.com/sunbird-specs/vc-specs#registrationNo", + "regNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#regNumber", "@context": { "name": "schema:Text" } }, - "candidatePic": { - "@id": "https://github.com/sunbird-specs/vc-specs#candidatePic", + "diplomaNumber": { + "@id": "https://github.com/sunbird-specs/vc-specs#diplomaNumber", "@context": { "name": "schema:Text" } }, - "doc-proof": { - "@id": "https://github.com/sunbird-specs/vc-specs#doc-proof", + "nurseRegNo": { + "@id": "https://github.com/sunbird-specs/vc-specs#nurseRegNo", "@context": { "name": "schema:Text" } }, - "paymentStatus": { - "@id": "https://github.com/sunbird-specs/vc-specs#paymentStatus", + "nurseRegDate": { + "@id": "https://github.com/sunbird-specs/vc-specs#nurseRegDate", + "@context": { + "name": "schema:Text" + } + }, + "courseState": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseState", + "@context": { + "name": "schema:Text" + } + }, + "courseCouncil": { + "@id": "https://github.com/sunbird-specs/vc-specs#courseCouncil", "@context": { "name": "schema:Text" } } - } ], "type": ["VerifiableCredential"], @@ -411,22 +393,40 @@ "credentialSubject": { "type": "Person", "name": "{{name}}", + "council": "{{council}}", + "email": "{{email}}", + "phoneNumber": "{{phoneNumber}}", "mothersName": "{{mothersName}}", "fathersName": "{{fathersName}}", + "dateOfBirth": "{{dateOfBirth}}", + "aadhaarNo": "{{aadhaarNo}}", + "gender": "{{gender}}", + "address": "{{address}}", + "state":"{{state}}", + "district": "{{district}}", + "country": "{{country}}", + "pincode": "{{pincode}}", + "candidatePic": "{{candidatePic}}", "courseName": "{{courseName}}", + "nursingCollage": "{{nursingCollage}}", "joiningMonth": "{{joiningMonth}}", - "joiningYear": "{{joiningYear}}", - "passingMonth": "{{passingMonth}}", + "joiningYear": "{{joiningYear}}", + "passingMonth": "{{passingMonth}}", "passingYear": "{{passingYear}}", - "examBody": "{{examBody}}", "finalYearRollNo": "{{finalYearRollNo}}", - "date": "{{date}}", - "courseState": "{{courseState}}", - "council": "{{council}}", - "registrationNo": "{{registrationNo}}", + "feeReciptNo": "{{feeReciptNo}}", + "examBody": "{{examBody}}", + "examYear": "{{examYear}}", + "centerCode": "{{centerCode}}", + "paymentStatus": "{{paymentStatus}}", + "credType":"{{credType}}", + "docproof": "{{docproof}}", + "regNumber": "{{regNumber}}", + "diplomaNumber": "{{diplomaNumber}}", "nurseRegNo": "{{nurseRegNo}}", "nurseRegDate": "{{nurseRegDate}}", - "candidatePic": "{{candidatePic}}" + "courseState": "{{courseState}}", + "courseCouncil": "{{courseCouncil}}" }, "issuer": "did:web:sunbirdrc.dev/vc/skill" } @@ -463,4 +463,4 @@ "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate" } } -} \ No newline at end of file +} From 209b370bcbb59cfda1f8629c7571c7291b6d5c3c Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 24 Aug 2023 07:01:34 +0530 Subject: [PATCH 33/43] certificate number --- .../CertificateNumberController.java | 23 +++++++++++++ .../claim/controller/EventController.java | 26 +++++++-------- .../dev/sunbirdrc/claim/entity/Event.java | 4 +++ .../claim/entity/GeneratedNumber.java | 28 ++++++++++++++++ .../claim/entity/TelemetryObject.java | 32 +++++++++++++++++++ .../repository/GeneratedNumberRepository.java | 7 ++++ .../repository/TelemetryObjectRepository.java | 7 ++++ .../service/CertificateNumberService.java | 29 +++++++++++++++++ .../sunbirdrc/claim/service/EventService.java | 28 ++++++++++------ 9 files changed, 159 insertions(+), 25 deletions(-) create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/controller/CertificateNumberController.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/GeneratedNumber.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/TelemetryObject.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/GeneratedNumberRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/TelemetryObjectRepository.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/CertificateNumberService.java diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CertificateNumberController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CertificateNumberController.java new file mode 100644 index 000000000..5a780afa5 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CertificateNumberController.java @@ -0,0 +1,23 @@ +package dev.sunbirdrc.claim.controller; + +import dev.sunbirdrc.claim.service.CertificateNumberService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CertificateNumberController { + + private CertificateNumberService certificateNumberService; + + @Autowired + public CertificateNumberController(CertificateNumberService certificateNumberService) { + this.certificateNumberService = certificateNumberService; + } + + @GetMapping("/api/v1/generate-certNumber") + public Long generateNumber() { + return certificateNumberService.generateAndSaveNumber(); + } +} + diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EventController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EventController.java index 3bc253816..565f7f9b3 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EventController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EventController.java @@ -12,30 +12,26 @@ @RestController @RequestMapping("/v1/api/events") -public class EventController { - private final EventService eventService; +public class EventController +{ + @Autowired + private EventService eventService; + @Autowired public EventController(EventService eventService) { this.eventService = eventService; } - @PostMapping("/") - public ResponseEntity saveEvent(@RequestBody Event event) { - Event savedEvent = eventService.saveEvent(event); - return new ResponseEntity<>(savedEvent, HttpStatus.CREATED); + @PostMapping + public ResponseEntity createEventWithTelemetry(@RequestBody Event event) { + Event savedEvent = eventService.saveEventWithTelemetry(event); + return ResponseEntity.ok(savedEvent); } - @GetMapping("/") + @GetMapping public ResponseEntity> getAllEvents() { List events = eventService.getAllEvents(); - return new ResponseEntity<>(events, HttpStatus.OK); - } - - @GetMapping("/{id}") - public ResponseEntity getEventById(@PathVariable Long id) { - Optional event = eventService.getEventById(id); - return event.map(value -> new ResponseEntity<>(value, HttpStatus.OK)) - .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); + return ResponseEntity.ok(events); } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Event.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Event.java index f412ca9f3..383601e05 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Event.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Event.java @@ -6,6 +6,7 @@ import lombok.NoArgsConstructor; import javax.persistence.*; +import java.util.List; @Entity @Data @@ -28,4 +29,7 @@ public class Event { @Column(name = "mid") private String mid; + + @OneToMany(mappedBy = "event", cascade = CascadeType.ALL, orphanRemoval = true) + private List telemetryObjects; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/GeneratedNumber.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/GeneratedNumber.java new file mode 100644 index 000000000..9beb2b6c2 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/GeneratedNumber.java @@ -0,0 +1,28 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class GeneratedNumber { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private Long number; + + +} + diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/TelemetryObject.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/TelemetryObject.java new file mode 100644 index 000000000..fc4ceebc6 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/TelemetryObject.java @@ -0,0 +1,32 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import net.minidev.json.annotate.JsonIgnore; + +import javax.persistence.*; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class TelemetryObject { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "telemetry_id") + private String telemetryId; + + @Column(name = "type") + private String type; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "event_id") + @JsonIgnore + private Event event; +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/GeneratedNumberRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/GeneratedNumberRepository.java new file mode 100644 index 000000000..c60f86298 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/GeneratedNumberRepository.java @@ -0,0 +1,7 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.GeneratedNumber; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GeneratedNumberRepository extends JpaRepository { +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/TelemetryObjectRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/TelemetryObjectRepository.java new file mode 100644 index 000000000..4cd9349ef --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/TelemetryObjectRepository.java @@ -0,0 +1,7 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.TelemetryObject; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface TelemetryObjectRepository extends JpaRepository { +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/CertificateNumberService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CertificateNumberService.java new file mode 100644 index 000000000..76ba99ace --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CertificateNumberService.java @@ -0,0 +1,29 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.entity.GeneratedNumber; +import dev.sunbirdrc.claim.repository.GeneratedNumberRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class CertificateNumberService { + + private final GeneratedNumberRepository numberRepository; + + @Autowired + public CertificateNumberService(GeneratedNumberRepository numberRepository) { + this.numberRepository = numberRepository; + } + + public Long generateAndSaveNumber() { + // Generate a random number (you can replace this with your logic) + Long generatedNumber = (long) Math.floor(Math.random() * 1000000); + + // Create an entity and save it in the database + GeneratedNumber entity = new GeneratedNumber(); + entity.setNumber(generatedNumber); + numberRepository.save(entity); + + return generatedNumber; + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EventService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EventService.java index 2e9a11416..78ff0afe4 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EventService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EventService.java @@ -1,32 +1,40 @@ package dev.sunbirdrc.claim.service; import dev.sunbirdrc.claim.entity.Event; +import dev.sunbirdrc.claim.entity.TelemetryObject; import dev.sunbirdrc.claim.repository.EventRepository; +import dev.sunbirdrc.claim.repository.TelemetryObjectRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; + @Service public class EventService { - private final EventRepository eventRepository; @Autowired - public EventService(EventRepository eventRepository) { - this.eventRepository = eventRepository; - } + private EventRepository eventRepository; - public Event saveEvent(Event event) { - return eventRepository.save(event); + @Autowired + private TelemetryObjectRepository telemetryObjectRepository; + + public Event saveEventWithTelemetry(Event event) { + List telemetryObjects = event.getTelemetryObjects(); + Event savedEvent = eventRepository.save(event); + if (telemetryObjects != null) { + for (TelemetryObject telemetryObject : telemetryObjects) { + telemetryObject.setEvent(savedEvent); + telemetryObjectRepository.save(telemetryObject); + } + } + + return savedEvent; } public List getAllEvents() { return eventRepository.findAll(); } - - public Optional getEventById(Long id) { - return eventRepository.findById(id); - } } From ac1bf0c6469c5f7188b1e8cb6dcd50ca21b9f62c Mon Sep 17 00:00:00 2001 From: rkrahu Date: Thu, 24 Aug 2023 17:03:41 +0530 Subject: [PATCH 34/43] Verify link with candidate details and approval. Manual mail send to foreign council. --- .../sunbirdrc/claim/ClaimsApplication.java | 2 + .../claim/config/PropertyMapper.java | 9 ++ .../claim/controller/EmailController.java | 15 +- .../controller/OutsideStudentController.java | 44 +++++ .../sunbirdrc/claim/dto/PendingMailDTO.java | 1 + .../dev/sunbirdrc/claim/entity/Claim.java | 11 ++ .../entity/StudentForeignVerification.java | 40 +++++ .../claim/repository/ClaimRepository.java | 2 + .../StudentForeignVerificationRowMapper.java | 41 +++++ .../claim/service/AsyncMailSender.java | 150 ++++++++++++++++++ .../sunbirdrc/claim/service/ClaimService.java | 27 ++++ .../sunbirdrc/claim/service/EmailService.java | 138 ++++++---------- .../StudentForeignVerificationService.java | 87 ++++++++++ .../src/main/resources/application.properties | 3 + .../resources/templates/candidate-details.ftl | 142 +++++++++++++++++ .../templates/manual-pending-item-mail.ftl | 44 ++++- .../resources/templates/pending-item-mail.ftl | 2 + .../controller/RegistryEntityController.java | 6 +- .../registry/util/ClaimRequestClient.java | 21 ++- 19 files changed, 675 insertions(+), 110 deletions(-) create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/controller/OutsideStudentController.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentForeignVerification.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/StudentForeignVerificationRowMapper.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/AsyncMailSender.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentForeignVerificationService.java create mode 100644 java/claim/src/main/resources/templates/candidate-details.ftl diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/ClaimsApplication.java b/java/claim/src/main/java/dev/sunbirdrc/claim/ClaimsApplication.java index 3591f43a0..c17770630 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/ClaimsApplication.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/ClaimsApplication.java @@ -4,6 +4,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableAsync; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; @@ -11,6 +12,7 @@ @SpringBootApplication @ComponentScan(basePackages = { "dev.sunbirdrc.registry.middleware", "dev.sunbirdrc.claim"}) +@EnableAsync public class ClaimsApplication { public static void main(String[] args) { SpringApplication.run(ClaimsApplication.class, args); diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java index d56b98715..ecf50be7b 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java @@ -18,4 +18,13 @@ public class PropertyMapper { @Value("${regulator.table.name}") private String regulatorTableName; + + @Value("${student.foreign.verification.table.name}") + private String studentForeignVerificationTableName; + + @Value("${claim.url}") + private String claimUrl; + + @Value("${registry.shard.id}") + private String registryShardId; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java index d41cf3e54..dbd9a726e 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java @@ -15,10 +15,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.*; import javax.imageio.ImageIO; import javax.xml.bind.DatatypeConverter; @@ -119,10 +116,12 @@ public ResponseEntity sendCertificateMail(@RequestBody CertificateMailDt return new ResponseEntity<>("Mail is sending", HttpStatus.OK); } - @RequestMapping(value = "/api/v1/sendPendingForeignItemMail", method = RequestMethod.POST) + @RequestMapping(value = "/api/v1/sendPendingForeignItemMail/{claimId}", method = RequestMethod.GET) public ResponseEntity sendPendingItemMail(@RequestHeader HttpHeaders headers, - @RequestBody PendingMailDTO pendingMailDTO) { - emailService.sendManualPendingMail(pendingMailDTO); - return new ResponseEntity<>("Mail is sending", HttpStatus.OK); + @PathVariable String claimId) { + + emailService.collectAndSendForeignCoucilMailManually(claimId); + + return new ResponseEntity<>("Sending manual foreign pending item mail", HttpStatus.OK); } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/OutsideStudentController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/OutsideStudentController.java new file mode 100644 index 000000000..139bc4e00 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/OutsideStudentController.java @@ -0,0 +1,44 @@ +package dev.sunbirdrc.claim.controller; + +import dev.sunbirdrc.claim.service.ClaimService; +import dev.sunbirdrc.claim.service.StudentForeignVerificationService; +import dev.sunbirdrc.claim.status.Status; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/outside") +public class OutsideStudentController { + + @Autowired + private StudentForeignVerificationService foreignVerificationService; + + @Autowired + private ClaimService claimService; + + @GetMapping("/foreignStudent/{id}") + public ResponseEntity getForeignStudentVerificationDetail(@PathVariable String id) { + String template = foreignVerificationService.generatePendingMailContent(id); + + if (!StringUtils.isEmpty(template)) { + return new ResponseEntity<>(template, HttpStatus.OK); + } else { + return ResponseEntity.notFound().build(); + } + } + + @GetMapping("/foreignStudent/verify/{id}/{status}") + public ResponseEntity verifyForeignStudentVerification(@PathVariable String id, + @PathVariable Status status) { + + claimService.updateForeignStudentStatus(id, status); + + return new ResponseEntity<>("Foreign student verification updated", HttpStatus.OK); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java index b54401151..a39dd30d0 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java @@ -19,4 +19,5 @@ public class PendingMailDTO { private String regulatorEmail; private String credType; private String registrationNumber; + private String verifyLink; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java index 6e2efc748..9c006eb88 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java @@ -63,6 +63,17 @@ public void setCredType(String credType) { @Column private String attestorUserId; + @Column + private String foreignStudentStatus; + + public String getForeignStudentStatus() { + return foreignStudentStatus; + } + + public void setForeignStudentStatus(String foreignStudentStatus) { + this.foreignStudentStatus = foreignStudentStatus; + } + @PrePersist protected void onCreate() { createdAt = new Date(); diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentForeignVerification.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentForeignVerification.java new file mode 100644 index 000000000..4b2c02118 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentForeignVerification.java @@ -0,0 +1,40 @@ +package dev.sunbirdrc.claim.entity; + + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class StudentForeignVerification { + private String title; + private String name; + private String registrationType; + private String registrationNumber; + private String refNo; + private String phoneNumber; + private String passingYear; + private String passingMonth; + private String osOwner; + private String osid; + private String nursingCollage; + private String mothersName; + private String joiningYear; + private String joiningMonth; + private String gender; + private String finalYearRollNo; + private String fathersName; + private String examBody; + private String email; + private String dateOfBirth; + private String date; + private String courseName; + private String council; + private String candidatePic; + private String barCode; + private String aadhaarNo; + + +} \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimRepository.java index e2d992705..885b95ff6 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimRepository.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/ClaimRepository.java @@ -13,4 +13,6 @@ public interface ClaimRepository extends JpaRepository { List findByAttestorEntity(String entity); List findByRequestorName(String requestorName); + + List findByEntityId(String entityId); } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/StudentForeignVerificationRowMapper.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/StudentForeignVerificationRowMapper.java new file mode 100644 index 000000000..dd8c0cc6f --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/StudentForeignVerificationRowMapper.java @@ -0,0 +1,41 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.StudentForeignVerification; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class StudentForeignVerificationRowMapper implements RowMapper { + @Override + public StudentForeignVerification mapRow(ResultSet rs, int rowNum) throws SQLException { + return new StudentForeignVerification( + rs.getString("title"), + rs.getString("name"), + rs.getString("registrationType"), + rs.getString("registrationNumber"), + rs.getString("refNo"), + rs.getString("phoneNumber"), + rs.getString("passingYear"), + rs.getString("passingMonth"), + rs.getString("osOwner"), + rs.getString("osid"), + rs.getString("nursingCollage"), + rs.getString("mothersName"), + rs.getString("joiningYear"), + rs.getString("joiningMonth"), + rs.getString("gender"), + rs.getString("finalYearRollNo"), + rs.getString("fathersName"), + rs.getString("examBody"), + rs.getString("email"), + rs.getString("dateOfBirth"), + rs.getString("date"), + rs.getString("courseName"), + rs.getString("council"), + rs.getString("candidatePic"), + rs.getString("barCode"), + rs.getString("aadhaarNo") + ); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/AsyncMailSender.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/AsyncMailSender.java new file mode 100644 index 000000000..ebb369957 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/AsyncMailSender.java @@ -0,0 +1,150 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.config.PropertyMapper; +import dev.sunbirdrc.claim.controller.EmailController; +import dev.sunbirdrc.claim.dto.PendingMailDTO; +import dev.sunbirdrc.claim.entity.Regulator; +import dev.sunbirdrc.claim.exception.ClaimMailException; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.lang.NonNull; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; + +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Service +public class AsyncMailSender { + private static final Logger logger = LoggerFactory.getLogger(AsyncMailSender.class); + @Autowired + private JavaMailSender mailSender; + + @Autowired + private PropertyMapper propertyMapper; + + @Autowired + private Configuration freeMarkerConfiguration; + + /** + * @param pendingMailDTOList + * @param regulatorList + */ + @Async + public void sendPendingMailToRegulatorList(@NonNull List pendingMailDTOList, + List regulatorList) { + + for (Regulator regulator : regulatorList) { + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + + MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + + mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); + mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(), + "Auto generated mail for pending item")); + mimeMessageHelper.setTo(regulator.getEmail()); + mimeMessageHelper.setText(generatePendingMailContent(pendingMailDTOList, regulator.getName()), true); + + mailSender.send(mimeMessageHelper.getMimeMessage()); + } catch (Exception e) { + logger.error("Exception while sending mail: ", e); + throw new ClaimMailException("Exception while composing and sending mail with OTP"); + } + } + } + + /** + * @param pendingMailDTOList + * @param regulatorName + * @return + */ + private String generatePendingMailContent(@NonNull List pendingMailDTOList, + @NonNull String regulatorName) { + String processedTemplateString = null; + + Map mailMap = new HashMap<>(); + mailMap.put("candidates", pendingMailDTOList); + mailMap.put("regulatorName", regulatorName); + + try { + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("pending-item-mail.ftl"); + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + + } catch (TemplateException e) { + logger.error("TemplateException while creating auto mail template for foreing pending item ", e); + throw new ClaimMailException("Error while creating auto mail template for foreing pending item"); + } catch (IOException e) { + logger.error("IOException while creating auto mail template for foreing pending item ", e); + throw new ClaimMailException("Error while creating auto mail template for foreing pending item"); + } + return processedTemplateString; + } + + /** + * @param pendingMailDTO + * @param regulatorName + * @param regulatorEmail + */ + @Async + public void sendManualPendingMail(PendingMailDTO pendingMailDTO, @NonNull String regulatorName, + @NonNull String regulatorEmail) { + + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + + MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + + mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); + mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(), + "Pending action item")); + mimeMessageHelper.setTo(regulatorEmail); + mimeMessageHelper.setText(generateManualForeignPendingMailContent(pendingMailDTO, regulatorName), true); + + mailSender.send(mimeMessageHelper.getMimeMessage()); + } catch (Exception e) { + logger.error("Exception while sending mail: ", e); + throw new ClaimMailException("Exception while composing and sending mail with OTP"); + } + + } + + /** + * @param pendingMailDTO + * @param foreignRegulatorName + * @return + */ + private String generateManualForeignPendingMailContent(PendingMailDTO pendingMailDTO, String foreignRegulatorName) { + String processedTemplateString = null; + + Map mailMap = new HashMap<>(); + mailMap.put("candidate", pendingMailDTO); + mailMap.put("regulatorName", foreignRegulatorName); + + try { + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("manual-pending-item-mail.ftl"); + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + + } catch (TemplateException e) { + logger.error("TemplateException while creating manual mail template for foreing pending item ", e); + throw new ClaimMailException("Error while creating manual mail template for foreing pending item"); + } catch (IOException e) { + logger.error("IOException while creating manual mail template for foreing pending item ", e); + throw new ClaimMailException("Error while creating manual mail template for foreing pending item"); + } + return processedTemplateString; + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java index 515abda95..6394413bd 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java @@ -5,13 +5,17 @@ import dev.sunbirdrc.claim.entity.Claim; import dev.sunbirdrc.claim.entity.ClaimNote; import dev.sunbirdrc.claim.exception.ClaimAlreadyProcessedException; +import dev.sunbirdrc.claim.exception.InvalidInputException; import dev.sunbirdrc.claim.exception.ResourceNotFoundException; import dev.sunbirdrc.claim.exception.UnAuthorizedException; import dev.sunbirdrc.claim.model.ClaimStatus; import dev.sunbirdrc.claim.repository.ClaimNoteRepository; import dev.sunbirdrc.claim.repository.ClaimRepository; +import dev.sunbirdrc.claim.status.Status; import dev.sunbirdrc.pojos.attestation.Action; import dev.sunbirdrc.registry.middleware.util.EntityUtil; +import freemarker.template.Configuration; +import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -139,4 +143,27 @@ public ClaimWithNotesDTO generateNotesForTheClaim(Claim claim) { claimWithNotesDTO.setClaim(claim); return claimWithNotesDTO; } + + /** + * @param entityId + * @param status + */ + public void updateForeignStudentStatus(String entityId, Status status) { + if (!StringUtils.isEmpty(entityId) && status != null) { + List claimList = claimRepository.findByEntityId(entityId); + + if (claimList != null && !claimList.isEmpty()) { + Claim claim = claimList.get(0); + + if (Status.Approved.name().equalsIgnoreCase(claim.getForeignStudentStatus())) { + throw new ClaimAlreadyProcessedException("Claim is already approved"); + } else { + claim.setForeignStudentStatus(status.name()); + claimRepository.save(claim); + } + } + } else { + throw new InvalidInputException("Entity id or status is not valid"); + } + } } \ No newline at end of file diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java index 6ded2a89c..baefdefed 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java @@ -19,6 +19,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.FileSystemResource; import org.springframework.lang.NonNull; @@ -28,6 +29,7 @@ import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; @@ -63,6 +65,9 @@ public class EmailService @Autowired private RegulatorService regulatorService; + + @Autowired + private AsyncMailSender asyncMailSender; /** * This method will send compose and send the message @@ -189,56 +194,6 @@ private String generateAttachedCertificateMailContent(CertificateMailDto certifi return processedTemplateString; } - @Async - public void sendPendingMail(@NonNull List pendingMailDTOList, @NonNull String regulatorName, - @NonNull String regulatorEmail) { - - try { - MimeMessage mimeMessage = mailSender.createMimeMessage(); - - MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); - - mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); - mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(), - "Pending Action Item")); - mimeMessageHelper.setTo(regulatorEmail); - mimeMessageHelper.setText(generatePendingMailContent(pendingMailDTOList, regulatorName), true); - - mailSender.send(mimeMessageHelper.getMimeMessage()); - } catch (Exception e) { - logger.error("Exception while sending mail: ", e); - throw new ClaimMailException("Exception while composing and sending mail with OTP"); - } - - } - - /** - * @param mailDto - * @return - */ - private String generatePendingMailContent(@NonNull List pendingMailDTOList, - @NonNull String regulatorName) { - String processedTemplateString = null; - - Map mailMap = new HashMap<>(); - mailMap.put("candidates", pendingMailDTOList); - mailMap.put("regulatorName", regulatorName); - - try { - freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); - Template template = freeMarkerConfiguration.getTemplate("pending-item-mail.ftl"); - processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); - - } catch (TemplateException e) { - logger.error("TemplateException while creating mail template for certificate ", e); - throw new ClaimMailException("Error while creating mail template for certificate"); - } catch (IOException e) { - logger.error("IOException while creating mail template for certificate ", e); - throw new ClaimMailException("Error while creating mail template for certificate"); - } - return processedTemplateString; - } - public void sendForeignPendingItemMail() { if (!regulatorService.isRegulatorTableExist()) { logger.error(">>>>>>>>>>> Unable to find regulator table in database: No further process will be occurred"); @@ -260,9 +215,7 @@ public void sendForeignPendingItemMail() { List regulatorList = regulatorService.findByCouncil(foreignCouncilName); - for (Regulator regulator : regulatorList) { - sendPendingMail(pendingMailDTOList, regulator.getName(), regulator.getEmail()); - } + asyncMailSender.sendPendingMailToRegulatorList(pendingMailDTOList, regulatorList); } } } @@ -297,6 +250,7 @@ public void sendForeignPendingItemMail() { String propertyData = claim.getPropertyData(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(propertyData); + String entityId = claim.getEntityId().replace(propertyMapper.getRegistryShardId() + "-", ""); PendingMailDTO pendingMailDTO = PendingMailDTO.builder() .credType(jsonNode.get("credType") != null ? jsonNode.get("credType").asText() : "") @@ -304,6 +258,7 @@ public void sendForeignPendingItemMail() { .refNo(jsonNode.get("refNo") != null ? jsonNode.get("refNo").asText() : "") .name(jsonNode.get("name") != null ? jsonNode.get("name").asText() : "") .registrationNumber(jsonNode.get("registrationNumber") != null ? jsonNode.get("registrationNumber").asText() : "") + .verifyLink(propertyMapper.getClaimUrl() + "/api/v1/outside/foreignStudent/" + entityId) .build(); pendingMailDTOList.add(pendingMailDTO); @@ -311,8 +266,6 @@ public void sendForeignPendingItemMail() { } catch (Exception e) { logger.error(">>>>>>>>>>> Unable to read council name from claim property data", e); } - - return pendingMailDTOList; } @@ -333,52 +286,61 @@ public void sendForeignPendingItemMail() { return council; } - @Async - public void sendManualPendingMail(PendingMailDTO pendingMailDTO) { + /** + * @param claimId + */ + public void collectAndSendForeignCoucilMailManually(String claimId) { + if (!StringUtils.isEmpty(claimId)) { + Optional claimOptional = claimService.findById(claimId); - try { - MimeMessage mimeMessage = mailSender.createMimeMessage(); + if (claimOptional.isPresent()) { + Claim claim = claimOptional.get(); - MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + String foreignCouncilName = getCouncilName(claim.getPropertyData()); - mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); - mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(),pendingMailDTO.getName())); - mimeMessageHelper.setTo(pendingMailDTO.getEmailAddress()); - mimeMessageHelper.setText(generateManualPendingMailContent(pendingMailDTO), true); + Optional pendingMailDtoOptional = collectEntityDetailsForManualMail(claim); - mailSender.send(mimeMessageHelper.getMimeMessage()); - } catch (Exception e) { - logger.error("Exception while sending mail: ", e); - throw new ClaimMailException("Exception while composing and sending mail with OTP"); - } + if (pendingMailDtoOptional.isPresent()) { + List regulatorList = regulatorService.findByCouncil(foreignCouncilName); + for (Regulator regulator : regulatorList) { + logger.info(">>>>>>>>>>>>>>> before sending pending mail"); + asyncMailSender.sendManualPendingMail(pendingMailDtoOptional.get(), regulator.getName(), regulator.getEmail()); + logger.info(">>>>>>>>>>>>>>>>>>> mail has been processed"); + } + } else { + logger.error(">>>>> Unable to collect entitiy details - while sending pending item mail to foreign council"); + } + } + } } /** - * @param mailDto + * @param claim * @return */ - private String generateManualPendingMailContent(PendingMailDTO pendingMailDTO) { - String processedTemplateString = null; + private Optional collectEntityDetailsForManualMail(@NonNull Claim claim) { + try { + String propertyData = claim.getPropertyData(); + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(propertyData); + String entityId = claim.getEntityId().replace(propertyMapper.getRegistryShardId() + "-", ""); - Map mailMap = new HashMap<>(); - mailMap.put("name", pendingMailDTO.getName()); - mailMap.put("council", pendingMailDTO.getCouncil()); - mailMap.put("itemName", pendingMailDTO.getItemName()); + PendingMailDTO pendingMailDTO = PendingMailDTO.builder() + .credType(jsonNode.get("credType") != null ? jsonNode.get("credType").asText() : "") + .emailAddress(jsonNode.get("email") != null ? jsonNode.get("email").asText() : "") + .refNo(jsonNode.get("refNo") != null ? jsonNode.get("refNo").asText() : "") + .name(jsonNode.get("name") != null ? jsonNode.get("name").asText() : "") + .registrationNumber(jsonNode.get("registrationNumber") != null ? jsonNode.get("registrationNumber").asText() : "") + .verifyLink(propertyMapper.getClaimUrl() + "/api/v1/outside/foreignStudent/" + entityId) + .build(); - try { - freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); - Template template = freeMarkerConfiguration.getTemplate("manual-pending-item-mail.ftl"); - processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + return Optional.ofNullable(pendingMailDTO); - } catch (TemplateException e) { - logger.error("TemplateException while creating mail template for certificate ", e); - throw new ClaimMailException("Error while creating mail template for certificate"); - } catch (IOException e) { - logger.error("IOException while creating mail template for certificate ", e); - throw new ClaimMailException("Error while creating mail template for certificate"); + } catch (Exception e) { + logger.error(">>>>>>>>>>> Unable to read council name from claim property data", e); } - return processedTemplateString; - } + return Optional.empty(); + } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentForeignVerificationService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentForeignVerificationService.java new file mode 100644 index 000000000..978ae3bc4 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentForeignVerificationService.java @@ -0,0 +1,87 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.config.PropertyMapper; +import dev.sunbirdrc.claim.entity.StudentForeignVerification; +import dev.sunbirdrc.claim.exception.ClaimMailException; +import dev.sunbirdrc.claim.repository.StudentForeignVerificationRowMapper; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Service +public class StudentForeignVerificationService { + private static final Logger logger = LoggerFactory.getLogger(StudentForeignVerificationService.class); + @Autowired + private PropertyMapper propertyMapper; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Autowired + private Configuration freeMarkerConfiguration; + + public List findByOsid(String osid) { + try { + return jdbcTemplate.query("SELECT * FROM \"" + propertyMapper.getStudentForeignVerificationTableName() + + "\" where osid=?", new StudentForeignVerificationRowMapper(), osid); + + } catch (IncorrectResultSizeDataAccessException e) { + return null; + } + } + + public List findAll() { + return jdbcTemplate.query("SELECT * from \"" + propertyMapper.getStudentForeignVerificationTableName() + "\"", + new StudentForeignVerificationRowMapper()); + } + + public boolean isStudentForeignVerificationTableExist() { + String sqlQuery = "SELECT count(*) FROM information_schema.tables WHERE table_name = '" + + propertyMapper.getStudentForeignVerificationTableName() + "'"; + + Integer tableCount = jdbcTemplate.queryForObject(sqlQuery, Integer.class); + + return tableCount > 0; + } + + public String generatePendingMailContent(String id) { + String processedTemplateString = null; + List studentForeignVerificationList = findByOsid(id); + + if (studentForeignVerificationList != null && !studentForeignVerificationList.isEmpty()) { + StudentForeignVerification studentForeignVerification = studentForeignVerificationList.get(0); + + Map mailMap = new HashMap<>(); + mailMap.put("candidate", studentForeignVerification); + mailMap.put("entityId", propertyMapper.getRegistryShardId() + "-" + studentForeignVerification.getOsid()); + + try { + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("candidate-details.ftl"); + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + + } catch (TemplateException e) { + logger.error("TemplateException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } catch (IOException e) { + logger.error("IOException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } + } + + return processedTemplateString; + } + +} diff --git a/java/claim/src/main/resources/application.properties b/java/claim/src/main/resources/application.properties index caaba96c9..37494c97b 100644 --- a/java/claim/src/main/resources/application.properties +++ b/java/claim/src/main/resources/application.properties @@ -50,6 +50,9 @@ foreign.pending.item.subject = Pending Item #Pending Item config up.council.name = upsmfac regulator.table.name = V_Regulator +student.foreign.verification.table.name = V_StudentForeignVerification +claim.url = http://localhost:8082 +registry.shard.id = 1 #---------------------------- QUARTZ CONFIGS ---------------------------- samplejob.frequency=0 40 15 ? * * * diff --git a/java/claim/src/main/resources/templates/candidate-details.ftl b/java/claim/src/main/resources/templates/candidate-details.ftl new file mode 100644 index 000000000..b933c6262 --- /dev/null +++ b/java/claim/src/main/resources/templates/candidate-details.ftl @@ -0,0 +1,142 @@ + + + + + + +
NameCourseCred Type Reference Number Registration Number Email
${candidate.name} ${candidate.course}${candidate.credType} ${candidate.refNo} ${candidate.registrationNumber} ${candidate.emailAddress}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Candidate Details

Title${candidate.title}
Student Name${candidate.name}
Registration Type${candidate.registrationType}
Registration Number${candidate.registrationNumber}
Reference No${candidate.refNo}
Phone Number${candidate.phoneNumber}
Passing Year${candidate.passingYear}
Passing Month${candidate.passingMonth}
Nursing Collage${candidate.nursingCollage}
Mothers Name${candidate.mothersName}
Joining Year${candidate.joiningYear}
Joining Month${candidate.joiningMonth}
Gender${candidate.gender}
Final Year Roll No${candidate.finalYearRollNo}
Fathers Name${candidate.fathersName}
Exam Body${candidate.examBody}
Email${candidate.email}
Date Of Birth${candidate.dateOfBirth}
Date${candidate.date}
Course Name${candidate.courseName}
Council${candidate.council}
CandidatePic${candidate.candidatePic}
Bar Code${candidate.barCode}
Aadhaar No${candidate.aadhaarNo}
+
+ + + + + +
+ + + +
+
+ + diff --git a/java/claim/src/main/resources/templates/manual-pending-item-mail.ftl b/java/claim/src/main/resources/templates/manual-pending-item-mail.ftl index 9b7a765d5..1c7f50ae6 100644 --- a/java/claim/src/main/resources/templates/manual-pending-item-mail.ftl +++ b/java/claim/src/main/resources/templates/manual-pending-item-mail.ftl @@ -1,12 +1,46 @@ + + + -

Hi ${name}

+

Hi ${regulatorName}

+ +

Following candidate has applied for registration certificate from your institution as claimed by candidate.

-

We have pending item for ${council}, which have been requested

+

Candidate list:

+

+ + + + + + + + + + + + + + + + + +
NameCred TypeReference NumberRegistration NumberEmailVerify Link
${candidate.name} ${candidate.credType}${candidate.refNo}${candidate.registrationNumber}${candidate.emailAddress}Verify Candidate
+

-
Item name:

${itemName}

+
your response awaited
-

Thank you,

-

< Registration Credential Issuing Authority >

+

Thank you,

+

< Registration Credential Issuing Authority >

\ No newline at end of file diff --git a/java/claim/src/main/resources/templates/pending-item-mail.ftl b/java/claim/src/main/resources/templates/pending-item-mail.ftl index 5f786b2d1..4c6ffc996 100644 --- a/java/claim/src/main/resources/templates/pending-item-mail.ftl +++ b/java/claim/src/main/resources/templates/pending-item-mail.ftl @@ -26,6 +26,7 @@ Reference Number Registration Number Email + Verify Link <#list candidates as candidate > @@ -34,6 +35,7 @@ ${candidate.refNo} ${candidate.registrationNumber} ${candidate.emailAddress} + Verify Candidate diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index c225777ed..8102f04a1 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -1438,9 +1438,9 @@ public JsonNode searchEntity(ObjectNode searchNode, String entityName) { return result; } - @RequestMapping(value = "/api/v1/{entityName}/sendPendingForeignItemMail", method = RequestMethod.POST) + @RequestMapping(value = "/api/v1/{entityName}/sendPendingForeignItemMail/{claimId}", method = RequestMethod.GET) public ResponseEntity sendPendingForeignItemMail(@PathVariable String entityName, - @RequestBody ManualPendingMailDTO pendingMailDTO, + @PathVariable String claimId, HttpServletRequest request) { ResponseParams responseParams = new ResponseParams(); @@ -1449,7 +1449,7 @@ public ResponseEntity sendPendingForeignItemMail(@PathVariable String en try { registryHelper.authorizeInviteEntity(request, entityName); - String mailStatus = claimRequestClient.sendPendingForeignItemMail(pendingMailDTO); + String mailStatus = claimRequestClient.sendPendingForeignItemMail(claimId); response.setResult(mailStatus); responseParams.setStatus(Response.Status.SUCCESSFUL); diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index 8baa0a608..6de9a0f0b 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -19,6 +19,7 @@ import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.util.UriComponentsBuilder; @@ -46,7 +47,7 @@ public class ClaimRequestClient { private static final String CLAIM_MULTI_FILE_UPLOAD = "/api/v1/files/upload/multiple"; private static String URL_APPENDER = "/"; - private static final String MAIL_SEND_PENDING_FOREIGN_ITEM_URL = "/api/v1/sendPendingForeignItemMail"; + private static final String MAIL_SEND_PENDING_FOREIGN_ITEM_URL = "/api/v1/sendPendingForeignItemMail/"; ClaimRequestClient(@Value("${claims.url}") String claimRequestUrl, RestTemplate restTemplate) { this.claimRequestUrl = claimRequestUrl; @@ -242,11 +243,19 @@ public List uploadCLaimMultipleFiles(@NonNull MultipartFile[] files, St return fileDtoList; } - public String sendPendingForeignItemMail(ManualPendingMailDTO pendingMailDTO) { - String mailStatus = restTemplate.postForObject( - claimRequestUrl + MAIL_SEND_PENDING_FOREIGN_ITEM_URL, pendingMailDTO, String.class); + public String sendPendingForeignItemMail(String claimId) { + if (!StringUtils.isEmpty(claimId)) { - logger.info("Pending foreign item mail status: " + mailStatus); - return mailStatus; + ResponseEntity mailStatusResponse = restTemplate.getForEntity( + claimRequestUrl + MAIL_SEND_PENDING_FOREIGN_ITEM_URL + claimId, String.class); + + logger.info(">>>>>>>> Pending foreign item mail status: " + mailStatusResponse.getBody()); + + return mailStatusResponse.getBody(); + } else { + logger.error(">>>>>>> Invalid claim id - while calling claim service for foreign pending item (manually)"); + } + + return "Failed to send mail to foreign pending item - invalid claim id"; } } From 304b97d8aaee5aa28c30b5617bbada73492ed541 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 24 Aug 2023 17:35:03 +0530 Subject: [PATCH 35/43] api request --- .../claim/controller/CoursesController.java | 8 ++-- .../sunbirdrc/claim/entity/Credentials.java | 2 +- .../src/main/resources/application.properties | 4 +- .../controller/RegistryEntityController.java | 43 +++++++++++++++++++ .../service/impl/CertificateServiceImpl.java | 2 +- .../registry/util/ClaimRequestClient.java | 37 +++++++++++++++- .../registry/util/HmacValidator.java | 37 ++++++++++++++++ .../src/main/resources/application.yml | 1 + 8 files changed, 125 insertions(+), 9 deletions(-) create mode 100644 java/registry/src/main/java/dev/sunbirdrc/registry/util/HmacValidator.java diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java index e33eed2b8..377fb1d25 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java @@ -37,8 +37,8 @@ public ResponseEntity getCourseById(@PathVariable Long id) { } } - @GetMapping("/category/{category}") - public ResponseEntity getCourseByName(@PathVariable String category) { + @GetMapping("/category") + public ResponseEntity getCourseByName(@RequestParam(value = "category", required = false) String category) { Optional course = coursesService.getCourseByCourse(category); if (course.isPresent()) { @@ -48,8 +48,8 @@ public ResponseEntity getCourseByName(@PathVariable String category) { } } - @GetMapping("/diploma/{category}") - public ResponseEntity> getCourseByCategory(@PathVariable String category) { + @GetMapping("/diploma") + public ResponseEntity> getCourseByCategory(@RequestParam(value = "category", required = false) String category) { List course = coursesService.getCourseByCategory(category); return ResponseEntity.ok(course); } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Credentials.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Credentials.java index 3405dbd57..29d8ee531 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Credentials.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Credentials.java @@ -18,7 +18,7 @@ @Builder public class Credentials { @Value("${gcs.api.url}") - public static String HTTP_LOCALHOST_8080_API_V_1_FILES_DOWNLOAD_FILE_NAME = "http://localhost:8082/api/v1/files/download?fileName="; + public static String HTTP_LOCALHOST_8080_API_V_1_FILES_DOWNLOAD_FILE_NAME = "http://registration.uphrh.in:8082/api/v1/files/download?fileName="; @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; diff --git a/java/claim/src/main/resources/application.properties b/java/claim/src/main/resources/application.properties index caaba96c9..04356561a 100644 --- a/java/claim/src/main/resources/application.properties +++ b/java/claim/src/main/resources/application.properties @@ -1,6 +1,6 @@ server.port=8082 -spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry} +spring.datasource.url=${connectionInfo_uri:jdbc:postgresql://localhost:5432/registry10} spring.datasource.username=${connectionInfo_username:postgres} spring.datasource.password=${connectionInfo_password:postgres} @@ -39,7 +39,7 @@ gcp.bucket.name=dev-public-upsmf gcp.bucket.id=dev-public-upsmf gcp.dir.name=issuance gcp.file.validity=2 - +gcs.api.url=http://registration.uphrh.in:8082/api/v1/files/download?fileName spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index c225777ed..381ad8a4d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -1464,4 +1464,47 @@ public ResponseEntity sendPendingForeignItemMail(@PathVariable String en return new ResponseEntity<>(response, HttpStatus.OK); } + + @RequestMapping(value = "/api/v1/category/{entityName}/{category}", method = RequestMethod.GET) + public ResponseEntity getCourseName(@PathVariable String entityName, @PathVariable String category,HttpServletRequest request) { + + ResponseParams responseParams = new ResponseParams(); + Response response = new Response(Response.API_ID.SEND, "OK", responseParams); + + try { + List list = claimRequestClient.getCourseCategory(category); + //Long certNumber = claimRequestClient.getCertificateNumber(); + response.setResult(list); + responseParams.setStatus(Response.Status.SUCCESSFUL); + + } catch (Exception exception) { + logger.error("Exception : {}", exception.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(exception.getMessage()); + return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); + } + + return new ResponseEntity<>(response, HttpStatus.OK); + } + + @RequestMapping(value = "/api/v1/course/{entityName}/certificate-number", method = RequestMethod.GET) + public ResponseEntity getCourseCertificateNumber(@PathVariable String entityName,HttpServletRequest request) { + + ResponseParams responseParams = new ResponseParams(); + Response response = new Response(Response.API_ID.SEND, "OK", responseParams); + + try { + Long certNumber = claimRequestClient.getCertificateNumber(); + response.setResult(certNumber); + responseParams.setStatus(Response.Status.SUCCESSFUL); + } catch (Exception exception) { + logger.error("Exception : {}", exception.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(exception.getMessage()); + return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); + } + + return new ResponseEntity<>(response, HttpStatus.OK); + } + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java index b78070670..1fb56e86d 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/impl/CertificateServiceImpl.java @@ -36,7 +36,7 @@ public class CertificateServiceImpl implements ICertificateService { private final String certificateHealthCheckURL; private final RestTemplate restTemplate; - @Value("${claims.url}") + @Value("${claims.domain-url}") private String claimRequestUrl; @Value("${claims.download-path}") diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index 8baa0a608..8db892ad3 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -30,7 +30,8 @@ @Component public class ClaimRequestClient { - private static Logger logger = LoggerFactory.getLogger(RegistryController.class); + private static final String GET_CERTIFICATE_NUMBER = "/api/v1/generate-certNumber"; + private static Logger logger = LoggerFactory.getLogger(ClaimRequestClient.class); private final String claimRequestUrl; private final RestTemplate restTemplate; private static final String CLAIMS_PATH = "/api/v1/claims"; @@ -41,6 +42,8 @@ public class ClaimRequestClient { private static final String BAR_CODE_API = "/api/v1/barcode"; private static final String SAVE_CRED_API = "/api/v1/credentials/save"; private static final String GET_CRED_URL = "/api/v1/files/download?"; + + private static final String GET_COURSE_CATEGORY = "/api/v1/courses/diploma"; private static final String PDF = ".PDF"; private static final String GCS_CODE_API = "/api/v1/files/upload"; private static final String CLAIM_MULTI_FILE_UPLOAD = "/api/v1/files/upload/multiple"; @@ -249,4 +252,36 @@ public String sendPendingForeignItemMail(ManualPendingMailDTO pendingMailDTO) { logger.info("Pending foreign item mail status: " + mailStatus); return mailStatus; } + + public List getCourseCategory(String category) { + String requestUrl = claimRequestUrl + GET_COURSE_CATEGORY; + MultiValueMap queryParams = new LinkedMultiValueMap<>(); + queryParams.add("category", category); + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestUrl) + .queryParam("category", category); + // Set request headers if needed + HttpHeaders headers = new HttpHeaders(); + // Add any required headers here + headers.set("accept", "*/*"); + ResponseEntity response = restTemplate.exchange( + builder.toUriString(), HttpMethod.GET, null, List.class, queryParams, headers + ); logger.info("end getCredentials ..."); + return response.getBody(); + } + + ///api/v1/generate-certNumber + + public Long getCertificateNumber() { + String requestUrl = claimRequestUrl + GET_CERTIFICATE_NUMBER; + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestUrl); + // Set request headers if needed + HttpHeaders headers = new HttpHeaders(); + // Add any required headers here + headers.set("accept", "*/*"); + ResponseEntity response = restTemplate.exchange( + builder.toUriString(), HttpMethod.GET, null, Long.class, headers + ); logger.info("end getCredentials ..."); + return response.getBody(); + } + } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/HmacValidator.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/HmacValidator.java new file mode 100644 index 000000000..c8ce1cc00 --- /dev/null +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/HmacValidator.java @@ -0,0 +1,37 @@ +package dev.sunbirdrc.registry.util; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +public class HmacValidator { + + public static boolean validateHmac(String xml, String hmacFromRequest, String secret) throws Exception { + String hmac = generateHMACSHA256(xml, secret); + String base64Hmac = base64Encode(hmac); + return (validateHMAC(hmacFromRequest,base64Hmac)); + } + + private static String generateHMACSHA256(String data, String secretKey) throws Exception { + Mac mac = Mac.getInstance("HmacSHA256"); + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); + mac.init(secretKeySpec); + byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); + StringBuilder hexHmac = new StringBuilder(); + for (byte b : rawHmac) { + String hex = String.format("%02x", b); + hexHmac.append(hex); + } + return hexHmac.toString(); + } + + private static String base64Encode(String data) { + return Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8)); + } + + private static boolean validateHMAC(String actualHMAC, String expectedHMAC) { + return actualHMAC.equals(expectedHMAC); + } +} + diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 096d4c988..4ba6adabc 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -249,6 +249,7 @@ keycloak-user: email-actions: ${keycloack_user_email_actions:} claims: url: ${claims_url:http://localhost:8082} + domain-url: ${claims_domain-url:http://registration.uphrh.in:8082} download-path: /api/v1/files/download authentication: enabled: ${authentication_enabled:true} From 9ab99598402a3a040da0af980cd2a76692b57704 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Thu, 24 Aug 2023 17:39:28 +0530 Subject: [PATCH 36/43] api request --- .../sunbirdrc/registry/controller/RegistryEntityController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 0ea0386e1..31cdf171b 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -1389,7 +1389,7 @@ private void shareCredentials(JsonNode node, String url) { public JsonNode searchEntityForDGL(ObjectNode searchNode) { JsonNode result = null; - String[] entityArr = {"StudentFromUP","StudentOutSideUP"}; + String[] entityArr = {"StudentFromUP","StudentOutSideUP","StudentForeignVerification","StudentGoodstanding"}; for (String entityName: entityArr) { try { ArrayNode entity = JsonNodeFactory.instance.arrayNode(); From 818b6996e57474f2203df94abba348ccbbd1ddaf Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Fri, 25 Aug 2023 15:54:08 +0530 Subject: [PATCH 37/43] updates --- .../controller/RegistryEntityController.java | 85 ++++++++-------- .../src/main/resources/application.yml | 2 +- .../public/_schemas/studentFromUP.json | 96 ++++++++++++------ .../public/_schemas/studentOutsideUp.json | 97 +++++++++++++------ 4 files changed, 178 insertions(+), 102 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 31cdf171b..51133d726 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -32,11 +32,8 @@ import dev.sunbirdrc.registry.transform.Configuration; import dev.sunbirdrc.registry.transform.Data; import dev.sunbirdrc.registry.transform.ITransformer; -import dev.sunbirdrc.registry.util.ClaimRequestClient; +import dev.sunbirdrc.registry.util.*; import org.agrona.Strings; -import dev.sunbirdrc.registry.util.DigiLockerUtils; -import dev.sunbirdrc.registry.util.DocDetails; -import dev.sunbirdrc.registry.util.ViewTemplateManager; import dev.sunbirdrc.validators.ValidationException; import org.apache.commons.lang3.StringUtils; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -94,6 +91,7 @@ public class RegistryEntityController extends AbstractController { @Value("${authentication.enabled:true}") boolean securityEnabled; + @Value("${certificate.enableExternalTemplates:false}") boolean externalTemplatesEnabled; @@ -1141,10 +1139,11 @@ public ResponseEntity issueCertificateToDigiLocker(HttpServletRequest re @RequestMapping(value = "/api/v1/pullDocUriRequest/{entityName}", method = RequestMethod.POST, produces = {MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_XML_VALUE}) - public ResponseEntity pullDocURI(HttpServletRequest request) { + public ResponseEntity pullDocURI(HttpServletRequest request) throws Exception { String statusCode = "1"; Scanner scanner = null; - String hmac = request.getHeader("hmac"); + String hmacFromRequest = request.getHeader("hmac"); + logger.info(hmacFromRequest+":Hmac From server"); try { scanner = new Scanner(request.getInputStream(), "UTF-8"); } catch (IOException e) { @@ -1157,49 +1156,47 @@ public ResponseEntity pullDocURI(HttpServletRequest request) { xmlString = scanner1.next(); } PullDocRequest pullDocRequest = null; - try { - pullDocRequest = DigiLockerUtils.processPullDocRequest(xmlString); - } catch (Exception e) { - throw new RuntimeException(e); - } - boolean isValidReq = DigiLockerUtils.verifyHmac(pullDocRequest.getTs(), DIGILOCKER_KEY, hmac); -// if(isValidReq){ -// statusCode = "0"; -// HttpHeaders headers = new HttpHeaders(); -// headers.setContentType(MediaType.APPLICATION_XML); -// return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); -// } - String fullName = pullDocRequest.getDocDetails().getFullName(); - String dob = pullDocRequest.getDocDetails().getDob(); - JsonNode searchNode = DigiLockerUtils.getQuryNode(fullName, dob); - JsonNode result = searchEntityForDGL((ObjectNode)searchNode); - if(result==null){ - statusCode = "0"; - return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); - } - String credName = pullDocRequest.getDocDetails().getUri(); - credName = "issuance/"+credName+".pdf"; - byte[] cred = certificateService.getCred(credName); - - // get stident by osid - String osid = pullDocRequest.getTxn(); - if(cred!=null){ + boolean isValidReq = HmacValidator.validateHmac(xmlString,hmacFromRequest,DIGILOCKER_KEY); + if(isValidReq) { try { - //DigiLockerUtils.getPersonDetail(result, "entityName"); - Person person = new Person(); - person.setDob(dob); - person.setDob(fullName); - PullDocResponse pullDocResponse = DigiLockerUtils.getDocPullUriResponse(pullDocRequest, statusCode, cred, person); - Object responseString = DigiLockerUtils.convertJaxbToPullDoc(pullDocResponse); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_XML); - return new ResponseEntity<>(responseString, headers, HttpStatus.OK); + pullDocRequest = DigiLockerUtils.processPullDocRequest(xmlString); } catch (Exception e) { statusCode = "0"; - e.printStackTrace(); return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); } - }else{ + String fullName = pullDocRequest.getDocDetails().getFullName(); + String dob = pullDocRequest.getDocDetails().getDob(); + JsonNode searchNode = DigiLockerUtils.getQuryNode(fullName, dob); + JsonNode result = searchEntityForDGL((ObjectNode) searchNode); + if (result == null) { + statusCode = "0"; + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); + } + String credName = pullDocRequest.getDocDetails().getUri(); + credName = "issuance/" + credName + ".pdf"; + byte[] cred = certificateService.getCred(credName); + if (cred != null) { + try { + //DigiLockerUtils.getPersonDetail(result, "entityName"); + Person person = new Person(); + person.setDob(dob); + person.setDob(fullName); + PullDocResponse pullDocResponse = DigiLockerUtils.getDocPullUriResponse(pullDocRequest, statusCode, cred, person); + Object responseString = DigiLockerUtils.convertJaxbToPullDoc(pullDocResponse); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_XML); + return new ResponseEntity<>(responseString, headers, HttpStatus.OK); + } catch (Exception e) { + statusCode = "0"; + e.printStackTrace(); + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); + } + + } else { + statusCode = "0"; + return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); + } + }else { statusCode = "0"; return new ResponseEntity<>(statusCode, HttpStatus.NOT_FOUND); } diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 4ba6adabc..ad5880967 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -66,7 +66,7 @@ registry: host: ${redis_host:localhost} port: ${redis_port:6379} digilocker: - hkey: ${hmackey:vTV3Jl81kXDOca70TT2+P/YAb5DXnS+DDr/ArlFhow0=} + hmackey: ${digilocker_hmackey:vTV3Jl81kXDOca70TT2+P/YAb5DXnS+DDr/ArlFhow0=} workflow: enabled: ${workflow.enable:true} diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 6c63e5db6..6cb214371 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -433,34 +433,74 @@ } ], "certificateTemplates": { - "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", - "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", - "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/degree", - "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", - "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", - "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding", - "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate", - "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r", - "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r", - "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate" + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html", + "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html", + "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BDS_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BDS-REG-24987.html", + "BDS_REG_STATE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BDS_REG_STATE.html", + "BDS_REG_NO" :"https://raw.githubusercontent.com/kumarpawantarento/templates/main/BDS_REG_NO.html", + "BDS_DUPLICATE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BDS_REG_DUPLICATE.html", + "BDS_REISSUE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/REISSUE-BDS.html", + "CME_CERTIFICATE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/CME.html", + "CORRECTED_PRO": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/CORRECTED_PRO.html", + "GOODTANDING_UPDC": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/goodstanding.html", + "DH_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/DH-REG.html", + "MDS_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MDS-REG.html", + "NOC": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/NOC.html", + "BDS_PRO": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/PRO.html", + "ORTHOPAEDIC_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Additional-Registration.html", + "MD_MEDICINE_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/ADDITIONAL_UP.html", + "CORRECTION_PROVISIONAL": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/CORRECTION-provision.html", + "OTORHINOLARYNGOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/CORRECTION-OTHER.html", + "MBBS_CORRECTION_PERMANANT": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/COORECTION-permanent.html", + "GOODTANDING_UPMC": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GOODSTANDING2.html", + "MBBS_PERMANANT_REG_FOREIGN": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-permanent-foreign.html", + "MBBS_PERMANANT_REG_FOREIGN_OTHER_COUNCIL ": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-Permanent-Registration-FORGIN-OTHER-COUNCIL-REGISTERD.html", + "MBBS_PERMANANT_REG_OTHER_THAN_UP": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-permanent-R.html", + "MBBS_PERMANANT_REG_UP": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-Permanent-Registration-Certificate-UP.html", + "MBBS_PROVISIONAL_FOREIGN": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-provisional.html", + "MBBS_MATRIMONY_NAME_CHANGE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Matrimonial-name-change.html", + "MD_RADIODIAGNOSIS": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Matrimony-Name-Change.additional.html", + "NOC_UPMC": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/NOC-medical.html", + "MBBS_PERMANANT_REG_DUPLICATE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Permanent-registration-Duplicate.html", + "MBBS_PERMANANT_REGISTRATION_REISSUE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Permenant-registratio-re-issue.html", + "ANM_REG_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING_REG":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING_CORRECTED_REG":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/bsc-r-corr.html", + "BSC_NURSING_DUPLICATE_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/duplicate-r.html", + "GNM_REG_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "GOODSTANDING_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding-upnc.html", + "MSC_OBSTETRIC_GYNAECOLOGY":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r-UPNC.html", + "GNM_REG-UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/name-change.html", + "NOC_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/NOC-0001.html", + "NPCC_REG":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/NPCC-r.html", + "PBBSC_REG_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "PHYCHIATRIC_DIPLOMA":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/PSYCH.html" } } } diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json index fd6bad2ce..a2854444b 100644 --- a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -433,34 +433,73 @@ } ], "certificateTemplates": { - "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", - "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D", - "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", - "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/degree", - "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", - "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing", - "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding", - "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate", - "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r", - "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r", - "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate", - "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate" - } + "ANM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ANM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BABY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BABY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "DEGREE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCA_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "ETCT_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "ETCT_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GNM_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "GNM_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHARMACY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "GOODSTANDING_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding.html", + "FOREIGN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Foreign-certificate.html", + "MSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "PBBSC_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "SANITATION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "SANITATION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "PHYSIOTHERAPY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OPTOMETRY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OPTOMETRY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "OTTECHNICIAN_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "OTTECHNICIAN_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "CARDIOLOGY_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "CARDIOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BLOOD_TRANSFUSION_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate.html", + "BLOOD_TRANSFUSION_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BABY-D.html", + "BDS_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BDS-REG-24987.html", + "BDS_REG_STATE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BDS_REG_STATE.html", + "BDS_REG_NO" :"https://raw.githubusercontent.com/kumarpawantarento/templates/main/BDS_REG_NO.html", + "BDS_DUPLICATE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/BDS_REG_DUPLICATE.html", + "BDS_REISSUE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/REISSUE-BDS.html", + "CME_CERTIFICATE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/CME.html", + "CORRECTED_PRO": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/CORRECTED_PRO.html", + "GOODTANDING_UPDC": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/goodstanding.html", + "DH_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/DH-REG.html", + "MDS_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MDS-REG.html", + "NOC": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/NOC.html", + "BDS_PRO": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/PRO.html", + "ORTHOPAEDIC_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Additional-Registration.html", + "MD_MEDICINE_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/ADDITIONAL_UP.html", + "CORRECTION_PROVISIONAL": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/CORRECTION-provision.html", + "OTORHINOLARYNGOLOGY_DIPLOMA": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/CORRECTION-OTHER.html", + "MBBS_CORRECTION_PERMANANT": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/COORECTION-permanent.html", + "GOODTANDING_UPMC": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/GOODSTANDING2.html", + "MBBS_PERMANANT_REG_FOREIGN": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-permanent-foreign.html", + "MBBS_PERMANANT_REG_FOREIGN_OTHER_COUNCIL ": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-Permanent-Registration-FORGIN-OTHER-COUNCIL-REGISTERD.html", + "MBBS_PERMANANT_REG_OTHER_THAN_UP": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-permanent-R.html", + "MBBS_PERMANANT_REG_UP": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-Permanent-Registration-Certificate-UP.html", + "MBBS_PROVISIONAL_FOREIGN": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/MBBS-provisional.html", + "MBBS_MATRIMONY_NAME_CHANGE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Matrimonial-name-change.html", + "MD_RADIODIAGNOSIS": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Matrimony-Name-Change.additional.html", + "NOC_UPMC": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/NOC-medical.html", + "MBBS_PERMANANT_REG_DUPLICATE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Permanent-registration-Duplicate.html", + "MBBS_PERMANANT_REGISTRATION_REISSUE": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/Permenant-registratio-re-issue.html", + "ANM_REG_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING_REG":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "BSC_NURSING_CORRECTED_REG":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/bsc-r-corr.html", + "BSC_NURSING_DUPLICATE_REG": "https://raw.githubusercontent.com/kumarpawantarento/templates/main/duplicate-r.html", + "GNM_REG_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/registration-certificate-nursing.html", + "GOODSTANDING_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/GoodStanding-upnc.html", + "MSC_OBSTETRIC_GYNAECOLOGY":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r-UPNC.html", + "GNM_REG-UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/name-change.html", + "NOC_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/NOC-0001.html", + "NPCC_REG":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/NPCC-r.html", + "PBBSC_REG_UPNC":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/MSC-r.html", + "PHYCHIATRIC_DIPLOMA":"https://raw.githubusercontent.com/kumarpawantarento/templates/main/PSYCH.html" } } } From 14927e95740c4811bf71998d2926462700c79300 Mon Sep 17 00:00:00 2001 From: Mahesh Maney R Date: Sun, 27 Aug 2023 13:06:08 +0530 Subject: [PATCH 38/43] adding user represtation and role representation details to auth token . --- .../dev/sunbirdrc/service/UserService.java | 68 +++++++++++++------ 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/java/user-management/src/main/java/dev/sunbirdrc/service/UserService.java b/java/user-management/src/main/java/dev/sunbirdrc/service/UserService.java index 068c7491b..f04c241f1 100644 --- a/java/user-management/src/main/java/dev/sunbirdrc/service/UserService.java +++ b/java/user-management/src/main/java/dev/sunbirdrc/service/UserService.java @@ -106,26 +106,56 @@ public UserTokenDetailsDTO loginAndGenerateKeycloakToken(UserLoginDTO userLoginD if (userLoginDTO != null && StringUtils.hasText(userLoginDTO.getUsername()) && StringUtils.hasText(userLoginDTO.getPassword())) { - try { - TokenManager tokenManager = keycloakConfig - .getUserKeycloak(userLoginDTO.getUsername(), userLoginDTO.getPassword()).tokenManager(); - - AccessTokenResponse accessTokenResponse = tokenManager.getAccessToken(); - - return UserTokenDetailsDTO.builder() - .accessToken(accessTokenResponse.getToken()) - .expiresIn(accessTokenResponse.getExpiresIn()) - .refreshToken(accessTokenResponse.getRefreshToken()) - .refreshExpiresIn(accessTokenResponse.getRefreshExpiresIn()) - .tokenType(accessTokenResponse.getTokenType()) - .scope(accessTokenResponse.getScope()) - .build(); - } catch (NotAuthorizedException e) { - throw new AuthorizationException("Credentials have authorization issue"); - } catch (Exception e) { - throw new KeycloakUserException("Unable to get user detils - Update user"); + String username = userLoginDTO.getUsername(); + LOGGER.info("username {}", username); + List userRepresentationList = getUserDetails(username); + LOGGER.info("userRepresentationList {}", userRepresentationList); + if (userRepresentationList != null && !userRepresentationList.isEmpty()) { + + Optional userRepresentationOptional = userRepresentationList.stream() + .filter(userRepresentation -> username.equalsIgnoreCase(userRepresentation.getUsername())) + .findFirst(); + LOGGER.info("userRepresentationOptional {}", userRepresentationOptional); + + if (!userRepresentationOptional.isPresent()) { + throw new UserCredentialsException("Username missing."); + } + + List roleRepresentationList = getSystemUsersResource() + .get(userRepresentationOptional.get().getId()) + .roles().realmLevel().listEffective(); + + LOGGER.info("roleRepresentationList {}", roleRepresentationList); + + try { + TokenManager tokenManager = keycloakConfig + .getUserKeycloak(userLoginDTO.getUsername(), userLoginDTO.getPassword()).tokenManager(); + + AccessTokenResponse accessTokenResponse = tokenManager.getAccessToken(); + + return UserTokenDetailsDTO.builder() + .accessToken(accessTokenResponse.getToken()) + .expiresIn(accessTokenResponse.getExpiresIn()) + .refreshToken(accessTokenResponse.getRefreshToken()) + .refreshExpiresIn(accessTokenResponse.getRefreshExpiresIn()) + .tokenType(accessTokenResponse.getTokenType()) + .scope(accessTokenResponse.getScope()) + .userRepresentation(userRepresentationOptional.get()) + .roleRepresentationList(roleRepresentationList) + .build(); + } catch (NotAuthorizedException e) { + LOGGER.error("Credentials have authorization issue",e); + throw new AuthorizationException("Credentials have authorization issue"); + } catch (Exception e) { + LOGGER.error("Unable to get user details",e); + throw new KeycloakUserException("Unable to get user details"); + } + } else { + LOGGER.info("User details not found"); + throw new UserCredentialsException("User details not found"); } } else { + LOGGER.info("User credentials are invalid"); throw new UserCredentialsException("User credentials are invalid"); } } @@ -477,7 +507,7 @@ public void persistUserDetailsWithCredentials(@NonNull CustomUserDTO customUserD } /** - * @param adminDTO + * @param customUsernameDTO * @throws Exception */ public void generateCustomUserOtp(CustomUsernameDTO customUsernameDTO) { From ff682aa817a6a11717a807c30eba3e158b6fc526 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 29 Aug 2023 11:59:49 +0530 Subject: [PATCH 39/43] outside up fix --- .../main/resources/public/_schemas/studentOutsideUp.json | 8 -------- 1 file changed, 8 deletions(-) diff --git a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json index a2854444b..7bfb6b04c 100644 --- a/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json +++ b/java/registry/src/main/resources/public/_schemas/studentOutsideUp.json @@ -116,14 +116,6 @@ } }, "_osConfig": { - - "ownershipAttributes": [ - { - "email": "/email", - "mobile": "/phoneNumber", - "userId": "/phoneNumber" - } - ], "inviteRoles": ["anonymous"], "roles": ["StudentOutsideUP","StudentFromUP"], "attestationPolicies": [ From 84f75d7aa7bfa3c766d4dcd47e79d53c8cd418ff Mon Sep 17 00:00:00 2001 From: rkrahu Date: Tue, 29 Aug 2023 12:30:54 +0530 Subject: [PATCH 40/43] Auto mail for foreign, outside, from up and good standing candidate. Manual mail to foreign/outside from dashboard by regulator. --- .../claim/config/PropertyMapper.java | 24 ++ .../claim/controller/EmailController.java | 17 +- .../controller/OutsideStudentController.java | 26 +- .../claim/dto/ManualPendingMailDTO.java | 24 ++ .../sunbirdrc/claim/dto/PendingMailDTO.java | 6 + .../dev/sunbirdrc/claim/entity/Claim.java | 10 +- .../claim/entity/StudentOutsideUP.java | 39 +++ .../claim/quartz/MailingJobExecutor.java | 33 ++- .../repository/StudentOutsideUpRowMapper.java | 44 +++ .../claim/service/AsyncMailSender.java | 91 +++++- .../sunbirdrc/claim/service/ClaimService.java | 10 +- .../sunbirdrc/claim/service/EmailService.java | 66 +++-- .../StudentForeignVerificationService.java | 16 +- .../service/StudentOutsideUpService.java | 93 ++++++ .../src/main/resources/application.properties | 10 +- .../resources/templates/candidate-details.ftl | 142 ---------- .../templates/ec-pending-item-mail.ftl | 80 ++++++ .../foreign-student-candidate-details.ftl | 257 +++++++++++++++++ .../outside-up-student-candidate-details.ftl | 267 ++++++++++++++++++ .../student-foreign-pending-item-mail.ftl | 49 ++++ ...student-from-outside-pending-item-mail.ftl | 49 ++++ .../student-from-up-pending-item-mail.ftl | 47 +++ ...tudent-good-standing-pending-item-mail.ftl | 49 ++++ .../controller/RegistryEntityController.java | 26 ++ .../model/dto/ManualPendingMailDTO.java | 13 +- .../registry/util/ClaimRequestClient.java | 9 + 26 files changed, 1295 insertions(+), 202 deletions(-) create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/dto/ManualPendingMailDTO.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentOutsideUP.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/repository/StudentOutsideUpRowMapper.java create mode 100644 java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentOutsideUpService.java delete mode 100644 java/claim/src/main/resources/templates/candidate-details.ftl create mode 100644 java/claim/src/main/resources/templates/ec-pending-item-mail.ftl create mode 100644 java/claim/src/main/resources/templates/foreign-student-candidate-details.ftl create mode 100644 java/claim/src/main/resources/templates/outside-up-student-candidate-details.ftl create mode 100644 java/claim/src/main/resources/templates/student-foreign-pending-item-mail.ftl create mode 100644 java/claim/src/main/resources/templates/student-from-outside-pending-item-mail.ftl create mode 100644 java/claim/src/main/resources/templates/student-from-up-pending-item-mail.ftl create mode 100644 java/claim/src/main/resources/templates/student-good-standing-pending-item-mail.ftl diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java index ecf50be7b..28f5cfaf5 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/config/PropertyMapper.java @@ -13,6 +13,15 @@ public class PropertyMapper { @Value("${foreign.pending.item.subject}") private String foreignPendingItemSubject; + @Value("${outside.up.pending.item.subject}") + private String outsideUpPendingItemSubject; + + @Value("${from.up.pending.item.subject}") + private String fromUpPendingItemSubject; + + @Value("${good.standing.pending.item.subject}") + private String goodStandingPendingItemSubject; + @Value("${up.council.name}") private String upCouncilName; @@ -22,9 +31,24 @@ public class PropertyMapper { @Value("${student.foreign.verification.table.name}") private String studentForeignVerificationTableName; + @Value("${student.outside.verification.table.name}") + private String studentOutsideVerificationTableName; + @Value("${claim.url}") private String claimUrl; @Value("${registry.shard.id}") private String registryShardId; + + @Value("${student.foreign.entity.name}") + private String studentForeignEntityName; + + @Value("${student.from.up.entity.name}") + private String studentFromUpEntityName; + + @Value("${student.from.outside.entity.name}") + private String studentFromOutsideEntityName; + + @Value("${student.good.standing.entity.name}") + private String studentGoodStandingEntityName; } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java index dbd9a726e..9f3a665e4 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/EmailController.java @@ -1,9 +1,7 @@ package dev.sunbirdrc.claim.controller; -import dev.sunbirdrc.claim.dto.BarCode; -import dev.sunbirdrc.claim.dto.CertificateMailDto; -import dev.sunbirdrc.claim.dto.MailDto; -import dev.sunbirdrc.claim.dto.PendingMailDTO; +import dev.sunbirdrc.claim.dto.*; +import dev.sunbirdrc.claim.service.AsyncMailSender; import dev.sunbirdrc.claim.service.EmailService; import net.sourceforge.barbecue.Barcode; import net.sourceforge.barbecue.BarcodeFactory; @@ -30,6 +28,10 @@ public class EmailController { @Autowired private EmailService emailService; + + @Autowired + private AsyncMailSender asyncMailSender; + private static final Logger logger = LoggerFactory.getLogger(EmailController.class); private static final Font BARCODE_TEXT_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 8); @Autowired @@ -124,4 +126,11 @@ public ResponseEntity sendPendingItemMail(@RequestHeader HttpHeaders hea return new ResponseEntity<>("Sending manual foreign pending item mail", HttpStatus.OK); } + + @RequestMapping(value = "/api/v1/sendEcPendingItemMail", method = RequestMethod.POST) + public ResponseEntity sendPendingItemMail(@RequestHeader HttpHeaders headers, + @RequestBody ManualPendingMailDTO manualPendingMailDTO) { + asyncMailSender.sendEcPendingItemMail(manualPendingMailDTO); + return new ResponseEntity<>("Mail is sending", HttpStatus.OK); + } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/OutsideStudentController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/OutsideStudentController.java index 139bc4e00..14146223c 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/OutsideStudentController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/OutsideStudentController.java @@ -2,7 +2,7 @@ import dev.sunbirdrc.claim.service.ClaimService; import dev.sunbirdrc.claim.service.StudentForeignVerificationService; -import dev.sunbirdrc.claim.status.Status; +import dev.sunbirdrc.claim.service.StudentOutsideUpService; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -13,12 +13,15 @@ import org.springframework.web.bind.annotation.RestController; @RestController -@RequestMapping("/api/v1/outside") +@RequestMapping("/api/v1") public class OutsideStudentController { @Autowired private StudentForeignVerificationService foreignVerificationService; + @Autowired + private StudentOutsideUpService studentOutsideUpService; + @Autowired private ClaimService claimService; @@ -33,12 +36,23 @@ public ResponseEntity getForeignStudentVerificationDetail(@PathVariable } } - @GetMapping("/foreignStudent/verify/{id}/{status}") + @GetMapping("/outsideStudent/verify/{id}/{status}") public ResponseEntity verifyForeignStudentVerification(@PathVariable String id, - @PathVariable Status status) { + @PathVariable String status) { + + claimService.updateOutsideStudentStatus(id, status); + + return new ResponseEntity<>("Outside/Foreign student verification updated", HttpStatus.OK); + } - claimService.updateForeignStudentStatus(id, status); + @GetMapping("/outsideStudent/{id}") + public ResponseEntity getOutsideStudentVerificationDetail(@PathVariable String id) { + String template = studentOutsideUpService.generatePendingMailContent(id); - return new ResponseEntity<>("Foreign student verification updated", HttpStatus.OK); + if (!StringUtils.isEmpty(template)) { + return new ResponseEntity<>(template, HttpStatus.OK); + } else { + return ResponseEntity.notFound().build(); + } } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/ManualPendingMailDTO.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/ManualPendingMailDTO.java new file mode 100644 index 000000000..987976f21 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/ManualPendingMailDTO.java @@ -0,0 +1,24 @@ +package dev.sunbirdrc.claim.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ManualPendingMailDTO { + private String outsideEntityMailId; + private String name; + private String email; + private String council; + private String gender; + private String examBody; + private String diplomaNumber; + private String nursingCollage; + private String docProof; + private String courseState; + private String courseCouncil; + private String country; + private String state; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java index a39dd30d0..a40d282cb 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/dto/PendingMailDTO.java @@ -20,4 +20,10 @@ public class PendingMailDTO { private String credType; private String registrationNumber; private String verifyLink; + private String nurseRegNo; + private String registrationType; + private String courseName; + private String workPlace; + private String examBody; + } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java index 9c006eb88..361152ef6 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/Claim.java @@ -64,14 +64,14 @@ public void setCredType(String credType) { private String attestorUserId; @Column - private String foreignStudentStatus; + private String outsideStudentStatus; - public String getForeignStudentStatus() { - return foreignStudentStatus; + public String getOutsideStudentStatus() { + return outsideStudentStatus; } - public void setForeignStudentStatus(String foreignStudentStatus) { - this.foreignStudentStatus = foreignStudentStatus; + public void setOutsideStudentStatus(String outsideStudentStatus) { + this.outsideStudentStatus = outsideStudentStatus; } @PrePersist diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentOutsideUP.java b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentOutsideUP.java new file mode 100644 index 000000000..0cda50ee1 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/entity/StudentOutsideUP.java @@ -0,0 +1,39 @@ +package dev.sunbirdrc.claim.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class StudentOutsideUP { + private String aadhaarNo; + private String barCode; + private String candidatePic; + private String council; + private String courseName; + private String courseState; + private String date; + private String dateOfBirth; + private String email; + private String examBody; + private String fathersName; + private String feeReciptNo; + private String finalYearRollNo; + private String gender; + private String joiningMonth; + private String joiningYear; + private String mothersName; + private String name; + private String nurseRegNo; + private String nursingCollage; + private String osid; + private String osOwner; + private String passingMonth; + private String passingYear; + private String phoneNumber; + private String registrationNo; + private String registrationType; + private String title; +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/MailingJobExecutor.java b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/MailingJobExecutor.java index 6b4d092d3..05f588ca7 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/MailingJobExecutor.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/quartz/MailingJobExecutor.java @@ -1,6 +1,9 @@ package dev.sunbirdrc.claim.quartz; +import dev.sunbirdrc.claim.config.PropertyMapper; import dev.sunbirdrc.claim.service.EmailService; +import dev.sunbirdrc.claim.service.StudentForeignVerificationService; +import dev.sunbirdrc.claim.service.StudentOutsideUpService; import lombok.extern.slf4j.Slf4j; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; @@ -17,11 +20,39 @@ public class MailingJobExecutor extends QuartzJobBean { @Autowired private EmailService emailService; + @Autowired + private StudentForeignVerificationService foreignVerificationService; + + @Autowired + private StudentOutsideUpService studentOutsideUpService; + + @Autowired + private PropertyMapper propertyMapper; + @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { log.info(">>>>>>>>>>>> Mail for foreign council job started :: " + new Date(System.currentTimeMillis()) + " <<<<<<<<<<<<<<<<"); - emailService.sendForeignPendingItemMail(); + if (foreignVerificationService.isStudentForeignVerificationTableExist()) { + log.info(">>>>>>>>>>>>>>> Sending auto mail to foreign student pending item"); + emailService.autoSendPendingItemMail(propertyMapper.getStudentForeignEntityName()); + } else { + log.error(">>>>>>>>>> Unable to find student foreign verification table - Further process will not be executed"); + } + + if (studentOutsideUpService.isStudentFromOutsideVerificationTableExist()) { + log.info(">>>>>>>>>>>>>>> Sending auto mail to student from outside pending item"); + emailService.autoSendPendingItemMail(propertyMapper.getStudentFromOutsideEntityName()); + } else { + log.error(">>>>>>>>>>> Unable to find student from outside verification table - Further process will not be executed"); + } + + log.info(">>>>>>>>>>>>>>> Sending auto mail to student from up pending item"); + emailService.autoSendPendingItemMail(propertyMapper.getStudentFromUpEntityName()); + + log.info(">>>>>>>>>>>>>>> Sending auto mail to student good standing pending item"); + emailService.autoSendPendingItemMail(propertyMapper.getStudentGoodStandingEntityName()); + log.info(">>>>>>>>>>>> Mail for foreign council has been completed :: " + new Date(System.currentTimeMillis()) + " <<<<<<<<<<<<<<<<"); } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/StudentOutsideUpRowMapper.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/StudentOutsideUpRowMapper.java new file mode 100644 index 000000000..30ec33787 --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/StudentOutsideUpRowMapper.java @@ -0,0 +1,44 @@ +package dev.sunbirdrc.claim.repository; + +import dev.sunbirdrc.claim.entity.StudentForeignVerification; +import dev.sunbirdrc.claim.entity.StudentOutsideUP; +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class StudentOutsideUpRowMapper implements RowMapper { + @Override + public StudentOutsideUP mapRow(ResultSet rs, int rowNum) throws SQLException { + return new StudentOutsideUP( + rs.getString("aadhaarNo"), + rs.getString("barCode"), + rs.getString("candidatePic"), + rs.getString("council"), + rs.getString("courseName"), + rs.getString("courseState"), + rs.getString("date"), + rs.getString("dateOfBirth"), + rs.getString("email"), + rs.getString("examBody"), + rs.getString("fathersName"), + rs.getString("feeReciptNo"), + rs.getString("finalYearRollNo"), + rs.getString("gender"), + rs.getString("joiningMonth"), + rs.getString("joiningYear"), + rs.getString("mothersName"), + rs.getString("name"), + rs.getString("nurseRegNo"), + rs.getString("nursingCollage"), + rs.getString("osid"), + rs.getString("osOwner"), + rs.getString("passingMonth"), + rs.getString("passingYear"), + rs.getString("phoneNumber"), + rs.getString("registrationNo"), + rs.getString("registrationType"), + rs.getString("title") + ); + } +} diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/AsyncMailSender.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/AsyncMailSender.java index ebb369957..a4ffd75ea 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/AsyncMailSender.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/AsyncMailSender.java @@ -2,6 +2,7 @@ import dev.sunbirdrc.claim.config.PropertyMapper; import dev.sunbirdrc.claim.controller.EmailController; +import dev.sunbirdrc.claim.dto.ManualPendingMailDTO; import dev.sunbirdrc.claim.dto.PendingMailDTO; import dev.sunbirdrc.claim.entity.Regulator; import dev.sunbirdrc.claim.exception.ClaimMailException; @@ -43,7 +44,8 @@ public class AsyncMailSender { */ @Async public void sendPendingMailToRegulatorList(@NonNull List pendingMailDTOList, - List regulatorList) { + List regulatorList, + String entityName) { for (Regulator regulator : regulatorList) { try { @@ -51,11 +53,11 @@ public void sendPendingMailToRegulatorList(@NonNull List pending MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); - mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); + mimeMessageHelper.setSubject(getSubject(entityName)); mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(), "Auto generated mail for pending item")); mimeMessageHelper.setTo(regulator.getEmail()); - mimeMessageHelper.setText(generatePendingMailContent(pendingMailDTOList, regulator.getName()), true); + mimeMessageHelper.setText(generatePendingMailContent(pendingMailDTOList, regulator.getName(), entityName), true); mailSender.send(mimeMessageHelper.getMimeMessage()); } catch (Exception e) { @@ -71,7 +73,8 @@ public void sendPendingMailToRegulatorList(@NonNull List pending * @return */ private String generatePendingMailContent(@NonNull List pendingMailDTOList, - @NonNull String regulatorName) { + @NonNull String regulatorName, + @NonNull String entityName) { String processedTemplateString = null; Map mailMap = new HashMap<>(); @@ -80,19 +83,46 @@ private String generatePendingMailContent(@NonNull List pendingM try { freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); - Template template = freeMarkerConfiguration.getTemplate("pending-item-mail.ftl"); + Template template = freeMarkerConfiguration.getTemplate(getTemplateName(entityName)); processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); } catch (TemplateException e) { - logger.error("TemplateException while creating auto mail template for foreing pending item ", e); - throw new ClaimMailException("Error while creating auto mail template for foreing pending item"); + logger.error("TemplateException while creating auto mail template for pending item ", e); + throw new ClaimMailException("Error while creating auto mail template for pending item"); } catch (IOException e) { - logger.error("IOException while creating auto mail template for foreing pending item ", e); - throw new ClaimMailException("Error while creating auto mail template for foreing pending item"); + logger.error("IOException while creating auto mail template for pending item ", e); + throw new ClaimMailException("Error while creating auto mail template for pending item"); } return processedTemplateString; } + private String getSubject(String entityName) { + if (propertyMapper.getStudentForeignEntityName().equalsIgnoreCase(entityName)) { + return propertyMapper.getForeignPendingItemSubject(); + }else if (propertyMapper.getStudentFromOutsideEntityName().equalsIgnoreCase(entityName)) { + return propertyMapper.getOutsideUpPendingItemSubject(); + } else if (propertyMapper.getStudentFromUpEntityName().equalsIgnoreCase(entityName)) { + return propertyMapper.getFromUpPendingItemSubject(); + } else if (propertyMapper.getStudentGoodStandingEntityName().equalsIgnoreCase(entityName)) { + return propertyMapper.getGoodStandingPendingItemSubject(); + } else { + throw new ClaimMailException("Unable to find appropriate template for mail"); + } + } + private String getTemplateName(String entityName) { + if (propertyMapper.getStudentForeignEntityName().equalsIgnoreCase(entityName)) { + return "student-foreign-pending-item-mail.ftl"; + }else if (propertyMapper.getStudentFromOutsideEntityName().equalsIgnoreCase(entityName)) { + return "student-from-outside-pending-item-mail.ftl"; + } else if (propertyMapper.getStudentFromUpEntityName().equalsIgnoreCase(entityName)) { + return "student-from-up-pending-item-mail.ftl"; + } else if (propertyMapper.getStudentGoodStandingEntityName().equalsIgnoreCase(entityName)) { + return "student-good-standing-pending-item-mail.ftl"; + } else { + throw new ClaimMailException("Unable to find appropriate template for mail"); + } + } + /** * @param pendingMailDTO * @param regulatorName @@ -116,7 +146,7 @@ public void sendManualPendingMail(PendingMailDTO pendingMailDTO, @NonNull String mailSender.send(mimeMessageHelper.getMimeMessage()); } catch (Exception e) { logger.error("Exception while sending mail: ", e); - throw new ClaimMailException("Exception while composing and sending mail with OTP"); + throw new ClaimMailException("Exception while composing and sending mail for manual pending mail"); } } @@ -147,4 +177,45 @@ private String generateManualForeignPendingMailContent(PendingMailDTO pendingMai } return processedTemplateString; } + + @Async + public void sendEcPendingItemMail(ManualPendingMailDTO manualPendingMailDTO) { + try { + MimeMessage mimeMessage = mailSender.createMimeMessage(); + + MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); + + mimeMessageHelper.setSubject(propertyMapper.getForeignPendingItemSubject()); + mimeMessageHelper.setFrom(new InternetAddress(propertyMapper.getSimpleMailMessageFrom(), + "Pending action item")); + mimeMessageHelper.setTo(manualPendingMailDTO.getOutsideEntityMailId()); + mimeMessageHelper.setText(generateManualEcPendingMailContent(manualPendingMailDTO), true); + + mailSender.send(mimeMessageHelper.getMimeMessage()); + } catch (Exception e) { + logger.error("Exception while sending mail: ", e); + throw new ClaimMailException("Exception while composing and sending mail for EC pending item"); + } + } + + private String generateManualEcPendingMailContent(ManualPendingMailDTO manualPendingMailDTO) { + String processedTemplateString = null; + + Map mailMap = new HashMap<>(); + mailMap.put("candidate", manualPendingMailDTO); + + try { + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("ec-pending-item-mail.ftl"); + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + + } catch (TemplateException e) { + logger.error("TemplateException while creating manual mail template for EC pending item ", e); + throw new ClaimMailException("Error while creating manual mail template for EC pending item"); + } catch (IOException e) { + logger.error("IOException while creating manual mail template for EC pending item ", e); + throw new ClaimMailException("Error while creating manual mail template for EC pending item"); + } + return processedTemplateString; + } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java index 6394413bd..07f3be954 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/ClaimService.java @@ -11,10 +11,8 @@ import dev.sunbirdrc.claim.model.ClaimStatus; import dev.sunbirdrc.claim.repository.ClaimNoteRepository; import dev.sunbirdrc.claim.repository.ClaimRepository; -import dev.sunbirdrc.claim.status.Status; import dev.sunbirdrc.pojos.attestation.Action; import dev.sunbirdrc.registry.middleware.util.EntityUtil; -import freemarker.template.Configuration; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -148,17 +146,17 @@ public ClaimWithNotesDTO generateNotesForTheClaim(Claim claim) { * @param entityId * @param status */ - public void updateForeignStudentStatus(String entityId, Status status) { + public void updateOutsideStudentStatus(String entityId, String status) { if (!StringUtils.isEmpty(entityId) && status != null) { List claimList = claimRepository.findByEntityId(entityId); if (claimList != null && !claimList.isEmpty()) { Claim claim = claimList.get(0); - if (Status.Approved.name().equalsIgnoreCase(claim.getForeignStudentStatus())) { - throw new ClaimAlreadyProcessedException("Claim is already approved"); + if ("Completed".equalsIgnoreCase(claim.getOutsideStudentStatus())) { + throw new ClaimAlreadyProcessedException("Claim is already completed"); } else { - claim.setForeignStudentStatus(status.name()); + claim.setOutsideStudentStatus(status); claimRepository.save(claim); } } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java index baefdefed..9bfe2f044 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/EmailService.java @@ -5,7 +5,6 @@ import dev.sunbirdrc.claim.config.PropertyMapper; import dev.sunbirdrc.claim.controller.EmailController; import dev.sunbirdrc.claim.dto.CertificateMailDto; -import dev.sunbirdrc.claim.dto.MailDto; import dev.sunbirdrc.claim.dto.PendingMailDTO; import dev.sunbirdrc.claim.entity.Claim; import dev.sunbirdrc.claim.entity.Regulator; @@ -19,7 +18,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.FileSystemResource; import org.springframework.lang.NonNull; @@ -29,7 +27,6 @@ import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.scheduling.annotation.Async; -import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; @@ -194,7 +191,7 @@ private String generateAttachedCertificateMailContent(CertificateMailDto certifi return processedTemplateString; } - public void sendForeignPendingItemMail() { + public void autoSendPendingItemMail(String entityName) { if (!regulatorService.isRegulatorTableExist()) { logger.error(">>>>>>>>>>> Unable to find regulator table in database: No further process will be occurred"); return; @@ -203,19 +200,19 @@ public void sendForeignPendingItemMail() { List allClaimList = claimService.findAll(); if (allClaimList != null && !allClaimList.isEmpty()) { - List foreignCouncilNames = getPendingForeignCouncilList(allClaimList); + List pendingItemCouncilList = getPendingItemCouncilList(allClaimList, entityName); - for (String foreignCouncilName : foreignCouncilNames) { + for (String councilName : pendingItemCouncilList) { - List foreignCouncilClaims = allClaimList.stream() - .filter(claim -> foreignCouncilName.equalsIgnoreCase(getCouncilName(claim.getPropertyData()))) + List councilClaims = allClaimList.stream() + .filter(claim -> councilName.equalsIgnoreCase(getCouncilName(claim.getPropertyData()))) .collect(Collectors.toList()); - List pendingMailDTOList = collectEntityDetailsForMail(foreignCouncilClaims); + List pendingMailDTOList = collectEntityDetailsForPendingItem(councilClaims, entityName); - List regulatorList = regulatorService.findByCouncil(foreignCouncilName); + List regulatorList = regulatorService.findByCouncil(councilName); - asyncMailSender.sendPendingMailToRegulatorList(pendingMailDTOList, regulatorList); + asyncMailSender.sendPendingMailToRegulatorList(pendingMailDTOList, regulatorList, entityName); } } } @@ -224,11 +221,9 @@ public void sendForeignPendingItemMail() { * @param claimList * @return */ - private @NonNull List getPendingForeignCouncilList(@NonNull List claimList) { + private @NonNull List getPendingItemCouncilList(@NonNull List claimList, @NonNull String entityName) { List councilList = claimList.stream() - .filter(claim -> !propertyMapper.getUpCouncilName() - .equalsIgnoreCase(getCouncilName(claim.getPropertyData())) - ) + .filter(claim -> entityName.equalsIgnoreCase(claim.getEntity())) .filter(claim -> ClaimStatus.OPEN.name().equalsIgnoreCase(claim.getStatus())) .map(claim -> getCouncilName(claim.getPropertyData())) .distinct() @@ -242,7 +237,7 @@ public void sendForeignPendingItemMail() { } } - private @NonNull List collectEntityDetailsForMail(@NonNull List claimList) { + private @NonNull List collectEntityDetailsForPendingItem(@NonNull List claimList, String entityName) { List pendingMailDTOList = new ArrayList<>(); try { @@ -252,14 +247,37 @@ public void sendForeignPendingItemMail() { JsonNode jsonNode = objectMapper.readTree(propertyData); String entityId = claim.getEntityId().replace(propertyMapper.getRegistryShardId() + "-", ""); - PendingMailDTO pendingMailDTO = PendingMailDTO.builder() - .credType(jsonNode.get("credType") != null ? jsonNode.get("credType").asText() : "") - .emailAddress(jsonNode.get("email") != null ? jsonNode.get("email").asText() : "") - .refNo(jsonNode.get("refNo") != null ? jsonNode.get("refNo").asText() : "") - .name(jsonNode.get("name") != null ? jsonNode.get("name").asText() : "") - .registrationNumber(jsonNode.get("registrationNumber") != null ? jsonNode.get("registrationNumber").asText() : "") - .verifyLink(propertyMapper.getClaimUrl() + "/api/v1/outside/foreignStudent/" + entityId) - .build(); + PendingMailDTO pendingMailDTO = new PendingMailDTO(); + pendingMailDTO.setCredType(jsonNode.get("credType") != null ? jsonNode.get("credType").asText() : ""); + pendingMailDTO.setEmailAddress(jsonNode.get("email") != null ? jsonNode.get("email").asText() : ""); + pendingMailDTO.setName(jsonNode.get("name") != null ? jsonNode.get("name").asText() : ""); + + + if (propertyMapper.getStudentForeignEntityName().equalsIgnoreCase(entityName)) { + pendingMailDTO.setRefNo(jsonNode.get("refNo") != null ? jsonNode.get("refNo").asText() : ""); + pendingMailDTO.setRegistrationNumber(jsonNode.get("registrationNumber") != null + ? jsonNode.get("registrationNumber").asText() : ""); + + pendingMailDTO.setVerifyLink(propertyMapper.getClaimUrl() + "/api/v1/foreignStudent/" + entityId); + } + + if (propertyMapper.getStudentFromOutsideEntityName().equalsIgnoreCase(entityName)) { + pendingMailDTO.setNurseRegNo(jsonNode.get("nurseRegNo") != null + ? jsonNode.get("nurseRegNo").asText() : ""); + pendingMailDTO.setRegistrationType(jsonNode.get("registrationType") != null + ? jsonNode.get("registrationType").asText() : ""); + + pendingMailDTO.setVerifyLink(propertyMapper.getClaimUrl() + "/api/v1/outsideStudent/" + entityId); + } + + if (propertyMapper.getStudentFromUpEntityName().equalsIgnoreCase(entityName)) { + pendingMailDTO.setCourseName(jsonNode.get("courseName") != null ? jsonNode.get("courseName").asText() : ""); + pendingMailDTO.setExamBody(jsonNode.get("examBody") != null ? jsonNode.get("examBody").asText() : ""); + } + + if (propertyMapper.getStudentGoodStandingEntityName().equalsIgnoreCase(entityName)) { + pendingMailDTO.setCourseName(jsonNode.get("workPlace") != null ? jsonNode.get("workPlace").asText() : ""); + } pendingMailDTOList.add(pendingMailDTO); } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentForeignVerificationService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentForeignVerificationService.java index 978ae3bc4..f310e551c 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentForeignVerificationService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentForeignVerificationService.java @@ -32,6 +32,10 @@ public class StudentForeignVerificationService { @Autowired private Configuration freeMarkerConfiguration; + /** + * @param osid + * @return + */ public List findByOsid(String osid) { try { return jdbcTemplate.query("SELECT * FROM \"" + propertyMapper.getStudentForeignVerificationTableName() @@ -42,11 +46,17 @@ public List findByOsid(String osid) { } } + /** + * @return + */ public List findAll() { return jdbcTemplate.query("SELECT * from \"" + propertyMapper.getStudentForeignVerificationTableName() + "\"", new StudentForeignVerificationRowMapper()); } + /** + * @return + */ public boolean isStudentForeignVerificationTableExist() { String sqlQuery = "SELECT count(*) FROM information_schema.tables WHERE table_name = '" + propertyMapper.getStudentForeignVerificationTableName() + "'"; @@ -56,6 +66,10 @@ public boolean isStudentForeignVerificationTableExist() { return tableCount > 0; } + /** + * @param id + * @return + */ public String generatePendingMailContent(String id) { String processedTemplateString = null; List studentForeignVerificationList = findByOsid(id); @@ -69,7 +83,7 @@ public String generatePendingMailContent(String id) { try { freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); - Template template = freeMarkerConfiguration.getTemplate("candidate-details.ftl"); + Template template = freeMarkerConfiguration.getTemplate("foreign-student-candidate-details.ftl"); processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); } catch (TemplateException e) { diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentOutsideUpService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentOutsideUpService.java new file mode 100644 index 000000000..caa43fa7e --- /dev/null +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/StudentOutsideUpService.java @@ -0,0 +1,93 @@ +package dev.sunbirdrc.claim.service; + +import dev.sunbirdrc.claim.config.PropertyMapper; +import dev.sunbirdrc.claim.entity.StudentOutsideUP; +import dev.sunbirdrc.claim.exception.ClaimMailException; +import dev.sunbirdrc.claim.repository.StudentOutsideUpRowMapper; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Service +public class StudentOutsideUpService { + private static final Logger logger = LoggerFactory.getLogger(StudentForeignVerificationService.class); + @Autowired + private PropertyMapper propertyMapper; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Autowired + private Configuration freeMarkerConfiguration; + + /** + * @param osid + * @return + */ + public List findByOsid(String osid) { + try { + return jdbcTemplate.query("SELECT * FROM \"" + propertyMapper.getStudentOutsideVerificationTableName() + + "\" where osid=?", new StudentOutsideUpRowMapper(), osid); + + } catch (IncorrectResultSizeDataAccessException e) { + return null; + } + } + + /** + * @return + */ + public boolean isStudentFromOutsideVerificationTableExist() { + String sqlQuery = "SELECT count(*) FROM information_schema.tables WHERE table_name = '" + + propertyMapper.getStudentOutsideVerificationTableName() + "'"; + + Integer tableCount = jdbcTemplate.queryForObject(sqlQuery, Integer.class); + + return tableCount > 0; + } + + /** + * @param id + * @return + */ + public String generatePendingMailContent(String id) { + String processedTemplateString = null; + List studentOutsideUpList = findByOsid(id); + + if (studentOutsideUpList != null && !studentOutsideUpList.isEmpty()) { + StudentOutsideUP studentOutsideUP = studentOutsideUpList.get(0); + + Map mailMap = new HashMap<>(); + mailMap.put("candidate", studentOutsideUP); + mailMap.put("entityId", propertyMapper.getRegistryShardId() + "-" + studentOutsideUP.getOsid()); + + try { + freeMarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/templates/"); + Template template = freeMarkerConfiguration.getTemplate("outside-up-student-candidate-details.ftl"); + processedTemplateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailMap); + + } catch (TemplateException e) { + logger.error("TemplateException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } catch (IOException e) { + logger.error("IOException while creating mail template for certificate ", e); + throw new ClaimMailException("Error while creating mail template for certificate"); + } + } + + return processedTemplateString; + } + +} diff --git a/java/claim/src/main/resources/application.properties b/java/claim/src/main/resources/application.properties index 17596178c..af58e3c5c 100644 --- a/java/claim/src/main/resources/application.properties +++ b/java/claim/src/main/resources/application.properties @@ -45,14 +45,22 @@ spring.servlet.multipart.max-request-size=10MB # Mail config simple.mail.message.from = r.kishor.rahu@gmail.com -foreign.pending.item.subject = Pending Item +foreign.pending.item.subject = Foreign Pending Item +outside.up.pending.item.subject = Outside UP Pending Item +from.up.pending.item.subject = UP State Pending Item +good.standing.pending.item.subject = Good Standing Pending Item #Pending Item config up.council.name = upsmfac regulator.table.name = V_Regulator student.foreign.verification.table.name = V_StudentForeignVerification +student.outside.verification.table.name = V_StudentOutsideUP claim.url = http://localhost:8082 registry.shard.id = 1 +student.foreign.entity.name = StudentForeignVerification +student.from.up.entity.name = StudentFromUP +student.from.outside.entity.name = StudentOutsideUP +student.good.standing.entity.name = StudentGoodstanding #---------------------------- QUARTZ CONFIGS ---------------------------- samplejob.frequency=0 40 15 ? * * * diff --git a/java/claim/src/main/resources/templates/candidate-details.ftl b/java/claim/src/main/resources/templates/candidate-details.ftl deleted file mode 100644 index b933c6262..000000000 --- a/java/claim/src/main/resources/templates/candidate-details.ftl +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Candidate Details

Title${candidate.title}
Student Name${candidate.name}
Registration Type${candidate.registrationType}
Registration Number${candidate.registrationNumber}
Reference No${candidate.refNo}
Phone Number${candidate.phoneNumber}
Passing Year${candidate.passingYear}
Passing Month${candidate.passingMonth}
Nursing Collage${candidate.nursingCollage}
Mothers Name${candidate.mothersName}
Joining Year${candidate.joiningYear}
Joining Month${candidate.joiningMonth}
Gender${candidate.gender}
Final Year Roll No${candidate.finalYearRollNo}
Fathers Name${candidate.fathersName}
Exam Body${candidate.examBody}
Email${candidate.email}
Date Of Birth${candidate.dateOfBirth}
Date${candidate.date}
Course Name${candidate.courseName}
Council${candidate.council}
CandidatePic${candidate.candidatePic}
Bar Code${candidate.barCode}
Aadhaar No${candidate.aadhaarNo}
-
- - - - - -
- - - -
-
- - diff --git a/java/claim/src/main/resources/templates/ec-pending-item-mail.ftl b/java/claim/src/main/resources/templates/ec-pending-item-mail.ftl new file mode 100644 index 000000000..9118ac40f --- /dev/null +++ b/java/claim/src/main/resources/templates/ec-pending-item-mail.ftl @@ -0,0 +1,80 @@ + + + + + + +

Hi Council Admin

+ +

Pending action item for student foreign verification. Following candidate has applied for certificate.

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Candidate Details

Name${candidate.name}
Gender${candidate.gender}
Email${candidate.email}
Council${candidate.council}
Exam Body${candidate.examBody}
Diploma Number${candidate.diplomaNumber}
Nursing Collage${candidate.nursingCollage}
Doc Proof${candidate.docProof}
Course State${candidate.courseState}
Course Council${candidate.courseCouncil}
Country${candidate.country}
State${candidate.state}
+

+ +
Please follow up to respected entity
+ +

Thank you,

+

< Registration Credential Issuing Authority >

+ + diff --git a/java/claim/src/main/resources/templates/foreign-student-candidate-details.ftl b/java/claim/src/main/resources/templates/foreign-student-candidate-details.ftl new file mode 100644 index 000000000..4c6197243 --- /dev/null +++ b/java/claim/src/main/resources/templates/foreign-student-candidate-details.ftl @@ -0,0 +1,257 @@ + + + + + + + + + + + + <#if candidate.title?has_content> + + <#else> + + + + + + + <#if candidate.name?has_content> + + <#else> + + + + + + + <#if candidate.registrationType?has_content> + + <#else> + + + + + + + <#if candidate.registrationNumber?has_content> + + <#else> + + + + + + + <#if candidate.refNo?has_content> + + <#else> + + + + + + + <#if candidate.phoneNumber?has_content> + + <#else> + + + + + + + <#if candidate.passingYear?has_content> + + <#else> + + + + + + + <#if candidate.passingMonth?has_content> + + <#else> + + + + + + + <#if candidate.nursingCollage?has_content> + + <#else> + + + + + + + <#if candidate.mothersName?has_content> + + <#else> + + + + + + + <#if candidate.joiningYear?has_content> + + <#else> + + + + + + + <#if candidate.joiningMonth?has_content> + + <#else> + + + + + + + <#if candidate.gender?has_content> + + <#else> + + + + + + + <#if candidate.finalYearRollNo?has_content> + + <#else> + + + + + + + <#if candidate.fathersName?has_content> + + <#else> + + + + + + + <#if candidate.examBody?has_content> + + <#else> + + + + + + + <#if candidate.email?has_content> + + <#else> + + + + + + + <#if candidate.dateOfBirth?has_content> + + <#else> + + + + + + + <#if candidate.date?has_content> + + <#else> + + + + + + + <#if candidate.courseName?has_content> + + <#else> + + + + + + + <#if candidate.council?has_content> + + <#else> + + + + + + + <#if candidate.candidatePic?has_content> + + <#else> + + + + + + + <#if candidate.barCode?has_content> + + <#else> + + + + + + + <#if candidate.aadhaarNo?has_content> + + <#else> + + + +

Candidate Details

Title${candidate.title}
Student Name${candidate.name}
Registration Type${candidate.registrationType}
Registration Number${candidate.registrationNumber}
Reference No${candidate.refNo}
Phone Number${candidate.phoneNumber}
Passing Year${candidate.passingYear}
Passing Month${candidate.passingMonth}
Nursing Collage${candidate.nursingCollage}
Mothers Name${candidate.mothersName}
Joining Year${candidate.joiningYear}
Joining Month${candidate.joiningMonth}
Gender${candidate.gender}
Final Year Roll No${candidate.finalYearRollNo}
Fathers Name${candidate.fathersName}
Exam Body${candidate.examBody}
Email${candidate.email}
Date Of Birth${candidate.dateOfBirth}
Date${candidate.date}
Course Name${candidate.courseName}
Council${candidate.council}
CandidatePic${candidate.candidatePic}
Bar Code${candidate.barCode}
Aadhaar No${candidate.aadhaarNo}
+
+ + + + +
+ +
+
+ + diff --git a/java/claim/src/main/resources/templates/outside-up-student-candidate-details.ftl b/java/claim/src/main/resources/templates/outside-up-student-candidate-details.ftl new file mode 100644 index 000000000..e0ac3ef87 --- /dev/null +++ b/java/claim/src/main/resources/templates/outside-up-student-candidate-details.ftl @@ -0,0 +1,267 @@ + + + + + + + + + + + + <#if candidate.title?has_content> + + <#else> + + + + + + + + <#if candidate.name?has_content> + + <#else> + + + + + + + <#if candidate.aadhaarNo?has_content> + + <#else> + + + + + + + <#if candidate.barCode?has_content> + + <#else> + + + + + + + <#if candidate.council?has_content> + + <#else> + + + + + + + <#if candidate.courseName?has_content> + + <#else> + + + + + + + <#if candidate.courseState?has_content> + + <#else> + + + + + + + <#if candidate.date?has_content> + + <#else> + + + + + + + <#if candidate.dateOfBirth?has_content> + + <#else> + + + + + + + <#if candidate.email?has_content> + + <#else> + + + + + + + <#if candidate.examBody?has_content> + + <#else> + + + + + + + <#if candidate.fathersName?has_content> + + <#else> + + + + + + + <#if candidate.feeReciptNo?has_content> + + <#else> + + + + + + + <#if candidate.finalYearRollNo?has_content> + + <#else> + + + + + + + <#if candidate.gender?has_content> + + <#else> + + + + + + + <#if candidate.joiningMonth?has_content> + + <#else> + + + + + + + <#if candidate.joiningYear?has_content> + + <#else> + + + + + + + <#if candidate.mothersName?has_content> + + <#else> + + + + + + + <#if candidate.nurseRegNo?has_content> + + <#else> + + + + + + + <#if candidate.nursingCollage?has_content> + + <#else> + + + + + + + <#if candidate.passingMonth?has_content> + + <#else> + + + + + + + <#if candidate.passingYear?has_content> + + <#else> + + + + + + + <#if candidate.phoneNumber?has_content> + + <#else> + + + + + + + <#if candidate.registrationNo?has_content> + + <#else> + + + + + + + <#if candidate.registrationType?has_content> + + <#else> + + + +

Candidate Details

Title${candidate.title}
Name${candidate.name}
Aadhaar No${candidate.aadhaarNo}
Bar Code${candidate.barCode}
Council${candidate.council}
Course Name${candidate.courseName}
Course State${candidate.courseState}
Date${candidate.date}
Date of birth${candidate.dateOfBirth}
Email${candidate.email}
Exam Body${candidate.examBody}
Fathers Name${candidate.fathersName}
Ree Receipt No${candidate.feeReciptNo}
Final Year RollNo${candidate.finalYearRollNo}
gender${candidate.gender}
Joining Month${candidate.joiningMonth}
Joining Year${candidate.joiningYear}
Mothers Name${candidate.mothersName}
Nurse Registration No${candidate.nurseRegNo}
Nursing Collage${candidate.nursingCollage}
Passing Month${candidate.passingMonth}
Passing Year${candidate.passingYear}
Phone Number${candidate.phoneNumber}
Registration No${candidate.registrationNo}
Registration Type${candidate.registrationType}
+
+ + + + +
+ +
+
+ + diff --git a/java/claim/src/main/resources/templates/student-foreign-pending-item-mail.ftl b/java/claim/src/main/resources/templates/student-foreign-pending-item-mail.ftl new file mode 100644 index 000000000..2ad519b22 --- /dev/null +++ b/java/claim/src/main/resources/templates/student-foreign-pending-item-mail.ftl @@ -0,0 +1,49 @@ + + + + + + +

Hi ${regulatorName}

+ +

Pending action item for student foreign verification. Following candidate has applied for certificate.

+ +

Candidate list:

+

+ + + + + + + + + + <#list candidates as candidate > + + + + + + + + + +
NameCred TypeReference NumberRegistration NumberEmailVerify Link
${candidate.name} ${candidate.credType}${candidate.refNo}${candidate.registrationNumber}${candidate.emailAddress}Verify Candidate
+

+ +
Please follow up to respected entity
+ +

Thank you,

+

< Registration Credential Issuing Authority >

+ + diff --git a/java/claim/src/main/resources/templates/student-from-outside-pending-item-mail.ftl b/java/claim/src/main/resources/templates/student-from-outside-pending-item-mail.ftl new file mode 100644 index 000000000..a55e6874e --- /dev/null +++ b/java/claim/src/main/resources/templates/student-from-outside-pending-item-mail.ftl @@ -0,0 +1,49 @@ + + + + + + +

Hi ${regulatorName}

+ +

Pending action item for student from outside UP. Following candidate has applied for registration certificate.

+ +

Candidate list:

+

+ + + + + + + + + + <#list candidates as candidate > + + + + + + + + + +
NameCred TypeRegistration TypeNurse Registration NumberEmailVerify Link
${candidate.name} ${candidate.credType}${candidate.registrationType}${candidate.nurseRegNo}${candidate.emailAddress}Verify Candidate
+

+ +
Please follow up to respected entity
+ +

Thank you,

+

< Registration Credential Issuing Authority >

+ + diff --git a/java/claim/src/main/resources/templates/student-from-up-pending-item-mail.ftl b/java/claim/src/main/resources/templates/student-from-up-pending-item-mail.ftl new file mode 100644 index 000000000..be5e03929 --- /dev/null +++ b/java/claim/src/main/resources/templates/student-from-up-pending-item-mail.ftl @@ -0,0 +1,47 @@ + + + + + + +

Hi ${regulatorName}

+ +

Following candidate has applied for certificate.

+ +

Candidate list:

+

+ + + + + + + + + <#list candidates as candidate > + + + + + + + + +
NameCred TypeCourse NameEmailExam Body
${candidate.name} ${candidate.credType}${candidate.courseName}${candidate.courseName}${candidate.examBody}
+

+ +
your response awaited
+ +

Thank you,

+

< Registration Credential Issuing Authority >

+ + diff --git a/java/claim/src/main/resources/templates/student-good-standing-pending-item-mail.ftl b/java/claim/src/main/resources/templates/student-good-standing-pending-item-mail.ftl new file mode 100644 index 000000000..4c6ffc996 --- /dev/null +++ b/java/claim/src/main/resources/templates/student-good-standing-pending-item-mail.ftl @@ -0,0 +1,49 @@ + + + + + + +

Hi ${regulatorName}

+ +

Following candidate has applied for registration certificate from your institution as claimed by candidate.

+ +

Candidate list:

+

+ + + + + + + + + + <#list candidates as candidate > + + + + + + + + + +
NameCred TypeReference NumberRegistration NumberEmailVerify Link
${candidate.name} ${candidate.credType}${candidate.refNo}${candidate.registrationNumber}${candidate.emailAddress}Verify Candidate
+

+ +
your response awaited
+ +

Thank you,

+

< Registration Credential Issuing Authority >

+ + diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index 31cdf171b..ff0310f76 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -1464,6 +1464,32 @@ public ResponseEntity sendPendingForeignItemMail(@PathVariable String en return new ResponseEntity<>(response, HttpStatus.OK); } + @RequestMapping(value = "/api/v1/{entityName}/sendEcPendingItemMail", method = RequestMethod.POST) + public ResponseEntity sendEcPendingItemMail(@PathVariable String entityName, + @RequestBody ManualPendingMailDTO pendingMailDTO, + HttpServletRequest request) { + + ResponseParams responseParams = new ResponseParams(); + Response response = new Response(Response.API_ID.SEND, "OK", responseParams); + + try { + registryHelper.authorizeInviteEntity(request, entityName); + + String mailStatus = claimRequestClient.sendEcPendingItemMail(pendingMailDTO); + + response.setResult(mailStatus); + responseParams.setStatus(Response.Status.SUCCESSFUL); + + } catch (Exception exception) { + logger.error("Exception : {}", exception.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(exception.getMessage()); + return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); + } + + return new ResponseEntity<>(response, HttpStatus.OK); + } + @RequestMapping(value = "/api/v1/category/{entityName}/{category}", method = RequestMethod.GET) public ResponseEntity getCourseName(@PathVariable String entityName, @PathVariable String category,HttpServletRequest request) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/ManualPendingMailDTO.java b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/ManualPendingMailDTO.java index fcb67e61a..38953aa73 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/ManualPendingMailDTO.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/model/dto/ManualPendingMailDTO.java @@ -8,8 +8,17 @@ @AllArgsConstructor @NoArgsConstructor public class ManualPendingMailDTO { + private String outsideEntityMailId; private String name; - private String emailAddress; + private String email; private String council; - private String itemName; + private String gender; + private String examBody; + private String diplomaNumber; + private String nursingCollage; + private String docProof; + private String courseState; + private String courseCouncil; + private String country; + private String state; } diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index db56cc537..7495dc1f9 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -51,6 +51,7 @@ public class ClaimRequestClient { private static String URL_APPENDER = "/"; private static final String MAIL_SEND_PENDING_FOREIGN_ITEM_URL = "/api/v1/sendPendingForeignItemMail/"; + private static final String MAIL_SEND_EC_PENDING_ITEM_URL = "/api/v1/sendEcPendingItemMail/"; ClaimRequestClient(@Value("${claims.url}") String claimRequestUrl, RestTemplate restTemplate) { this.claimRequestUrl = claimRequestUrl; @@ -262,6 +263,14 @@ public String sendPendingForeignItemMail(String claimId) { return "Failed to send mail to foreign pending item - invalid claim id"; } + public String sendEcPendingItemMail(ManualPendingMailDTO pendingMailDTO) { + String mailStatus = restTemplate.postForObject( + claimRequestUrl + MAIL_SEND_EC_PENDING_ITEM_URL, pendingMailDTO, String.class); + + logger.info("Pending item mail status: " + mailStatus); + return mailStatus; + } + public List getCourseCategory(String category) { String requestUrl = claimRequestUrl + GET_COURSE_CATEGORY; MultiValueMap queryParams = new LinkedMultiValueMap<>(); From cf7d3a4ab03181dec7f42ac269ea41dc851732ff Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 29 Aug 2023 13:10:21 +0530 Subject: [PATCH 41/43] notifications setting --- .../resources/public/_schemas/studentFromUP.json | 14 ++++++++++++++ services/digilocker-certificate-api/Dockerfile | 2 +- .../digilocker-certificate-api/config/config.go | 6 +++--- .../config/application-default.yml | 2 +- 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index 6cb214371..d680e19c1 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -126,6 +126,20 @@ ], "inviteRoles": ["anonymous"], "roles": ["StudentFromUP","StudentOutsideUP"], + + "notificationTemplates": { + "create": [ + { + "subject": "Credential Created from schema", + "body": "{\"sender\": \"AppName\",\"route\": \"4\",\"country\": \"91\",\"unicode\": 1,\"sms\": [{ \"message\": \"{{name}}, Your {{entityType}} credential has been created\", \"to\": [ \"{{contact}}]\" ] \n }],\n ", + "invite": ": [],\n ", + "update": ": [],\n ", + "delete": ": [],\n ", + "revoke": ": []\n }\n}" + } + ] + }, + "attestationPolicies": [ { "name": "studentVerification", diff --git a/services/digilocker-certificate-api/Dockerfile b/services/digilocker-certificate-api/Dockerfile index 3c93cf8c0..929f3788e 100644 --- a/services/digilocker-certificate-api/Dockerfile +++ b/services/digilocker-certificate-api/Dockerfile @@ -7,7 +7,7 @@ ENV GO111MODULE=on WORKDIR $GOPATH/src/packages/digilocker-certificate-api/ COPY . . RUN go get -d -v -RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o /go/main . +RUN CGO_ENABLED=0 GOOS=windows go build -a -installsuffix cgo -o /go/main . ############################ # STEP 2 build a small image diff --git a/services/digilocker-certificate-api/config/config.go b/services/digilocker-certificate-api/config/config.go index b99b891be..5024d2297 100644 --- a/services/digilocker-certificate-api/config/config.go +++ b/services/digilocker-certificate-api/config/config.go @@ -11,14 +11,14 @@ import ( var Config = struct { Keycloak struct { - TokenURL string `env:"KEYCLOAK_TOKEN_URL" default:"http://keycloak:8080/auth/realms/sunbird-rc/protocol/openid-connect/token"` + TokenURL string `env:"KEYCLOAK_TOKEN_URL" default:"http://localhost:8080/auth/realms/sunbird-rc/protocol/openid-connect/token"` ClientId string `env:"KEYCLOAK_CLIENT_ID" default:"admin-api"` ClientSecret string `env:"KEYCLOAK_CLIENT_SECRET" default:"2b65f70c-bd02-4d5c-95d9-5341225aa849"` } Digilocker struct { - IDPrefix string `env:"DIGILOCKER_DOC_ID_PREFIX" default:"dev.sunbirdrc.vc"` + IDPrefix string `env:"DIGILOCKER_DOC_ID_PREFIX" default:"org.upsmfac"` AuthKeyName string `env:"DIGILOCKER_AUTH_KEYNAME" default:"x-digilocker-hmac"` - AuthHMACKey string `env:"DIGILOCKER_HMAC_AUTHKEY" default:"***"` + AuthHMACKey string `env:"DIGILOCKER_HMAC_AUTHKEY" default:"84600d73-e618-4c80-a347-6b51147103ee"` } Registry struct { URL string `env:"REGISTRY_URL" default:"https://localhost:8081/"` diff --git a/services/notification-service/config/application-default.yml b/services/notification-service/config/application-default.yml index 929969a37..a92ff9f90 100644 --- a/services/notification-service/config/application-default.yml +++ b/services/notification-service/config/application-default.yml @@ -12,7 +12,7 @@ smsapi: emailsmtp: fromAddress: upsmf.otp@upsmfac.org - password: + password: OTP22023## enable: true flagr: From 487997a573c686be7928d6baa12b8ff5f3b6fd82 Mon Sep 17 00:00:00 2001 From: Pawan k <128481755+kumarpawantarento@users.noreply.github.com> Date: Tue, 29 Aug 2023 18:23:54 +0530 Subject: [PATCH 42/43] notification change --- .../claim/controller/CoursesController.java | 17 ++++++-- .../claim/repository/CoursesRepository.java | 2 +- .../claim/service/CoursesService.java | 5 ++- .../controller/RegistryEntityController.java | 39 +++++++++++++++++-- .../registry/util/ClaimRequestClient.java | 22 +++++++++-- 5 files changed, 72 insertions(+), 13 deletions(-) diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java index 377fb1d25..860fae147 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/controller/CoursesController.java @@ -6,6 +6,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; +import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -20,12 +21,22 @@ public CoursesController(CoursesService coursesService) { this.coursesService = coursesService; } - @GetMapping("/") + @GetMapping("/all") public ResponseEntity> getAllCourses() { List courses = coursesService.getAllCourses(); return ResponseEntity.ok(courses); } + @GetMapping("/") + public ResponseEntity> getAllCourseName() { + List courses = coursesService.getAllCourses(); + List courseName = new ArrayList<>(); + for (Courses course:courses) { + courseName.add(course.getCourseName()); + } + return ResponseEntity.ok(courseName); + } + @GetMapping("/{id}") public ResponseEntity getCourseById(@PathVariable Long id) { Optional course = coursesService.getCourseById(id); @@ -54,10 +65,10 @@ public ResponseEntity> getCourseByCategory(@RequestParam(value = "c return ResponseEntity.ok(course); } - @GetMapping("/course-short-name/{courseName}") + @GetMapping("/course-template-key/{courseName}") public ResponseEntity getCourseShortName(@PathVariable String courseName) { courseName = courseName.replace(" ",""); - String course = coursesService.getCourseShortName(courseName); + String course = coursesService.getCourseTemplateKey(courseName); return ResponseEntity.ok(course); } diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java index 4c5e8c04a..e8cdc481c 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/repository/CoursesRepository.java @@ -14,7 +14,7 @@ public interface CoursesRepository extends JpaRepository { @Query("SELECT c.courseName FROM Courses c WHERE c.category = :value") List findByFieldName(@Param("value") String value); - @Query("SELECT c.shortName FROM Courses c WHERE c.courseName = :value") + @Query("SELECT c.courseNameKey FROM Courses c WHERE c.courseName = :value") String findByCouseName(@Param("value") String value); diff --git a/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java index e1e20c4c3..79393608e 100644 --- a/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java +++ b/java/claim/src/main/java/dev/sunbirdrc/claim/service/CoursesService.java @@ -30,12 +30,13 @@ public Optional getCourseByCourse(String category) { return coursesRepository.findByCategory(category); } + // find Couse Name public List getCourseByCategory(String category) { return coursesRepository.findByFieldName(category); } - //findByCouseName - public String getCourseShortName(String courseName) { + //find TemplateKey + public String getCourseTemplateKey(String courseName) { return coursesRepository.findByCouseName(courseName); } public Courses createCourse(Courses course) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java index d02795728..abb0e3a35 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/controller/RegistryEntityController.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.typesafe.config.Optional; import dev.sunbirdrc.keycloak.OwnerCreationException; import dev.sunbirdrc.pojos.AsyncRequest; import dev.sunbirdrc.pojos.PluginResponseMessage; @@ -579,7 +580,7 @@ public ResponseEntity getEntityType(@PathVariable String entityName, JsonNode node = registryHelper.readEntity(readerUserId, entityName, entityId, false, viewTemplateManager.getViewTemplateById(viewTemplateId), false) .get(entityName); -// JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); + String templateUrlFromRequest = getTemplateUrlFromRequest(request, entityName); String fileName = ""; @@ -981,11 +982,12 @@ public ResponseEntity getAttestationCertificateGCS(HttpServletRequest re String fileName = getFileNameOfCredentials(node); boolean wc = false; JsonNode attestationNode = getAttestationSignedData(attestationId, node); + String templateUrlFromRequest = getTemplateUrlFromRequest(request, entityName); certificate = certificateService.getCertificate(attestationNode, entityName, entityId, request.getHeader(HttpHeaders.ACCEPT), - getTemplateUrlFromRequest(request, entityName), + templateUrlFromRequest, getAttestationNode(attestationId, node), fileName, wc ); @@ -1489,13 +1491,20 @@ public ResponseEntity sendEcPendingItemMail(@PathVariable String entityN @RequestMapping(value = "/api/v1/category/{entityName}/{category}", method = RequestMethod.GET) - public ResponseEntity getCourseName(@PathVariable String entityName, @PathVariable String category,HttpServletRequest request) { + public ResponseEntity getCourseName(@PathVariable String entityName, @Optional @PathVariable String category, HttpServletRequest request) { ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.SEND, "OK", responseParams); try { - List list = claimRequestClient.getCourseCategory(category); + List list = null; + if(category == null || category.equals("")){ + claimRequestClient.getAllCourses(); + } + else{ + list = claimRequestClient.getCourseCategory(category); + } + //Long certNumber = claimRequestClient.getCertificateNumber(); response.setResult(list); responseParams.setStatus(Response.Status.SUCCESSFUL); @@ -1510,6 +1519,28 @@ public ResponseEntity getCourseName(@PathVariable String entityName, @Pa return new ResponseEntity<>(response, HttpStatus.OK); } + + @RequestMapping(value = "/api/v1/allcourse/{entityName}", method = RequestMethod.GET) + public ResponseEntity getAllCourseName(@PathVariable String entityName, HttpServletRequest request) { + + ResponseParams responseParams = new ResponseParams(); + Response response = new Response(Response.API_ID.SEND, "OK", responseParams); + + try { + List list = claimRequestClient.getAllCourses(); + //Long certNumber = claimRequestClient.getCertificateNumber(); + response.setResult(list); + responseParams.setStatus(Response.Status.SUCCESSFUL); + } catch (Exception exception) { + logger.error("Exception : {}", exception.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(exception.getMessage()); + return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); + } + + return new ResponseEntity<>(response, HttpStatus.OK); + } + @RequestMapping(value = "/api/v1/course/{entityName}/certificate-number", method = RequestMethod.GET) public ResponseEntity getCourseCertificateNumber(@PathVariable String entityName,HttpServletRequest request) { diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java index 7495dc1f9..54d1deb85 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/util/ClaimRequestClient.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import dev.sunbirdrc.pojos.dto.ClaimDTO; -import dev.sunbirdrc.registry.controller.RegistryController; import dev.sunbirdrc.registry.dao.Learner; import dev.sunbirdrc.registry.model.dto.*; import lombok.NonNull; @@ -37,7 +36,7 @@ public class ClaimRequestClient { private final RestTemplate restTemplate; private static final String CLAIMS_PATH = "/api/v1/claims"; private static final String FETCH_CLAIMS_PATH = "/api/v1/getClaims"; - + private static final String TEMPLATE_KEY = "/course-template-key/"; private static final String FETCH_CLAIMS_STUDENT_PATH = "/api/v2/getClaims"; private static final String MAIL_SEND_URL = "/api/v1/sendMail"; private static final String BAR_CODE_API = "/api/v1/barcode"; @@ -45,7 +44,9 @@ public class ClaimRequestClient { private static final String GET_CRED_URL = "/api/v1/files/download?"; private static final String GET_COURSE_CATEGORY = "/api/v1/courses/diploma"; - private static final String PDF = ".PDF"; + + private static final String GET_ALL_COURSES = "/api/v1/courses/"; + private static final String PDF = ".pdf"; private static final String GCS_CODE_API = "/api/v1/files/upload"; private static final String CLAIM_MULTI_FILE_UPLOAD = "/api/v1/files/upload/multiple"; private static String URL_APPENDER = "/"; @@ -287,6 +288,21 @@ public List getCourseCategory(String category) { return response.getBody(); } + + public List getAllCourses() { + String requestUrl = claimRequestUrl + GET_ALL_COURSES; + MultiValueMap queryParams = new LinkedMultiValueMap<>(); + // Set request headers if needed + HttpHeaders headers = new HttpHeaders(); + // Add any required headers here + headers.set("accept", "*/*"); + ResponseEntity response = restTemplate.exchange( + requestUrl, HttpMethod.GET, null, List.class, queryParams, headers + ); logger.info("end getCredentials ..."); + return response.getBody(); + } + + ///api/v1/generate-certNumber public Long getCertificateNumber() { From ce6e36a2ef6fb73d597c694708947e2fbad96a72 Mon Sep 17 00:00:00 2001 From: rkrahu Date: Wed, 30 Aug 2023 14:20:26 +0530 Subject: [PATCH 43/43] Send mail notification with default password while calling candidate invite for registration. --- .../registry/service/NotificationHelper.java | 9 +++++- .../src/main/resources/application.yml | 6 +++- .../public/_schemas/studentFromUP.json | 10 ++----- .../pkg/services/mail_service.go | 29 ++++++++++++++----- 4 files changed, 37 insertions(+), 17 deletions(-) diff --git a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NotificationHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NotificationHelper.java index 36fafa781..071fc0eeb 100644 --- a/java/registry/src/main/java/dev/sunbirdrc/registry/service/NotificationHelper.java +++ b/java/registry/src/main/java/dev/sunbirdrc/registry/service/NotificationHelper.java @@ -33,6 +33,12 @@ public class NotificationHelper { private EntityStateHelper entityStateHelper; private RegistryService registryService; private ObjectMapper objectMapper; + @Value("${keycloak-user.default-password}") + private String defaultInvitePassword; + + @Value("${notification.sms.enabled}") + boolean smsEnabled; + @Autowired public NotificationHelper(@Value("${notification.service.enabled}") boolean notificationEnabled, IDefinitionsManager definitionsManager, EntityStateHelper entityStateHelper, RegistryService registryService, ObjectMapper objectMapper) { this.notificationEnabled = notificationEnabled; @@ -50,6 +56,7 @@ public void sendNotification(JsonNode inputJson, String operationType) throws Ex List templates = getNotificationTemplate(entityType, operationType); Map objectNodeMap = (Map) JSONUtil.convertJsonNodeToMap(inputJson).get(entityType); objectNodeMap.put("entityType", entityType); + objectNodeMap.put("defaultInvitePassword", defaultInvitePassword); for(NotificationTemplate template: templates) { String bodyTemplate = template.getBody(); String subjectTemplate = template.getSubject(); @@ -65,7 +72,7 @@ private void sendNotificationToOwners(List owners, String operation, for (ObjectNode owner :owners) { String ownerMobile = owner.get(MOBILE).asText(""); String ownerEmail = owner.get(EMAIL).asText(""); - if (!StringUtils.isEmpty(ownerMobile)) { + if (smsEnabled && !StringUtils.isEmpty(ownerMobile)) { registryService.callNotificationActors(operation, String.format("tel:%s", ownerMobile), subject, message); } if (!StringUtils.isEmpty(ownerEmail)) { diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index ad5880967..92edfe569 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -23,12 +23,14 @@ server: notification: service: - enabled: ${notification_enabled:false} + enabled: ${notification_enabled:true} connection_url: ${notification_url:http://localhost:8765/notification-service/v1/notification} health_url: ${notification_url:http://localhost:8765/notification-service/v1/health} async: enabled: ${notification_async_enabled:false} topic: ${notification_topic:notify} + sms: + enabled: false invite: required_validation_enabled: ${invite_required_validation_enabled:true} @@ -346,6 +348,8 @@ view_template: notification: service: enabled: true + sms: + enabled: false perf: monitoring: enabled: false diff --git a/java/registry/src/main/resources/public/_schemas/studentFromUP.json b/java/registry/src/main/resources/public/_schemas/studentFromUP.json index d680e19c1..51191763d 100644 --- a/java/registry/src/main/resources/public/_schemas/studentFromUP.json +++ b/java/registry/src/main/resources/public/_schemas/studentFromUP.json @@ -128,14 +128,10 @@ "roles": ["StudentFromUP","StudentOutsideUP"], "notificationTemplates": { - "create": [ + "invite": [ { - "subject": "Credential Created from schema", - "body": "{\"sender\": \"AppName\",\"route\": \"4\",\"country\": \"91\",\"unicode\": 1,\"sms\": [{ \"message\": \"{{name}}, Your {{entityType}} credential has been created\", \"to\": [ \"{{contact}}]\" ] \n }],\n ", - "invite": ": [],\n ", - "update": ": [],\n ", - "delete": ": [],\n ", - "revoke": ": []\n }\n}" + "subject": "Credential Account Created", + "body": "

Hi {{name}}

Your account has been created. Please update your password.

Your default password is {{defaultInvitePassword}}.

Thank you,

Registration Credential Issuing Authority

" } ] }, diff --git a/services/notification-service/pkg/services/mail_service.go b/services/notification-service/pkg/services/mail_service.go index 46fccfc92..80c88baca 100644 --- a/services/notification-service/pkg/services/mail_service.go +++ b/services/notification-service/pkg/services/mail_service.go @@ -12,14 +12,27 @@ func SendEmail(recipientEmail string, mailSubject string, mailBody string) error from := config.Config.EmailSMTP.FromAddress pass := config.Config.EmailSMTP.Password - msg := "From: " + from + "\n" + - "To: " + recipientEmail + "\n" + - "Subject: " + mailSubject + "\n\n" + - mailBody - - err := smtp.SendMail("smtp.gmail.com:465", - smtp.PlainAuth("", from, pass, "smtp.gmail.com"), - from, []string{recipientEmail}, []byte(msg)) + // msg := "From: " + from + "\n" + + // "To: " + recipientEmail + "\n" + + // "Subject: " + mailSubject + "\n\n" + + // mailBody + + // err := smtp.SendMail("smtp.gmail.com:465", + // smtp.PlainAuth("", from, pass, "smtp.gmail.com"), + // from, []string{recipientEmail}, []byte(msg)) + + + mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n" + subject := "Subject: " + mailSubject+ "!\n" + msg := []byte(subject + mime + "\n" + mailBody) + addr := "smtp.gmail.com:587" + + err := smtp.SendMail(addr, smtp.PlainAuth("", from, pass, "smtp.gmail.com"), + from, []string{recipientEmail}, msg) + + + + log.Infof("Message to send in mail: %s", msg) if err != nil { log.Errorf("smtp error: %s", err)