From 7be608d6573bc0e4acfb83bdc02fece77a96677c Mon Sep 17 00:00:00 2001 From: VenuChoudhary001 Date: Thu, 24 Aug 2023 14:54:23 +0530 Subject: [PATCH 1/9] [+] anchoring schemas to cord network --- java/registry/pom.xml | 2 +- .../controller/RegistryEntityController.java | 34 ++++++++++--- .../registry/helper/RegistryHelper.java | 50 ++++++++++++++++++- 3 files changed, 76 insertions(+), 10 deletions(-) diff --git a/java/registry/pom.xml b/java/registry/pom.xml index 3a1dc4b06..557a17ee2 100644 --- a/java/registry/pom.xml +++ b/java/registry/pom.xml @@ -62,7 +62,7 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter-webflux 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..f9c3b818d 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 @@ -20,7 +20,7 @@ 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.ICertificateService; import dev.sunbirdrc.registry.transform.Configuration; import dev.sunbirdrc.registry.transform.Data; import dev.sunbirdrc.registry.transform.ITransformer; @@ -42,10 +42,10 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; - import javax.servlet.http.HttpServletRequest; import java.lang.reflect.InvocationTargetException; import java.util.*; +import com.fasterxml.jackson.databind.ObjectMapper; import static dev.sunbirdrc.registry.Constants.*; import static dev.sunbirdrc.registry.middleware.util.Constants.ENTITY_TYPE; @@ -89,7 +89,6 @@ public ResponseEntity invite( newRootNode.set(entityName, rootNode); try { checkEntityNameInDefinitionManager(entityName); - registryHelper.authorizeInviteEntity(request, entityName); watch.start(TAG); String entityId = registryHelper.inviteEntity(newRootNode, ""); registryHelper.autoRaiseClaim(entityName, entityId, "", null, newRootNode, dev.sunbirdrc.registry.Constants.USER_ANONYMOUS); @@ -269,7 +268,7 @@ public ResponseEntity putEntity( } } - + @RequestMapping(value = "/api/v1/{entityName}", method = RequestMethod.POST) public ResponseEntity postEntity( @PathVariable String entityName, @@ -278,22 +277,24 @@ public ResponseEntity postEntity( @RequestParam(defaultValue = "sync") String mode, @RequestParam(defaultValue = "${webhook.url}") String callbackUrl, HttpServletRequest request - ) { - + ) throws Exception { logger.info("MODE: {}", asyncRequest.isEnabled()); logger.info("MODE: {}", asyncRequest.getWebhookUrl()); logger.info("Adding entity {}", rootNode); ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.POST, "OK", responseParams); + logger.info("This is inside response {}",response); Map result = new HashMap<>(); ObjectNode newRootNode = objectMapper.createObjectNode(); newRootNode.set(entityName, rootNode); + try { checkEntityNameInDefinitionManager(entityName); String userId = registryHelper.authorizeManageEntity(request, entityName); String label = registryHelper.addEntity(newRootNode, userId); String emailId = registryHelper.fetchEmailIdFromToken(request, entityName); + Map resultMap = new HashMap<>(); if (asyncRequest.isEnabled()) { resultMap.put(TRANSACTION_ID, label); @@ -301,8 +302,27 @@ public ResponseEntity postEntity( registryHelper.autoRaiseClaim(entityName, label, userId, null, newRootNode, emailId); resultMap.put(dbConnectionInfoMgr.getUuidPropertyName(), label); } + + /** Anchoring schema to chain */ + JsonNode np=rootNode.get("schema"); + JsonNode str=new ObjectMapper().readTree(np.asText()); + JsonNode schemaNode=str.get("definitions"); + + JsonNode props=schemaNode.get("Place"); + JsonNode newProps=props.get("properties"); + + JsonNode outputSchema=new ObjectMapper().createObjectNode() + .put("title",str.get("title").asText()) + .put("description",str.get("description").asText()) + .set("properties",props.get("properties")); + + JsonNode finalSchema=new ObjectMapper().createObjectNode() + .set("schema",outputSchema); + registryHelper.anchorSchemaAPI(finalSchema); + + result.put(entityName, resultMap); - response.setResult(result); + response.setResult(result); responseParams.setStatus(Response.Status.SUCCESSFUL); watch.stop("RegistryController.addToExistingEntity"); 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..1c91010d5 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 @@ -59,7 +59,9 @@ import org.springframework.stereotype.Component; import org.springframework.util.DigestUtils; import org.springframework.web.bind.annotation.PathVariable; - +import org.springframework.http.MediaType; +import reactor.core.publisher.Mono; +import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -72,7 +74,7 @@ import static dev.sunbirdrc.registry.exception.ErrorMessages.*; import static dev.sunbirdrc.registry.middleware.util.Constants.*; import static dev.sunbirdrc.registry.middleware.util.OSSystemFields.*; - +import org.springframework.web.reactive.function.client.WebClient; /** * This is helper class, user-service calls this class in-order to access registry functionality */ @@ -191,6 +193,49 @@ public JsonNode removeFormatAttr(JsonNode requestBody) { return requestBody; } + /** + * REUSBALE METHOD FOR POST API CALLS + */ + public void apiHelper(JsonNode obj,String url){ + WebClient.Builder builder = WebClient.builder(); + try{ + Mono responseMono = builder.build() + .post() + .uri(url) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .bodyValue(obj) + .retrieve() + .bodyToMono(JsonNode.class) + .onErrorResume(throwable -> { + throwable.printStackTrace(); + return Mono.empty(); + }); + + JsonNode response = responseMono.block(); + logger.info("RESPONSE {}",response); + }catch(Exception e){ + logger.error("Exception occurred !" , e); + } + } + + /** + * Anchors schema to the CORD CHAIN + */ + public void anchorSchemaAPI(JsonNode obj){ + // apiHelper(obj,"http://172.24.0.1:5106/api/v1/schema"); + apiHelper(obj,"http://localhost:5106/api/v1/schema"); // considering issuer agent running in local + } + + + /** + * Anchors registry to the chain , + * Before calling this api, schema must be created + + */ + public void anchorRegistryAPI(){ + + } /** * calls validation and then persists the record to registry. * @@ -205,6 +250,7 @@ public String addEntity(JsonNode inputJson, String userId) throws Exception { } public String inviteEntity(JsonNode inputJson, String userId) throws Exception { + // System.out.println("lOL"); String entityId = addEntityHandler(inputJson, userId, skipRequiredValidationForInvite, skipSignatureForInvite); notificationHelper.sendNotification(inputJson, INVITE); return entityId; From 88dec0297b134a0abf58bf353b5e94f77b1a293b Mon Sep 17 00:00:00 2001 From: VenuChoudhary001 Date: Thu, 24 Aug 2023 19:34:11 +0530 Subject: [PATCH 2/9] [+/-] refactor: removed extra spaces and debug statements --- .../registry/controller/RegistryEntityController.java | 3 ++- .../java/dev/sunbirdrc/registry/helper/RegistryHelper.java | 1 - 2 files changed, 2 insertions(+), 2 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 70901a857..7726948fb 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 @@ -89,6 +89,7 @@ public ResponseEntity invite( newRootNode.set(entityName, rootNode); try { checkEntityNameInDefinitionManager(entityName); + registryHelper.authorizeInviteEntity(request, entityName); watch.start(TAG); String entityId = registryHelper.inviteEntity(newRootNode, ""); registryHelper.autoRaiseClaim(entityName, entityId, "", null, newRootNode, dev.sunbirdrc.registry.Constants.USER_ANONYMOUS); @@ -283,7 +284,7 @@ public ResponseEntity postEntity( logger.info("Adding entity {}", rootNode); ResponseParams responseParams = new ResponseParams(); Response response = new Response(Response.API_ID.POST, "OK", responseParams); - logger.info("This is inside response {}",response); + Map result = new HashMap<>(); ObjectNode newRootNode = objectMapper.createObjectNode(); newRootNode.set(entityName, rootNode); 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 bb01e6559..8522b4555 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 @@ -251,7 +251,6 @@ public String addEntity(JsonNode inputJson, String userId) throws Exception { } public String inviteEntity(JsonNode inputJson, String userId) throws Exception { - // System.out.println("lOL"); String entityId = addEntityHandler(inputJson, userId, skipRequiredValidationForInvite, skipSignatureForInvite); notificationHelper.sendNotification(inputJson, INVITE); return entityId; From d47a8d5535d5b15586fbeb2dbfd1ab3c007316ba Mon Sep 17 00:00:00 2001 From: VenuChoudhary001 Date: Fri, 1 Sep 2023 11:32:17 +0530 Subject: [PATCH 3/9] [+/-] refactored code --- .../controller/RegistryEntityController.java | 2039 ++++++++++------- .../registry/helper/RegistryHelper.java | 75 +- .../src/main/resources/application.yml | 5 +- 3 files changed, 1279 insertions(+), 840 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 7726948fb..d67b8624f 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 @@ -1,7 +1,11 @@ package dev.sunbirdrc.registry.controller; +import static dev.sunbirdrc.registry.Constants.*; +import static dev.sunbirdrc.registry.middleware.util.Constants.ENTITY_TYPE; + import com.fasterxml.jackson.core.JsonProcessingException; 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; @@ -15,17 +19,21 @@ import dev.sunbirdrc.registry.exception.ErrorMessages; import dev.sunbirdrc.registry.exception.RecordNotFoundException; import dev.sunbirdrc.registry.exception.UnAuthorizedException; +import dev.sunbirdrc.registry.helper.RegistryHelper; import dev.sunbirdrc.registry.middleware.MiddlewareHaltException; 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.service.FileStorageService; -import dev.sunbirdrc.registry.service.ICertificateService; +import dev.sunbirdrc.registry.service.ICertificateService; import dev.sunbirdrc.registry.transform.Configuration; import dev.sunbirdrc.registry.transform.Data; import dev.sunbirdrc.registry.transform.ITransformer; import dev.sunbirdrc.registry.util.ViewTemplateManager; import dev.sunbirdrc.validators.ValidationException; +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import javax.servlet.http.HttpServletRequest; import org.agrona.Strings; import org.apache.commons.lang3.StringUtils; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -42,880 +50,1267 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; -import java.lang.reflect.InvocationTargetException; -import java.util.*; -import com.fasterxml.jackson.databind.ObjectMapper; - -import static dev.sunbirdrc.registry.Constants.*; -import static dev.sunbirdrc.registry.middleware.util.Constants.ENTITY_TYPE; @RestController public class RegistryEntityController extends AbstractController { - private static final String TRANSACTION_ID = "transactionId"; - private static Logger logger = LoggerFactory.getLogger(RegistryEntityController.class); + private static final String TRANSACTION_ID = "transactionId"; + private static Logger logger = LoggerFactory.getLogger( + RegistryEntityController.class + ); - @Autowired - private ICertificateService certificateService; + @Autowired + private ICertificateService certificateService; - @Autowired - private FileStorageService fileStorageService; + @Autowired + private FileStorageService fileStorageService; - @Autowired - private AsyncRequest asyncRequest; + @Autowired + private AsyncRequest asyncRequest; - @Autowired - private ViewTemplateManager viewTemplateManager; + @Autowired + private ViewTemplateManager viewTemplateManager; @Value("${authentication.enabled:true}") boolean securityEnabled; @Value("${certificate.enableExternalTemplates:false}") boolean externalTemplatesEnabled; - - @RequestMapping(value = "/api/v1/{entityName}/invite", method = RequestMethod.POST) - public ResponseEntity invite( - @PathVariable String entityName, - @RequestHeader HttpHeaders header, - @RequestBody JsonNode rootNode, - HttpServletRequest request + @Value("${cord.anchor_to_cord:true}") + boolean anchorToCord; + + @RequestMapping( + value = "/api/v1/{entityName}/invite", + method = RequestMethod.POST + ) + public ResponseEntity invite( + @PathVariable String entityName, + @RequestHeader HttpHeaders header, + @RequestBody JsonNode rootNode, + HttpServletRequest request + ) { + final String TAG = "RegistryController:invite"; + logger.info("Inviting entity {}", rootNode); + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.INVITE, + "OK", + responseParams + ); + Map result = new HashMap<>(); + ObjectNode newRootNode = objectMapper.createObjectNode(); + newRootNode.set(entityName, rootNode); + try { + checkEntityNameInDefinitionManager(entityName); + registryHelper.authorizeInviteEntity(request, entityName); + watch.start(TAG); + String entityId = registryHelper.inviteEntity(newRootNode, ""); + registryHelper.autoRaiseClaim( + entityName, + entityId, + "", + null, + newRootNode, + dev.sunbirdrc.registry.Constants.USER_ANONYMOUS + ); + Map resultMap = new HashMap(); + resultMap.put(dbConnectionInfoMgr.getUuidPropertyName(), entityId); + result.put(entityName, resultMap); + response.setResult(result); + responseParams.setStatus(Response.Status.SUCCESSFUL); + watch.start(TAG); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + response = new Response(Response.API_ID.INVITE, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch ( + MiddlewareHaltException | ValidationException | OwnerCreationException e ) { - final String TAG = "RegistryController:invite"; - logger.info("Inviting entity {}", rootNode); - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.INVITE, "OK", responseParams); - Map result = new HashMap<>(); - ObjectNode newRootNode = objectMapper.createObjectNode(); - newRootNode.set(entityName, rootNode); - try { - checkEntityNameInDefinitionManager(entityName); - registryHelper.authorizeInviteEntity(request, entityName); - watch.start(TAG); - String entityId = registryHelper.inviteEntity(newRootNode, ""); - registryHelper.autoRaiseClaim(entityName, entityId, "", null, newRootNode, dev.sunbirdrc.registry.Constants.USER_ANONYMOUS); - Map resultMap = new HashMap(); - resultMap.put(dbConnectionInfoMgr.getUuidPropertyName(), entityId); - result.put(entityName, resultMap); - response.setResult(result); - responseParams.setStatus(Response.Status.SUCCESSFUL); - watch.start(TAG); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(), responseParams); - response = new Response(Response.API_ID.INVITE, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (MiddlewareHaltException | ValidationException | OwnerCreationException e) { - return badRequestException(responseParams, response, e.getMessage()); - } catch (UnAuthorizedException unAuthorizedException) { - return createUnauthorizedExceptionResponse(unAuthorizedException); - } catch (Exception e) { - if (e.getCause() != null && e.getCause().getCause() != null && - e.getCause().getCause() instanceof InvocationTargetException) { - Throwable targetException = ((InvocationTargetException) (e.getCause().getCause())).getTargetException(); - if (targetException instanceof OwnerCreationException) { - return badRequestException(responseParams, response, targetException.getMessage()); - } - } - return internalErrorResponse(responseParams, response, e); + return badRequestException(responseParams, response, e.getMessage()); + } catch (UnAuthorizedException unAuthorizedException) { + return createUnauthorizedExceptionResponse(unAuthorizedException); + } catch (Exception e) { + if ( + e.getCause() != null && + e.getCause().getCause() != null && + e.getCause().getCause() instanceof InvocationTargetException + ) { + Throwable targetException = + ( + (InvocationTargetException) (e.getCause().getCause()) + ).getTargetException(); + if (targetException instanceof OwnerCreationException) { + return badRequestException( + responseParams, + response, + targetException.getMessage() + ); } + } + return internalErrorResponse(responseParams, response, e); } - - @NotNull - private void createSchemaNotFoundResponse(String errorMessage, ResponseParams responseParams) { - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(errorMessage); + } + + @NotNull + private void createSchemaNotFoundResponse( + String errorMessage, + ResponseParams responseParams + ) { + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(errorMessage); + } + + private void checkEntityNameInDefinitionManager(String entityName) + throws RecordNotFoundException { + if (definitionsManager.getDefinition(entityName) == null) { + String errorMessage = String.format( + ErrorMessages.NOT_PART_OF_THE_SYSTEM_EXCEPTION, + entityName + ); + throw new RecordNotFoundException(errorMessage); } - - private void checkEntityNameInDefinitionManager(String entityName) throws RecordNotFoundException { - if (definitionsManager.getDefinition(entityName) == null) { - String errorMessage = String.format(ErrorMessages.NOT_PART_OF_THE_SYSTEM_EXCEPTION, entityName); - throw new RecordNotFoundException(errorMessage); - } + } + + @RequestMapping( + value = "/api/v1/{entityName}/{entityId}", + method = RequestMethod.DELETE + ) + public ResponseEntity deleteEntity( + @PathVariable String entityName, + @PathVariable String entityId, + @RequestHeader HttpHeaders header, + HttpServletRequest request + ) { + String userId = USER_ANONYMOUS; + logger.info("Deleting entityType {} with Id {}", entityName, entityId); + if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { + try { + userId = registryHelper.authorize(entityName, entityId, request); + } catch (Exception e) { + return createUnauthorizedExceptionResponse(e); + } } - - @RequestMapping(value = "/api/v1/{entityName}/{entityId}", method = RequestMethod.DELETE) - public ResponseEntity deleteEntity( - @PathVariable String entityName, - @PathVariable String entityId, - @RequestHeader HttpHeaders header, - HttpServletRequest request - ) { - - String userId = USER_ANONYMOUS; - logger.info("Deleting entityType {} with Id {}", entityName, entityId); - if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { - try { - - userId = registryHelper.authorize(entityName, entityId, request); - } catch (Exception e) { - return createUnauthorizedExceptionResponse(e); - } - } - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.DELETE, "OK", responseParams); - try { - checkEntityNameInDefinitionManager(entityName); - String tag = "RegistryController.delete " + entityName; - watch.start(tag); - Vertex deletedEntity = registryHelper.deleteEntity(entityName, entityId, userId); - if (deletedEntity != null && deletedEntity.keys().contains(OSSystemFields._osSignedData.name())) { - registryHelper.revokeExistingCredentials(entityName, entityId, userId, deletedEntity.value(OSSystemFields._osSignedData.name())); - } - responseParams.setErrmsg(""); - responseParams.setStatus(Response.Status.SUCCESSFUL); - watch.stop(tag); - return new ResponseEntity<>(response, HttpStatus.OK); - - } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(), responseParams); - response = new Response(Response.API_ID.DELETE, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (Exception e) { - logger.error("RegistryController: Exception while Deleting entity", e); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(e.getMessage()); - return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); - - } + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.DELETE, + "OK", + responseParams + ); + try { + checkEntityNameInDefinitionManager(entityName); + String tag = "RegistryController.delete " + entityName; + watch.start(tag); + Vertex deletedEntity = registryHelper.deleteEntity( + entityName, + entityId, + userId + ); + if ( + deletedEntity != null && + deletedEntity.keys().contains(OSSystemFields._osSignedData.name()) + ) { + registryHelper.revokeExistingCredentials( + entityName, + entityId, + userId, + deletedEntity.value(OSSystemFields._osSignedData.name()) + ); + } + responseParams.setErrmsg(""); + responseParams.setStatus(Response.Status.SUCCESSFUL); + watch.stop(tag); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + response = new Response(Response.API_ID.DELETE, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + logger.error("RegistryController: Exception while Deleting entity", e); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } - - @RequestMapping(value = "/api/v1/{entityName}/search", method = RequestMethod.POST) - public ResponseEntity searchEntity(@PathVariable String entityName, @RequestHeader HttpHeaders header, @RequestBody ObjectNode searchNode) { - - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.SEARCH, "OK", responseParams); - - try { - watch.start("RegistryController.searchEntity"); - ArrayNode entity = JsonNodeFactory.instance.arrayNode(); - entity.add(entityName); - searchNode.set(ENTITY_TYPE, entity); - checkEntityNameInDefinitionManager(entityName); - if (definitionsManager.getDefinition(entityName).getOsSchemaConfiguration().getEnableSearch()) { - JsonNode result = registryHelper.searchEntity(searchNode); - watch.stop("RegistryController.searchEntity"); - return new ResponseEntity<>(result.get(entityName), HttpStatus.OK); - } else { - watch.stop("RegistryController.searchEntity"); - logger.error("Searching on entity {} not allowed", entityName); - response.setResult(""); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(String.format("Searching on entity %s not allowed", entityName)); - } - } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(), responseParams); - response = new Response(Response.API_ID.SEARCH, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (Exception e) { - logger.error("Exception in controller while searching entities !", e); - response.setResult(""); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(e.getMessage()); - } - return new ResponseEntity<>(response, HttpStatus.OK); + } + + @RequestMapping( + value = "/api/v1/{entityName}/search", + method = RequestMethod.POST + ) + public ResponseEntity searchEntity( + @PathVariable String entityName, + @RequestHeader HttpHeaders header, + @RequestBody ObjectNode searchNode + ) { + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.SEARCH, + "OK", + responseParams + ); + + try { + watch.start("RegistryController.searchEntity"); + ArrayNode entity = JsonNodeFactory.instance.arrayNode(); + entity.add(entityName); + searchNode.set(ENTITY_TYPE, entity); + checkEntityNameInDefinitionManager(entityName); + if ( + definitionsManager + .getDefinition(entityName) + .getOsSchemaConfiguration() + .getEnableSearch() + ) { + JsonNode result = registryHelper.searchEntity(searchNode); + watch.stop("RegistryController.searchEntity"); + return new ResponseEntity<>(result.get(entityName), HttpStatus.OK); + } else { + watch.stop("RegistryController.searchEntity"); + logger.error("Searching on entity {} not allowed", entityName); + response.setResult(""); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg( + String.format("Searching on entity %s not allowed", entityName) + ); + } + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + response = new Response(Response.API_ID.SEARCH, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + logger.error("Exception in controller while searching entities !", e); + response.setResult(""); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(e.getMessage()); } - - @RequestMapping(value = "/api/v1/{entityName}/{entityId}", method = RequestMethod.PUT) - public ResponseEntity putEntity( - @PathVariable String entityName, - @PathVariable String entityId, - @RequestBody JsonNode rootNode, - HttpServletRequest request) { - - logger.info("Updating entityType {} request body {}", entityName, rootNode); - String userId = USER_ANONYMOUS; - if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { - try { - - userId = registryHelper.authorize(entityName, entityId, request); - } catch (Exception e) { - return createUnauthorizedExceptionResponse(e); - } - } - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.UPDATE, "OK", responseParams); - ((ObjectNode) rootNode).put(uuidPropertyName, entityId); - ObjectNode newRootNode = objectMapper.createObjectNode(); - newRootNode.set(entityName, rootNode); - - try { - checkEntityNameInDefinitionManager(entityName); - String tag = "RegistryController.update " + entityName; - watch.start(tag); - JsonNode existingNode = registryHelper.readEntity(newRootNode, userId); - String emailId = registryHelper.fetchEmailIdFromToken(request, entityName); - registryHelper.updateEntityAndState(existingNode, newRootNode, userId); - if (existingNode.get(entityName).has(OSSystemFields._osSignedData.name())) { - registryHelper.revokeExistingCredentials(entityName, entityId, userId, - existingNode.get(entityName).get(OSSystemFields._osSignedData.name()).asText("")); - } - registryHelper.invalidateAttestation(entityName, entityId, userId, null); - registryHelper.autoRaiseClaim(entityName, entityId, userId, existingNode, newRootNode, emailId); - responseParams.setErrmsg(""); - responseParams.setStatus(Response.Status.SUCCESSFUL); - watch.stop(tag); - - return new ResponseEntity<>(response, HttpStatus.OK); - - } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(), responseParams); - response = new Response(Response.API_ID.PUT, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (Exception e) { - logger.error("RegistryController: Exception while updating entity (without id)!", e); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(e.getMessage()); - return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); - } + return new ResponseEntity<>(response, HttpStatus.OK); + } + + @RequestMapping( + value = "/api/v1/{entityName}/{entityId}", + method = RequestMethod.PUT + ) + public ResponseEntity putEntity( + @PathVariable String entityName, + @PathVariable String entityId, + @RequestBody JsonNode rootNode, + HttpServletRequest request + ) { + logger.info("Updating entityType {} request body {}", entityName, rootNode); + String userId = USER_ANONYMOUS; + if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { + try { + userId = registryHelper.authorize(entityName, entityId, request); + } catch (Exception e) { + return createUnauthorizedExceptionResponse(e); + } } - - - @RequestMapping(value = "/api/v1/{entityName}", method = RequestMethod.POST) - public ResponseEntity postEntity( - @PathVariable String entityName, - @RequestHeader HttpHeaders header, - @RequestBody JsonNode rootNode, - @RequestParam(defaultValue = "sync") String mode, - @RequestParam(defaultValue = "${webhook.url}") String callbackUrl, - HttpServletRequest request - ) throws Exception { - logger.info("MODE: {}", asyncRequest.isEnabled()); - logger.info("MODE: {}", asyncRequest.getWebhookUrl()); - logger.info("Adding entity {}", rootNode); - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.POST, "OK", responseParams); - - Map result = new HashMap<>(); - ObjectNode newRootNode = objectMapper.createObjectNode(); + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.UPDATE, + "OK", + responseParams + ); + ((ObjectNode) rootNode).put(uuidPropertyName, entityId); + ObjectNode newRootNode = objectMapper.createObjectNode(); + newRootNode.set(entityName, rootNode); + + try { + checkEntityNameInDefinitionManager(entityName); + String tag = "RegistryController.update " + entityName; + watch.start(tag); + JsonNode existingNode = registryHelper.readEntity(newRootNode, userId); + String emailId = registryHelper.fetchEmailIdFromToken( + request, + entityName + ); + registryHelper.updateEntityAndState(existingNode, newRootNode, userId); + if ( + existingNode.get(entityName).has(OSSystemFields._osSignedData.name()) + ) { + registryHelper.revokeExistingCredentials( + entityName, + entityId, + userId, + existingNode + .get(entityName) + .get(OSSystemFields._osSignedData.name()) + .asText("") + ); + } + registryHelper.invalidateAttestation(entityName, entityId, userId, null); + registryHelper.autoRaiseClaim( + entityName, + entityId, + userId, + existingNode, + newRootNode, + emailId + ); + responseParams.setErrmsg(""); + responseParams.setStatus(Response.Status.SUCCESSFUL); + watch.stop(tag); + + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + response = new Response(Response.API_ID.PUT, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + logger.error( + "RegistryController: Exception while updating entity (without id)!", + e + ); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + @RequestMapping(value = "/api/v1/{entityName}", method = RequestMethod.POST) + public ResponseEntity postEntity( + @PathVariable String entityName, + @RequestHeader HttpHeaders header, + @RequestBody JsonNode rootNode, + @RequestParam(defaultValue = "sync") String mode, + @RequestParam(defaultValue = "${webhook.url}") String callbackUrl, + HttpServletRequest request + ) throws Exception { + logger.info("MODE: {}", asyncRequest.isEnabled()); + logger.info("MODE: {}", asyncRequest.getWebhookUrl()); + logger.info("Adding entity {}", rootNode); + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.POST, + "OK", + responseParams + ); + ObjectMapper objectMapper = new ObjectMapper(); + Map result = new HashMap<>(); + ObjectNode newRootNode = objectMapper.createObjectNode(); + + if (anchorToCord) { + if("Schema".equals(entityName)){ + JsonNode getRootNode=registryHelper.anchorToCord(rootNode); + newRootNode.set(entityName, getRootNode); + } + }else{ newRootNode.set(entityName, rootNode); - try { - checkEntityNameInDefinitionManager(entityName); - String userId = registryHelper.authorizeManageEntity(request, entityName); - String label = registryHelper.addEntity(newRootNode, userId); - String emailId = registryHelper.fetchEmailIdFromToken(request, entityName); - - Map resultMap = new HashMap<>(); - if (asyncRequest.isEnabled()) { - resultMap.put(TRANSACTION_ID, label); - } else { - registryHelper.autoRaiseClaim(entityName, label, userId, null, newRootNode, emailId); - resultMap.put(dbConnectionInfoMgr.getUuidPropertyName(), label); - } - /** Anchoring schema to chain */ - JsonNode np=rootNode.get("schema"); - JsonNode str=new ObjectMapper().readTree(np.asText()); - JsonNode schemaNode=str.get("definitions"); - - JsonNode props=schemaNode.get("Place"); - JsonNode newProps=props.get("properties"); - - JsonNode outputSchema=new ObjectMapper().createObjectNode() - .put("title",str.get("title").asText()) - .put("description",str.get("description").asText()) - .set("properties",props.get("properties")); - - JsonNode finalSchema=new ObjectMapper().createObjectNode() - .set("schema",outputSchema); - registryHelper.anchorSchemaAPI(finalSchema); - - - result.put(entityName, resultMap); - response.setResult(result); - responseParams.setStatus(Response.Status.SUCCESSFUL); - watch.stop("RegistryController.addToExistingEntity"); - - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(), responseParams); - response = new Response(Response.API_ID.POST, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (MiddlewareHaltException e) { - logger.info("Error in validating the request"); - return badRequestException(responseParams, response, e.getMessage()); - } catch (Exception e) { - logger.error("Exception in controller while adding entity !", e); - response.setResult(result); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(e.getMessage()); - return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); - } } - - - @RequestMapping(value = "/api/v1/{entityName}/{entityId}/**", method = RequestMethod.PUT) - public ResponseEntity updatePropertyOfTheEntity( - HttpServletRequest request, - @PathVariable String entityName, - @PathVariable String entityId, - @RequestBody JsonNode requestBody - - ) { - String userId = USER_ANONYMOUS; - if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { - try { - userId = registryHelper.authorize(entityName, entityId, request); - } catch (Exception e) { - return createUnauthorizedExceptionResponse(e); - } - } - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.UPDATE, "OK", responseParams); - - try { - checkEntityNameInDefinitionManager(entityName); - String tag = "RegistryController.update " + entityName; - watch.start(tag); - requestBody = registryHelper.removeFormatAttr(requestBody); - JsonNode existingNode = registryHelper.readEntity(userId, entityName, entityId, false, null, false); - registryHelper.updateEntityProperty(entityName, entityId, requestBody, request, existingNode); - if (existingNode.get(entityName).has(OSSystemFields._osSignedData.name())) { - registryHelper.revokeExistingCredentials(entityName, entityId, userId, - existingNode.get(entityName).get(OSSystemFields._osSignedData.name()).asText("")); - } - responseParams.setErrmsg(""); - responseParams.setStatus(Response.Status.SUCCESSFUL); - registryHelper.invalidateAttestation(entityName, entityId, userId, registryHelper.getPropertyToUpdate(request, entityId)); - watch.stop(tag); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(), responseParams); - response = new Response(Response.API_ID.PUT, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (Exception e) { - responseParams.setErrmsg(e.getMessage()); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } + logger.info("NEW NODE : {}",newRootNode); + + try { + checkEntityNameInDefinitionManager(entityName); + String userId = registryHelper.authorizeManageEntity(request, entityName); + String label = registryHelper.addEntity(newRootNode, userId); + String emailId = registryHelper.fetchEmailIdFromToken( + request, + entityName + ); + Map resultMap = new HashMap<>(); + if (asyncRequest.isEnabled()) { + resultMap.put(TRANSACTION_ID, label); + } else { + registryHelper.autoRaiseClaim( + entityName, + label, + userId, + null, + newRootNode, + emailId + ); + resultMap.put(dbConnectionInfoMgr.getUuidPropertyName(), label); + } + + result.put(entityName, resultMap); + response.setResult(result); + responseParams.setStatus(Response.Status.SUCCESSFUL); + watch.stop("RegistryController.addToExistingEntity"); + + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + response = new Response(Response.API_ID.POST, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (MiddlewareHaltException e) { + logger.info("Error in validating the request"); + return badRequestException(responseParams, response, e.getMessage()); + } catch (Exception e) { + logger.error("Exception in controller while adding entity !", e); + response.setResult(result); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } - - @RequestMapping(value = "/api/v1/{entityName}/{entityId}/**", method = RequestMethod.POST) - public ResponseEntity addNewPropertyToTheEntity( - HttpServletRequest request, - @PathVariable String entityName, - @PathVariable String entityId, - @RequestHeader HttpHeaders header, - @RequestBody JsonNode requestBody - ) { - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.UPDATE, "OK", responseParams); - try { - checkEntityNameInDefinitionManager(entityName); - registryHelper.authorize(entityName, entityId, request); - } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(), responseParams); - response = new Response(Response.API_ID.POST, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (Exception e) { - return createUnauthorizedExceptionResponse(e); - } - - try { - - String tag = "RegistryController.addNewPropertyToTheEntity " + entityName; - watch.start(tag); - String notes = getNotes(requestBody); - requestBody = registryHelper.removeFormatAttr(requestBody); - registryHelper.addEntityProperty(entityName, entityId, requestBody, request); - responseParams.setErrmsg(""); - responseParams.setStatus(Response.Status.SUCCESSFUL); - watch.stop(tag); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (Exception e) { - responseParams.setErrmsg(e.getMessage()); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } + } + + @RequestMapping( + value = "/api/v1/{entityName}/{entityId}/**", + method = RequestMethod.PUT + ) + public ResponseEntity updatePropertyOfTheEntity( + HttpServletRequest request, + @PathVariable String entityName, + @PathVariable String entityId, + @RequestBody JsonNode requestBody + ) { + String userId = USER_ANONYMOUS; + if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { + try { + userId = registryHelper.authorize(entityName, entityId, request); + } catch (Exception e) { + return createUnauthorizedExceptionResponse(e); + } } - - private String getNotes(JsonNode requestBody) { - String notes = ""; - if (requestBody.has("notes")) { - notes = requestBody.get("notes").asText(); - JSONUtil.removeNodes(requestBody, Collections.singletonList("notes")); - } - return notes; - } - - 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()); - return attestationNode; - } - - @Nullable - private JsonNode getAttestationNode(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; + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.UPDATE, + "OK", + responseParams + ); + + try { + checkEntityNameInDefinitionManager(entityName); + String tag = "RegistryController.update " + entityName; + watch.start(tag); + requestBody = registryHelper.removeFormatAttr(requestBody); + JsonNode existingNode = registryHelper.readEntity( + userId, + entityName, + entityId, + false, + null, + false + ); + registryHelper.updateEntityProperty( + entityName, + entityId, + requestBody, + request, + existingNode + ); + if ( + existingNode.get(entityName).has(OSSystemFields._osSignedData.name()) + ) { + registryHelper.revokeExistingCredentials( + entityName, + entityId, + userId, + existingNode + .get(entityName) + .get(OSSystemFields._osSignedData.name()) + .asText("") + ); + } + responseParams.setErrmsg(""); + responseParams.setStatus(Response.Status.SUCCESSFUL); + registryHelper.invalidateAttestation( + entityName, + entityId, + userId, + registryHelper.getPropertyToUpdate(request, entityId) + ); + watch.stop(tag); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + response = new Response(Response.API_ID.PUT, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + responseParams.setErrmsg(e.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } - - @RequestMapping(value = "/partner/api/v1/{entityName}", method = RequestMethod.GET) - public ResponseEntity getEntityWithConsent( - @PathVariable String entityName, - HttpServletRequest request) { - ResponseParams responseParams = new ResponseParams(); - try { - checkEntityNameInDefinitionManager(entityName); - ArrayList fields = getConsentFields(request); - JsonNode userInfoFromRegistry = registryHelper.getRequestedUserDetails(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); - } + } + + @RequestMapping( + value = "/api/v1/{entityName}/{entityId}/**", + method = RequestMethod.POST + ) + public ResponseEntity addNewPropertyToTheEntity( + HttpServletRequest request, + @PathVariable String entityName, + @PathVariable String entityId, + @RequestHeader HttpHeaders header, + @RequestBody JsonNode requestBody + ) { + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.UPDATE, + "OK", + responseParams + ); + try { + checkEntityNameInDefinitionManager(entityName); + registryHelper.authorize(entityName, entityId, request); + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + response = new Response(Response.API_ID.POST, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + return createUnauthorizedExceptionResponse(e); } - private ObjectNode copyWhiteListedFields(ArrayList fields, JsonNode dataNode) { - ObjectNode node = JsonNodeFactory.instance.objectNode(); - for (String key : fields) { - node.set(key, dataNode.get(key)); - } - return node; + try { + String tag = "RegistryController.addNewPropertyToTheEntity " + entityName; + watch.start(tag); + String notes = getNotes(requestBody); + requestBody = registryHelper.removeFormatAttr(requestBody); + registryHelper.addEntityProperty( + entityName, + entityId, + requestBody, + request + ); + responseParams.setErrmsg(""); + responseParams.setStatus(Response.Status.SUCCESSFUL); + watch.stop(tag); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + responseParams.setErrmsg(e.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } + } - private ArrayList getConsentFields(HttpServletRequest request) { - ArrayList fields = new ArrayList<>(); - KeycloakAuthenticationToken principal = (KeycloakAuthenticationToken) request.getUserPrincipal(); - try { - Map otherClaims = ((KeycloakPrincipal) principal.getPrincipal()).getKeycloakSecurityContext().getToken().getOtherClaims(); - if (otherClaims.keySet().contains(dev.sunbirdrc.registry.Constants.KEY_CONSENT) && otherClaims.get(dev.sunbirdrc.registry.Constants.KEY_CONSENT) instanceof Map) { - Map consentFields = (Map) otherClaims.get(dev.sunbirdrc.registry.Constants.KEY_CONSENT); - for (Object key : consentFields.keySet()) { - fields.add(key.toString()); - } - } - } catch (Exception ex) { - logger.error("Error while extracting other claims", ex); - } - return fields; - } - - @RequestMapping(value = "/api/v1/{entityName}/{entityId}", method = RequestMethod.GET, produces = - {MediaType.APPLICATION_PDF_VALUE, MediaType.TEXT_HTML_VALUE, Constants.SVG_MEDIA_TYPE}) - public ResponseEntity getEntityType(@PathVariable String entityName, - @PathVariable String entityId, - HttpServletRequest request, - @RequestHeader(required = false) String viewTemplateId) { - ResponseParams responseParams = new ResponseParams(); - Response response ; - if (registryHelper.doesEntityOperationRequireAuthorization(entityName) && securityEnabled) { - try { - - registryHelper.authorize(entityName, entityId, request); - } catch (Exception e) { - try { - checkEntityNameInDefinitionManager(entityName); - registryHelper.authorizeAttestor(entityName, request); - } catch (RecordNotFoundException re) { - createSchemaNotFoundResponse(re.getMessage(), responseParams); - response = new Response(Response.API_ID.GET, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (Exception exceptionFromAuthorizeAttestor) { - return new ResponseEntity<>(HttpStatus.FORBIDDEN); - } - } - } - try { - String readerUserId = getUserId(entityName, request); - JsonNode node = registryHelper.readEntity(readerUserId, entityName, entityId, false, - viewTemplateManager.getViewTemplateById(viewTemplateId), false) - .get(entityName); - JsonNode signedNode = objectMapper.readTree(node.get(OSSystemFields._osSignedData.name()).asText()); - return new ResponseEntity<>(certificateService.getCertificate(signedNode, - entityName, - entityId, - request.getHeader(HttpHeaders.ACCEPT), - getTemplateUrlFromRequest(request, entityName), - JSONUtil.removeNodesByPath(node, definitionsManager.getExcludingFieldsForEntity(entityName)) - ), HttpStatus.OK); - } catch (Exception exception) { - exception.printStackTrace(); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); - } + private String getNotes(JsonNode requestBody) { + String notes = ""; + if (requestBody.has("notes")) { + notes = requestBody.get("notes").asText(); + JSONUtil.removeNodes(requestBody, Collections.singletonList("notes")); } - - - private String getTemplateUrlFromRequest(HttpServletRequest request, String entityName) { - 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; - } - - @RequestMapping(value = "/api/v1/{entityName}/{entityId}", method = RequestMethod.GET) - public ResponseEntity getEntity( - @PathVariable String entityName, - @PathVariable String entityId, - @RequestHeader HttpHeaders header, HttpServletRequest request, - @RequestHeader(required = false) String viewTemplateId) { - boolean requireLDResponse = false; - boolean requireVCResponse = false; - for (MediaType t : header.getAccept()) { - if (t.toString().equals(Constants.LD_JSON_MEDIA_TYPE)) { - requireLDResponse = true; - break; - } else if (t.toString().equals(Constants.VC_JSON_MEDIA_TYPE)) { - requireVCResponse = true; - } + return notes; + } + + 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() + ); + return attestationNode; + } + + @Nullable + private JsonNode getAttestationNode(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; + } + + @RequestMapping( + value = "/partner/api/v1/{entityName}", + method = RequestMethod.GET + ) + public ResponseEntity getEntityWithConsent( + @PathVariable String entityName, + HttpServletRequest request + ) { + ResponseParams responseParams = new ResponseParams(); + try { + checkEntityNameInDefinitionManager(entityName); + ArrayList fields = getConsentFields(request); + JsonNode userInfoFromRegistry = registryHelper.getRequestedUserDetails( + 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); + } } - if (registryHelper.doesEntityOperationRequireAuthorization(entityName) && securityEnabled) { - try { - registryHelper.authorize(entityName, entityId, request); - } catch (Exception e) { - try { - registryHelper.authorizeAttestor(entityName, request); - } catch (Exception exceptionFromAuthorizeAttestor) { - return new ResponseEntity<>(HttpStatus.FORBIDDEN); - } - } + } + 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) { + node.set(key, dataNode.get(key)); + } + return node; + } + + private ArrayList getConsentFields(HttpServletRequest request) { + ArrayList fields = new ArrayList<>(); + KeycloakAuthenticationToken principal = (KeycloakAuthenticationToken) request.getUserPrincipal(); + try { + Map otherClaims = + ( + (KeycloakPrincipal) principal.getPrincipal() + ).getKeycloakSecurityContext() + .getToken() + .getOtherClaims(); + if ( + otherClaims + .keySet() + .contains(dev.sunbirdrc.registry.Constants.KEY_CONSENT) && + otherClaims.get( + dev.sunbirdrc.registry.Constants.KEY_CONSENT + ) instanceof Map + ) { + Map consentFields = (Map) otherClaims.get( + dev.sunbirdrc.registry.Constants.KEY_CONSENT + ); + for (Object key : consentFields.keySet()) { + fields.add(key.toString()); } - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.READ, "OK", responseParams); + } + } catch (Exception ex) { + logger.error("Error while extracting other claims", ex); + } + return fields; + } + + @RequestMapping( + value = "/api/v1/{entityName}/{entityId}", + method = RequestMethod.GET, + produces = { + MediaType.APPLICATION_PDF_VALUE, + MediaType.TEXT_HTML_VALUE, + Constants.SVG_MEDIA_TYPE, + } + ) + public ResponseEntity getEntityType( + @PathVariable String entityName, + @PathVariable String entityId, + HttpServletRequest request, + @RequestHeader(required = false) String viewTemplateId + ) { + ResponseParams responseParams = new ResponseParams(); + Response response; + if ( + registryHelper.doesEntityOperationRequireAuthorization(entityName) && + securityEnabled + ) { + try { + registryHelper.authorize(entityName, entityId, request); + } catch (Exception e) { try { - checkEntityNameInDefinitionManager(entityName); - String readerUserId = getUserId(entityName, request); - JsonNode node = getEntityJsonNode(entityName, entityId, requireLDResponse, readerUserId, viewTemplateId); - if (requireLDResponse) { - addJsonLDSpec(node); - } else if (requireVCResponse) { - String vcString = node.get(OSSystemFields._osSignedData.name()).textValue(); - return new ResponseEntity<>(vcString, HttpStatus.OK); - } - return new ResponseEntity<>(node, HttpStatus.OK); - + checkEntityNameInDefinitionManager(entityName); + registryHelper.authorizeAttestor(entityName, request); } catch (RecordNotFoundException re) { - createSchemaNotFoundResponse(re.getMessage(), responseParams); - response = new Response(Response.API_ID.GET, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (Exception e) { - logger.error("Read Api Exception occurred ", e); - responseParams.setErrmsg(e.getMessage()); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + createSchemaNotFoundResponse(re.getMessage(), responseParams); + response = new Response(Response.API_ID.GET, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception exceptionFromAuthorizeAttestor) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); } + } } - - private String getUserId(String entityName, HttpServletRequest request) throws Exception { - return registryHelper.getUserId(request, entityName); + try { + String readerUserId = getUserId(entityName, request); + JsonNode node = registryHelper + .readEntity( + readerUserId, + entityName, + entityId, + false, + viewTemplateManager.getViewTemplateById(viewTemplateId), + false + ) + .get(entityName); + JsonNode signedNode = objectMapper.readTree( + node.get(OSSystemFields._osSignedData.name()).asText() + ); + return new ResponseEntity<>( + certificateService.getCertificate( + signedNode, + entityName, + entityId, + request.getHeader(HttpHeaders.ACCEPT), + getTemplateUrlFromRequest(request, entityName), + JSONUtil.removeNodesByPath( + node, + definitionsManager.getExcludingFieldsForEntity(entityName) + ) + ), + HttpStatus.OK + ); + } catch (Exception exception) { + exception.printStackTrace(); + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - - private void addJsonLDSpec(JsonNode node) { - - } - - private JsonNode getEntityJsonNode(@PathVariable String entityName, @PathVariable String entityId, - boolean requireLDResponse, String userId, String viewTemplateId) throws Exception { - JsonNode resultNode = registryHelper.readEntity(userId, entityName, entityId, false, - viewTemplateManager.getViewTemplateById(viewTemplateId), false); - Data data = new Data<>(resultNode); - Configuration config = configurationHelper.getResponseConfiguration(requireLDResponse); - ITransformer responseTransformer = transformer.getInstance(config); - Data resultContent = responseTransformer.transform(data); - logger.info("ReadEntity,{},{}", entityId, resultContent); - if (!(resultContent.getData() instanceof JsonNode)) { - throw new RuntimeException("Unknown response object " + resultContent); - } - JsonNode node = (JsonNode) resultContent.getData(); - JsonNode entityNode = node.get(entityName); - return entityNode != null ? entityNode : node; + } + + private String getTemplateUrlFromRequest( + HttpServletRequest request, + String entityName + ) { + if ( + externalTemplatesEnabled && + !StringUtils.isEmpty(request.getHeader(Template)) + ) { + return request.getHeader(Template); } - - @RequestMapping(value = "/api/v1/{entityName}", method = RequestMethod.GET) - public ResponseEntity getEntityByToken(@PathVariable String entityName, HttpServletRequest request, - @RequestHeader(required = false) String viewTemplateId) throws RecordNotFoundException { - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.GET, "OK", responseParams); + 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 { - checkEntityNameInDefinitionManager(entityName); - String userId = registryHelper.getUserId(request, entityName); - if (!Strings.isEmpty(userId)) { - JsonNode responseFromDb = registryHelper.searchEntitiesByUserId(entityName, userId, viewTemplateId); - JsonNode entities = responseFromDb.get(entityName); - if (entities.size() > 0) { - return new ResponseEntity<>(entities, HttpStatus.OK); - } else { - responseParams.setErrmsg("No record found"); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } - } else { - responseParams.setErrmsg("User id is empty"); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } - } catch (RecordNotFoundException e) { - createSchemaNotFoundResponse(e.getMessage(),responseParams); - response = new Response(Response.API_ID.GET, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + 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 in controller while searching entities !", e); - response.setResult(""); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(e.getMessage()); - return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED); + logger.error( + "Exception while parsing certificate templates DID urls", + e + ); + return null; } + } } - - //TODO: check the usage and deprecate the api if not used - @GetMapping(value = "/api/v1/{entity}/{entityId}/attestationProperties") - public ResponseEntity getEntityForAttestation( - @PathVariable String entity, - @PathVariable String entityId + return null; + } + + @RequestMapping( + value = "/api/v1/{entityName}/{entityId}", + method = RequestMethod.GET + ) + public ResponseEntity getEntity( + @PathVariable String entityName, + @PathVariable String entityId, + @RequestHeader HttpHeaders header, + HttpServletRequest request, + @RequestHeader(required = false) String viewTemplateId + ) { + boolean requireLDResponse = false; + boolean requireVCResponse = false; + for (MediaType t : header.getAccept()) { + if (t.toString().equals(Constants.LD_JSON_MEDIA_TYPE)) { + requireLDResponse = true; + break; + } else if (t.toString().equals(Constants.VC_JSON_MEDIA_TYPE)) { + requireVCResponse = true; + } + } + if ( + registryHelper.doesEntityOperationRequireAuthorization(entityName) && + securityEnabled ) { - ResponseParams responseParams = new ResponseParams(); + try { + registryHelper.authorize(entityName, entityId, request); + } catch (Exception e) { try { - JsonNode resultNode = registryHelper.readEntity("", entity, entityId, false, null, false); - ObjectNode objectNode = objectMapper.createObjectNode(); - objectNode.set("entity", resultNode.get(entity)); - checkEntityNameInDefinitionManager(entity); - List attestationPolicies = definitionsManager.getDefinition(entity) - .getOsSchemaConfiguration() - .getAttestationPolicies(); - objectNode.set("attestationPolicies", objectMapper.convertValue(attestationPolicies, JsonNode.class)); - return new ResponseEntity<>(objectNode, HttpStatus.OK); - - } catch (RecordNotFoundException re) { - createSchemaNotFoundResponse(re.getMessage(), responseParams); - Response response = new Response(Response.API_ID.GET, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } - catch (Exception e) { - e.printStackTrace(); - return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + registryHelper.authorizeAttestor(entityName, request); + } catch (Exception exceptionFromAuthorizeAttestor) { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); } - + } } - - //TODO: check the usage and deprecate the api if not used - @RequestMapping(value = "/api/v1/{entityName}/{entityId}", method = RequestMethod.PATCH) - public ResponseEntity attestEntity( - @PathVariable String entityName, - @PathVariable String entityId, - @RequestHeader HttpHeaders header, - @RequestBody JsonNode rootNode - ) throws Exception { - ResponseParams responseParams = new ResponseParams(); - try { - checkEntityNameInDefinitionManager(entityName); - } catch (RecordNotFoundException re) { - createSchemaNotFoundResponse(re.getMessage(),responseParams); - Response response = new Response(Response.API_ID.PATCH, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } - - logger.info("Attestation request for {}", rootNode.get("fieldPaths")); - JsonNode nodePath = rootNode.get("jsonPaths"); - if (nodePath instanceof ArrayNode) { - Iterator elements = ((ArrayNode) nodePath).elements(); - ArrayList paths = new ArrayList<>(); - for (Iterator it = elements; it.hasNext(); ) { - JsonNode e = it.next(); - paths.add(e.textValue()); - } - JsonNode node = registryHelper.readEntity("admin", entityName, entityId, false, null, false); - registryHelper.attestEntity(entityName, node, paths.toArray(new String[]{}), "admin"); - } - return null; + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.READ, + "OK", + responseParams + ); + try { + checkEntityNameInDefinitionManager(entityName); + String readerUserId = getUserId(entityName, request); + JsonNode node = getEntityJsonNode( + entityName, + entityId, + requireLDResponse, + readerUserId, + viewTemplateId + ); + if (requireLDResponse) { + addJsonLDSpec(node); + } else if (requireVCResponse) { + String vcString = node + .get(OSSystemFields._osSignedData.name()) + .textValue(); + return new ResponseEntity<>(vcString, HttpStatus.OK); + } + return new ResponseEntity<>(node, HttpStatus.OK); + } catch (RecordNotFoundException re) { + createSchemaNotFoundResponse(re.getMessage(), responseParams); + response = new Response(Response.API_ID.GET, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + logger.error("Read Api Exception occurred ", e); + responseParams.setErrmsg(e.getMessage()); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } - - //TODO: check the usage and deprecate the api if not used - @RequestMapping(value = "/api/v1/system/{property}/{propertyId}", method = RequestMethod.POST) - public ResponseEntity updateProperty( - @PathVariable String property, - @PathVariable String propertyId, - @RequestBody JsonNode requestBody) { - logger.info("Got system request for the property {} {}", property, propertyId); - ((ObjectNode) requestBody).put(uuidPropertyName, propertyId); - ObjectNode newRootNode = objectMapper.createObjectNode(); - - ResponseParams responseParams = new ResponseParams(); - newRootNode.set(property, requestBody); - try { - String response = registryHelper.updateProperty(newRootNode, ""); - responseParams.setStatus(Response.Status.SUCCESSFUL); - responseParams.setResultList(Collections.singletonList(response)); - return new ResponseEntity<>(responseParams, HttpStatus.OK); - } catch (Exception exception) { - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(exception.getMessage()); - exception.printStackTrace(); - return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); - } + } + + private String getUserId(String entityName, HttpServletRequest request) + throws Exception { + return registryHelper.getUserId(request, entityName); + } + + private void addJsonLDSpec(JsonNode node) {} + + private JsonNode getEntityJsonNode( + @PathVariable String entityName, + @PathVariable String entityId, + boolean requireLDResponse, + String userId, + String viewTemplateId + ) throws Exception { + JsonNode resultNode = registryHelper.readEntity( + userId, + entityName, + entityId, + false, + viewTemplateManager.getViewTemplateById(viewTemplateId), + false + ); + Data data = new Data<>(resultNode); + Configuration config = configurationHelper.getResponseConfiguration( + requireLDResponse + ); + ITransformer responseTransformer = transformer.getInstance(config); + Data resultContent = responseTransformer.transform(data); + logger.info("ReadEntity,{},{}", entityId, resultContent); + if (!(resultContent.getData() instanceof JsonNode)) { + throw new RuntimeException("Unknown response object " + resultContent); } - - //TODO: API called by claim-ms, need to be blocked from external access - @RequestMapping(value = "/api/v1/{property}/{propertyId}/attestation/{attestationName}/{attestationId}", method = RequestMethod.PUT) - public ResponseEntity updateAttestationProperty( - @PathVariable String property, - @PathVariable String propertyId, - @PathVariable String attestationName, - @PathVariable String attestationId, - @RequestBody JsonNode requestBody) { - logger.info("Got system request to update attestation property {} {} {} {}", property, propertyId, attestationName, attestationId); - ((ObjectNode) requestBody).put(uuidPropertyName, propertyId); - ObjectNode newRootNode = objectMapper.createObjectNode(); - - ResponseParams responseParams = new ResponseParams(); - newRootNode.set(property, requestBody); - try { - logger.info("updateAttestationProperty: {}", requestBody); - PluginResponseMessage pluginResponseMessage = objectMapper.convertValue(requestBody, PluginResponseMessage.class); - registryHelper.updateState(pluginResponseMessage); - responseParams.setStatus(Response.Status.SUCCESSFUL); - responseParams.setResultList(Collections.singletonList("response")); - return new ResponseEntity<>(responseParams, HttpStatus.OK); - } catch (Exception exception) { - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(exception.getMessage()); - exception.printStackTrace(); - return new ResponseEntity<>(responseParams, HttpStatus.INTERNAL_SERVER_ERROR); + JsonNode node = (JsonNode) resultContent.getData(); + JsonNode entityNode = node.get(entityName); + return entityNode != null ? entityNode : node; + } + + @RequestMapping(value = "/api/v1/{entityName}", method = RequestMethod.GET) + public ResponseEntity getEntityByToken( + @PathVariable String entityName, + HttpServletRequest request, + @RequestHeader(required = false) String viewTemplateId + ) throws RecordNotFoundException { + ResponseParams responseParams = new ResponseParams(); + Response response = new Response(Response.API_ID.GET, "OK", responseParams); + try { + checkEntityNameInDefinitionManager(entityName); + String userId = registryHelper.getUserId(request, entityName); + if (!Strings.isEmpty(userId)) { + JsonNode responseFromDb = registryHelper.searchEntitiesByUserId( + entityName, + userId, + viewTemplateId + ); + JsonNode entities = responseFromDb.get(entityName); + if (entities.size() > 0) { + return new ResponseEntity<>(entities, HttpStatus.OK); + } else { + responseParams.setErrmsg("No record found"); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } + } else { + responseParams.setErrmsg("User id is empty"); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } + } catch (RecordNotFoundException e) { + createSchemaNotFoundResponse(e.getMessage(), responseParams); + response = new Response(Response.API_ID.GET, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + logger.error("Exception in controller while searching entities !", e); + response.setResult(""); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED); } - - @Deprecated - @RequestMapping(value = "/api/v1/{entityName}/sign", method = RequestMethod.GET) - public ResponseEntity getSignedEntityByToken(@PathVariable String entityName, HttpServletRequest request) { - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.SEARCH, "OK", responseParams); - try { - checkEntityNameInDefinitionManager(entityName); - JsonNode result = registryHelper.getRequestedUserDetails(request, entityName); - if (result.get(entityName).size() > 0) { - Object credentialTemplate = definitionsManager.getCredentialTemplate(entityName); - Object signedCredentials = registryHelper.getSignedDoc(result.get(entityName).get(0), credentialTemplate); - return new ResponseEntity<>(signedCredentials, HttpStatus.OK); - } else { - responseParams.setErrmsg("Entity not found"); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } - } catch (RecordNotFoundException re) { - createSchemaNotFoundResponse(re.getMessage(), responseParams); - response = new Response(Response.API_ID.GET, "ERROR", responseParams); - return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); - } catch (Exception e) { - logger.error("Exception in controller while searching entities !", e); - response.setResult(""); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(e.getMessage()); - } - return new ResponseEntity<>(response, HttpStatus.OK); + } + + //TODO: check the usage and deprecate the api if not used + @GetMapping(value = "/api/v1/{entity}/{entityId}/attestationProperties") + public ResponseEntity getEntityForAttestation( + @PathVariable String entity, + @PathVariable String entityId + ) { + ResponseParams responseParams = new ResponseParams(); + try { + JsonNode resultNode = registryHelper.readEntity( + "", + entity, + entityId, + false, + null, + false + ); + ObjectNode objectNode = objectMapper.createObjectNode(); + objectNode.set("entity", resultNode.get(entity)); + checkEntityNameInDefinitionManager(entity); + List attestationPolicies = definitionsManager + .getDefinition(entity) + .getOsSchemaConfiguration() + .getAttestationPolicies(); + objectNode.set( + "attestationPolicies", + objectMapper.convertValue(attestationPolicies, JsonNode.class) + ); + return new ResponseEntity<>(objectNode, HttpStatus.OK); + } catch (RecordNotFoundException re) { + createSchemaNotFoundResponse(re.getMessage(), responseParams); + Response response = new Response( + Response.API_ID.GET, + "ERROR", + responseParams + ); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + e.printStackTrace(); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + //TODO: check the usage and deprecate the api if not used + @RequestMapping( + value = "/api/v1/{entityName}/{entityId}", + method = RequestMethod.PATCH + ) + public ResponseEntity attestEntity( + @PathVariable String entityName, + @PathVariable String entityId, + @RequestHeader HttpHeaders header, + @RequestBody JsonNode rootNode + ) throws Exception { + ResponseParams responseParams = new ResponseParams(); + try { + checkEntityNameInDefinitionManager(entityName); + } catch (RecordNotFoundException re) { + createSchemaNotFoundResponse(re.getMessage(), responseParams); + Response response = new Response( + Response.API_ID.PATCH, + "ERROR", + responseParams + ); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } - @GetMapping(value = "/api/v1/{entityName}/{entityId}/attestation/{attestationName}/{attestationId}", - produces = {MediaType.APPLICATION_PDF_VALUE, MediaType.TEXT_HTML_VALUE, Constants.SVG_MEDIA_TYPE, MediaType.APPLICATION_JSON_VALUE}) - public ResponseEntity getAttestationCertificate(HttpServletRequest request, @PathVariable String entityName, @PathVariable String entityId, - @PathVariable String attestationName, @PathVariable String attestationId) { - ResponseParams responseParams = new ResponseParams(); - try { - checkEntityNameInDefinitionManager(entityName); - String readerUserId = getUserId(entityName, request); - JsonNode node = registryHelper.readEntity(readerUserId, entityName, entityId, false, null, false) - .get(entityName).get(attestationName); - JsonNode attestationNode = getAttestationSignedData(attestationId, node); - return new ResponseEntity<>(certificateService.getCertificate(attestationNode, - entityName, - entityId, - request.getHeader(HttpHeaders.ACCEPT), - getTemplateUrlFromRequest(request, entityName), - getAttestationNode(attestationId, node) - ), 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); - } + logger.info("Attestation request for {}", rootNode.get("fieldPaths")); + JsonNode nodePath = rootNode.get("jsonPaths"); + if (nodePath instanceof ArrayNode) { + Iterator elements = ((ArrayNode) nodePath).elements(); + ArrayList paths = new ArrayList<>(); + for (Iterator it = elements; it.hasNext();) { + JsonNode e = it.next(); + paths.add(e.textValue()); + } + JsonNode node = registryHelper.readEntity( + "admin", + entityName, + entityId, + false, + null, + false + ); + registryHelper.attestEntity( + entityName, + node, + paths.toArray(new String[] {}), + "admin" + ); } - @RequestMapping(value = "/api/v1/{entityName}/{entityId}/revoke", method = RequestMethod.POST) - public ResponseEntity revokeACredential ( - HttpServletRequest request, - @PathVariable String entityName, - @PathVariable String entityId, - @RequestHeader HttpHeaders headers - ){ - String userId = USER_ANONYMOUS; - logger.info("Revoking the entityType {} with {} Id",entityName, entityId); - // Check fot Authorisation - if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { - try { - userId = registryHelper.authorize(entityName, entityId, request); - } catch (Exception e) { - return createUnauthorizedExceptionResponse(e); - } - } - ResponseParams responseParams = new ResponseParams(); - Response response = new Response(Response.API_ID.REVOKE, "OK", responseParams); - try { - String tag = "RegistryController.revokeAnExistingCredential " + entityName; - watch.start(tag); - JsonNode existingEntityNode = getEntityJsonNode(entityName, entityId,false, userId, null); - String signedData = existingEntityNode.get(OSSystemFields._osSignedData.name()).asText(); - if (signedData.equals(new String()) || signedData.equals(null)) { - throw new RecordNotFoundException("Credential is already revoked"); - } - JsonNode revokedEntity = registryHelper.revokeAnEntity( entityName ,entityId, userId, existingEntityNode); - if (revokedEntity != null) { - registryHelper.revokeExistingCredentials(entityName, entityId, userId, signedData); - } - responseParams.setErrmsg(""); - responseParams.setStatus(Response.Status.SUCCESSFUL); - watch.stop(tag); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (Exception e) { - logger.error("Registry Controller: Exception while revoking an entity:", e); - responseParams.setStatus(Response.Status.UNSUCCESSFUL); - responseParams.setErrmsg(e.getMessage()); - return new ResponseEntity<>(response,HttpStatus.INTERNAL_SERVER_ERROR); - } + return null; + } + + //TODO: check the usage and deprecate the api if not used + @RequestMapping( + value = "/api/v1/system/{property}/{propertyId}", + method = RequestMethod.POST + ) + public ResponseEntity updateProperty( + @PathVariable String property, + @PathVariable String propertyId, + @RequestBody JsonNode requestBody + ) { + logger.info( + "Got system request for the property {} {}", + property, + propertyId + ); + ((ObjectNode) requestBody).put(uuidPropertyName, propertyId); + ObjectNode newRootNode = objectMapper.createObjectNode(); + + ResponseParams responseParams = new ResponseParams(); + newRootNode.set(property, requestBody); + try { + String response = registryHelper.updateProperty(newRootNode, ""); + responseParams.setStatus(Response.Status.SUCCESSFUL); + responseParams.setResultList(Collections.singletonList(response)); + return new ResponseEntity<>(responseParams, HttpStatus.OK); + } catch (Exception exception) { + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(exception.getMessage()); + exception.printStackTrace(); + return new ResponseEntity<>( + responseParams, + HttpStatus.INTERNAL_SERVER_ERROR + ); + } + } + + //TODO: API called by claim-ms, need to be blocked from external access + @RequestMapping( + value = "/api/v1/{property}/{propertyId}/attestation/{attestationName}/{attestationId}", + method = RequestMethod.PUT + ) + public ResponseEntity updateAttestationProperty( + @PathVariable String property, + @PathVariable String propertyId, + @PathVariable String attestationName, + @PathVariable String attestationId, + @RequestBody JsonNode requestBody + ) { + logger.info( + "Got system request to update attestation property {} {} {} {}", + property, + propertyId, + attestationName, + attestationId + ); + ((ObjectNode) requestBody).put(uuidPropertyName, propertyId); + ObjectNode newRootNode = objectMapper.createObjectNode(); + + ResponseParams responseParams = new ResponseParams(); + newRootNode.set(property, requestBody); + try { + logger.info("updateAttestationProperty: {}", requestBody); + PluginResponseMessage pluginResponseMessage = objectMapper.convertValue( + requestBody, + PluginResponseMessage.class + ); + registryHelper.updateState(pluginResponseMessage); + responseParams.setStatus(Response.Status.SUCCESSFUL); + responseParams.setResultList(Collections.singletonList("response")); + return new ResponseEntity<>(responseParams, HttpStatus.OK); + } catch (Exception exception) { + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(exception.getMessage()); + exception.printStackTrace(); + return new ResponseEntity<>( + responseParams, + HttpStatus.INTERNAL_SERVER_ERROR + ); + } + } + + @Deprecated + @RequestMapping( + value = "/api/v1/{entityName}/sign", + method = RequestMethod.GET + ) + public ResponseEntity getSignedEntityByToken( + @PathVariable String entityName, + HttpServletRequest request + ) { + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.SEARCH, + "OK", + responseParams + ); + try { + checkEntityNameInDefinitionManager(entityName); + JsonNode result = registryHelper.getRequestedUserDetails( + request, + entityName + ); + if (result.get(entityName).size() > 0) { + Object credentialTemplate = definitionsManager.getCredentialTemplate( + entityName + ); + Object signedCredentials = registryHelper.getSignedDoc( + result.get(entityName).get(0), + credentialTemplate + ); + return new ResponseEntity<>(signedCredentials, HttpStatus.OK); + } else { + responseParams.setErrmsg("Entity not found"); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } + } catch (RecordNotFoundException re) { + createSchemaNotFoundResponse(re.getMessage(), responseParams); + response = new Response(Response.API_ID.GET, "ERROR", responseParams); + return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); + } catch (Exception e) { + logger.error("Exception in controller while searching entities !", e); + response.setResult(""); + responseParams.setStatus(Response.Status.UNSUCCESSFUL); + responseParams.setErrmsg(e.getMessage()); + } + return new ResponseEntity<>(response, HttpStatus.OK); + } + + @GetMapping( + value = "/api/v1/{entityName}/{entityId}/attestation/{attestationName}/{attestationId}", + produces = { + MediaType.APPLICATION_PDF_VALUE, + MediaType.TEXT_HTML_VALUE, + Constants.SVG_MEDIA_TYPE, + MediaType.APPLICATION_JSON_VALUE, + } + ) + public ResponseEntity getAttestationCertificate( + HttpServletRequest request, + @PathVariable String entityName, + @PathVariable String entityId, + @PathVariable String attestationName, + @PathVariable String attestationId + ) { + ResponseParams responseParams = new ResponseParams(); + try { + checkEntityNameInDefinitionManager(entityName); + String readerUserId = getUserId(entityName, request); + JsonNode node = registryHelper + .readEntity(readerUserId, entityName, entityId, false, null, false) + .get(entityName) + .get(attestationName); + JsonNode attestationNode = getAttestationSignedData(attestationId, node); + return new ResponseEntity<>( + certificateService.getCertificate( + attestationNode, + entityName, + entityId, + request.getHeader(HttpHeaders.ACCEPT), + getTemplateUrlFromRequest(request, entityName), + getAttestationNode(attestationId, node) + ), + 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); + } + } + + @RequestMapping( + value = "/api/v1/{entityName}/{entityId}/revoke", + method = RequestMethod.POST + ) + public ResponseEntity revokeACredential( + HttpServletRequest request, + @PathVariable String entityName, + @PathVariable String entityId, + @RequestHeader HttpHeaders headers + ) { + String userId = USER_ANONYMOUS; + logger.info("Revoking the entityType {} with {} Id", entityName, entityId); + // Check fot Authorisation + if (registryHelper.doesEntityOperationRequireAuthorization(entityName)) { + try { + userId = registryHelper.authorize(entityName, entityId, request); + } catch (Exception e) { + return createUnauthorizedExceptionResponse(e); + } + } + ResponseParams responseParams = new ResponseParams(); + Response response = new Response( + Response.API_ID.REVOKE, + "OK", + responseParams + ); + try { + String tag = + "RegistryController.revokeAnExistingCredential " + entityName; + watch.start(tag); + JsonNode existingEntityNode = getEntityJsonNode( + entityName, + entityId, + false, + userId, + null + ); + String signedData = existingEntityNode + .get(OSSystemFields._osSignedData.name()) + .asText(); + if (signedData.equals(new String()) || signedData.equals(null)) { + throw new RecordNotFoundException("Credential is already revoked"); + } + JsonNode revokedEntity = registryHelper.revokeAnEntity( + entityName, + entityId, + userId, + existingEntityNode + ); + if (revokedEntity != null) { + registryHelper.revokeExistingCredentials( + entityName, + entityId, + userId, + signedData + ); + } + responseParams.setErrmsg(""); + responseParams.setStatus(Response.Status.SUCCESSFUL); + watch.stop(tag); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + logger.error( + "Registry Controller: Exception while revoking an entity:", + e + ); + 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/helper/RegistryHelper.java b/java/registry/src/main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java index 8522b4555..556f27880 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,13 +87,15 @@ public class RegistryHelper { private static final String ATTESTATION_RESPONSE = "attestationResponse"; public static String ROLE_ANONYMOUS = "anonymous"; - private static final Logger logger = LoggerFactory.getLogger(RegistryHelper.class); + private static final org.slf4j.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("${cord.schemaURL}") String cord_schema_url; + @Value("${cord.issuer_schema_url:http://172.24.0.1/5106/api/v1/schema}") String cord_schema_url; + @Value("${cord.issuer_registry_url:http://172.24.0.1/5106/api/v1/registry}") String cord_registry_url; + @Autowired private NotificationHelper notificationHelper; @Autowired @@ -193,11 +195,11 @@ public JsonNode removeFormatAttr(JsonNode requestBody) { } return requestBody; } - + /** * REUSBALE METHOD FOR POST API CALLS */ - public void apiHelper(JsonNode obj,String url){ + public JsonNode apiHelper(JsonNode obj,String url) throws Exception{ WebClient.Builder builder = WebClient.builder(); try{ Mono responseMono = builder.build() @@ -214,27 +216,66 @@ public void apiHelper(JsonNode obj,String url){ }); JsonNode response = responseMono.block(); - logger.info("RESPONSE {}",response); + return response; }catch(Exception e){ logger.error("Exception occurred !" , e); + return new ObjectMapper().createObjectNode().put("ERROR ","exception caught"); } } - /** - * Anchors schema to the CORD CHAIN - */ - public void anchorSchemaAPI(JsonNode obj){ - // apiHelper(obj,"http://172.24.0.1:5106/api/v1/schema"); - apiHelper(obj,cord_schema_url); // considering issuer agent running in local + + /** Anchors schema to the CORD CHAIN*/ + public JsonNode anchorSchemaAPI(JsonNode obj) throws Exception{ + JsonNode schema=apiHelper(obj,cord_schema_url); + return schema; + } + /** Anchors registry to the CORD NETWORK ,*/ + public JsonNode anchorRegistryAPI(JsonNode obj) throws Exception{ + JsonNode registryDetails=apiHelper(obj,cord_registry_url); + return registryDetails; } + /** Helper function for Anchoring to CORD */ + public JsonNode anchorToCord(JsonNode rootNode) throws Exception{ + try{ - /** - * Anchors registry to the chain , - * Before calling this api, schema must be created - - */ - public void anchorRegistryAPI(){ + ObjectMapper objectMapper=new ObjectMapper(); + /* anchor schema */ + JsonNode schemaProperty=rootNode.get("schema"); + JsonNode convertedSchema=objectMapper.readTree(schemaProperty.asText()); + + JsonNode schemaNode=convertedSchema.get("definitions"); + + JsonNode properties=schemaNode.get(rootNode.get("name").asText()); + JsonNode getProperties=properties.get("properties"); + + JsonNode createSchema=objectMapper.createObjectNode() + .put("title",convertedSchema.get("title").asText()) + .put("description",convertedSchema.get("description").asText()) + .set("properties",properties.get("properties")); + + JsonNode schemaToBeAnchored=objectMapper.createObjectNode() + .set("schema",createSchema); + + JsonNode anchoredSchema=anchorSchemaAPI(schemaToBeAnchored); + logger.info("ANCHORED SCHEMA TO CORD CHAIN {}",anchoredSchema); + /* Anchoring registry to CORD */ + JsonNode registrySchema=objectMapper.createObjectNode() + .put("title",convertedSchema.get("title").asText()) + .put("description",convertedSchema.get("description").asText()) + .put("schemaId",anchoredSchema.get("schemaId").asText()); + + JsonNode registryId=anchorRegistryAPI(registrySchema); + logger.info("REGISTRY ID GENERATED ON CORD {} ",registryId); + + ((ObjectNode)rootNode).set("cord_re gistry_id", registryId.get("registryId")); + ((ObjectNode)rootNode).set("cord_schema_id", anchoredSchema.get("schemaId")); + + return rootNode; + }catch(Exception e){ + logger.error("ERROR {}",e); + return objectMapper.createObjectNode().put("ERROR","Exception occurred"); + } } /** diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 4509edb97..d2cd2cc7e 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -66,7 +66,10 @@ registry: host: ${redis_host:localhost} port: ${redis_port:6379} cord: - schemaURL: ${cord_schema_url:http://localhost:5106/api/v1/schema} + anchor_to_cord: ${anchor_to_cord:true} + issuer_schema_url: ${issuer_schema_url:http://172.24.0.1:5106/api/v1/schema} + issuer_registry_url : ${issuer_registry_url:http://172.24.0.1:5106/api/v1/registry} + issuer_credential_url: ${issuer_credential_url:http://172.24.0.1:5106/api/v1/cred} workflow: enabled: ${workflow.enable:true} From 36e806b16ae66b251c4b80008e469ae57dbbfa4e Mon Sep 17 00:00:00 2001 From: VenuChoudhary001 Date: Wed, 6 Sep 2023 16:17:02 +0530 Subject: [PATCH 4/9] [+] anchoring documents/entities to the cord blockchain --- .../controller/RegistryEntityController.java | 26 +++--- .../registry/helper/RegistryHelper.java | 83 +++++++++++++++++-- 2 files changed, 90 insertions(+), 19 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 d67b8624f..c6ea4c963 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 @@ -387,19 +387,20 @@ public ResponseEntity postEntity( ObjectMapper objectMapper = new ObjectMapper(); Map result = new HashMap<>(); ObjectNode newRootNode = objectMapper.createObjectNode(); - - if (anchorToCord) { - if("Schema".equals(entityName)){ - JsonNode getRootNode=registryHelper.anchorToCord(rootNode); - newRootNode.set(entityName, getRootNode); - } - }else{ - newRootNode.set(entityName, rootNode); - } - logger.info("NEW NODE : {}",newRootNode); - + try { checkEntityNameInDefinitionManager(entityName); + // anchor schema to chain + if (anchorToCord) { + if("Schema".equals(entityName)){ + JsonNode getRootNode=registryHelper.anchorToCord(rootNode); + newRootNode.set(entityName, getRootNode); + }else{ + newRootNode.set(entityName,rootNode); + } + }else{ + newRootNode.set(entityName, rootNode); + } String userId = registryHelper.authorizeManageEntity(request, entityName); String label = registryHelper.addEntity(newRootNode, userId); String emailId = registryHelper.fetchEmailIdFromToken( @@ -420,6 +421,9 @@ public ResponseEntity postEntity( ); resultMap.put(dbConnectionInfoMgr.getUuidPropertyName(), label); } + // anchor a document to cord chain + if(anchorToCord && !"Schema".equals(entityName)) + registryHelper.anchorCredentialsToCord(entityName,rootNode); result.put(entityName, resultMap); response.setResult(result); 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 556f27880..1530fdf5f 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 @@ -86,15 +86,16 @@ public class RegistryHelper { private static final String CLAIM_ID = "claimId"; private static final String ATTESTATION_RESPONSE = "attestationResponse"; public static String ROLE_ANONYMOUS = "anonymous"; - + private final WebClient.Builder builder = WebClient.builder(); private static final org.slf4j.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("${cord.issuer_schema_url:http://172.24.0.1/5106/api/v1/schema}") String cord_schema_url; - @Value("${cord.issuer_registry_url:http://172.24.0.1/5106/api/v1/registry}") String cord_registry_url; + @Value("${registry.cord.issuer_schema_url}") String issuer_schema_url; + @Value("${registry.cord.issuer_registry_url}") String issuer_registry_url; + @Value("${registry.cord.issuer_credential_url}") String issuer_credential_url; @Autowired private NotificationHelper notificationHelper; @@ -200,9 +201,8 @@ public JsonNode removeFormatAttr(JsonNode requestBody) { * REUSBALE METHOD FOR POST API CALLS */ public JsonNode apiHelper(JsonNode obj,String url) throws Exception{ - WebClient.Builder builder = WebClient.builder(); try{ - Mono responseMono = builder.build() + Mono responseMono = this.builder.build() .post() .uri(url) .contentType(MediaType.APPLICATION_JSON) @@ -226,12 +226,12 @@ public JsonNode apiHelper(JsonNode obj,String url) throws Exception{ /** Anchors schema to the CORD CHAIN*/ public JsonNode anchorSchemaAPI(JsonNode obj) throws Exception{ - JsonNode schema=apiHelper(obj,cord_schema_url); + JsonNode schema=apiHelper(obj,issuer_schema_url); return schema; } /** Anchors registry to the CORD NETWORK ,*/ public JsonNode anchorRegistryAPI(JsonNode obj) throws Exception{ - JsonNode registryDetails=apiHelper(obj,cord_registry_url); + JsonNode registryDetails=apiHelper(obj,issuer_registry_url); return registryDetails; } @@ -268,7 +268,7 @@ public JsonNode anchorToCord(JsonNode rootNode) throws Exception{ JsonNode registryId=anchorRegistryAPI(registrySchema); logger.info("REGISTRY ID GENERATED ON CORD {} ",registryId); - ((ObjectNode)rootNode).set("cord_re gistry_id", registryId.get("registryId")); + ((ObjectNode)rootNode).set("cord_registry_id", registryId.get("registryId")); ((ObjectNode)rootNode).set("cord_schema_id", anchoredSchema.get("schemaId")); return rootNode; @@ -278,6 +278,73 @@ public JsonNode anchorToCord(JsonNode rootNode) throws Exception{ } } + /* Anchor documents to the CORD chain + * The below function first calls the search schema endpoint to get the registry_id & schema_id + * to create a proper json structure for issuer agent credentials api + * + * Schema for the search API + * { + * filters:{ + * "name":{ + * "eq":"" + * } + * }, + * limit:1, + * offset:1 + * } + * + * Schema accepted by ISSUER AGENT Credentials api + * { + * "schemaId":"", + * "registryId":"", + * "holderDid":"", + * "property":{ + * "":"" + * } + * } + * + */ + public void anchorCredentialsToCord(String schemaName,JsonNode credentials) throws Exception{ + try { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode filterProperty=objectMapper.createObjectNode() + .put("eq",schemaName); + JsonNode inputJson=objectMapper.createObjectNode() + .set("name",filterProperty); + ArrayNode entity = JsonNodeFactory.instance.arrayNode(); + entity.add("Schema"); + JsonNode newNode= objectMapper.createObjectNode() + .put("limit",1) + .put("offset",0) + .set("filters",inputJson); + ((ObjectNode)newNode).set(ENTITY_TYPE,entity ); + JsonNode getDetails=searchEntity(newNode); + + JsonNode schemaArray=getDetails.get("Schema"); + JsonNode firstSchema = schemaArray.get(0); + appendCredentialsToCord(firstSchema.get("cord_schema_id").asText(),firstSchema.get("cord_registry_id").asText(), credentials); + + } catch (Exception e) { + logger.error("EXCEPTION OCCURRED",e); + } + } + // The holderDid is hardcoded for now. + private void appendCredentialsToCord(String schemaId,String registryId,JsonNode document){ + try { + ObjectNode documentObject = (ObjectNode) document; + if(documentObject.has("osid")) documentObject.remove("osid"); + if(documentObject.has("osOwner")) documentObject.remove("osOwner"); + JsonNode rootNode=new ObjectMapper().createObjectNode() + .put("schemaId",schemaId) + .put("registryId",registryId) + .put("holderDid","did:cord:3yxVe6KTeexjYkK43q1SZxthbBVhnBdxwh1SYLTxzWxPobSS") + .set("property",documentObject); + + JsonNode anchorVC=apiHelper(rootNode,issuer_credential_url); + } catch (Exception e) { + logger.error("EXCEPTION OCCURRED WHILE APPENDING TO CORD"); + } + } /** * calls validation and then persists the record to registry. * From bed9628fcd206ddbcf20a441bcd7935be892791e Mon Sep 17 00:00:00 2001 From: vikastc Date: Sat, 23 Mar 2024 09:57:21 +0530 Subject: [PATCH 5/9] fix: removed registry dependency of cord Signed-off-by: vikastc --- .../registry/helper/RegistryHelper.java | 31 ++++--------------- .../src/main/resources/application.yml | 5 ++- 2 files changed, 8 insertions(+), 28 deletions(-) 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 cfd157847..d7c7e1d8b 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 @@ -99,7 +99,6 @@ public class RegistryHelper { @Value("${invite.signature_enabled}") boolean skipSignatureForInvite = true; @Value("${registry.cord.issuer_schema_url}") String issuer_schema_url; - @Value("${registry.cord.issuer_registry_url}") String issuer_registry_url; @Value("${registry.cord.issuer_credential_url}") String issuer_credential_url; @@ -239,11 +238,6 @@ public JsonNode anchorSchemaAPI(JsonNode obj) throws Exception{ JsonNode schema=apiHelper(obj,issuer_schema_url); return schema; } - /** Anchors registry to the CORD NETWORK ,*/ - public JsonNode anchorRegistryAPI(JsonNode obj) throws Exception{ - JsonNode registryDetails=apiHelper(obj,issuer_registry_url); - return registryDetails; - } /** Helper function for Anchoring to CORD */ public JsonNode anchorToCord(JsonNode rootNode) throws Exception{ @@ -269,16 +263,7 @@ public JsonNode anchorToCord(JsonNode rootNode) throws Exception{ JsonNode anchoredSchema=anchorSchemaAPI(schemaToBeAnchored); logger.info("ANCHORED SCHEMA TO CORD CHAIN {}",anchoredSchema); - /* Anchoring registry to CORD */ - JsonNode registrySchema=objectMapper.createObjectNode() - .put("title",convertedSchema.get("title").asText()) - .put("description",convertedSchema.get("description").asText()) - .put("schemaId",anchoredSchema.get("schemaId").asText()); - JsonNode registryId=anchorRegistryAPI(registrySchema); - logger.info("REGISTRY ID GENERATED ON CORD {} ",registryId); - - ((ObjectNode)rootNode).set("cord_registry_id", registryId.get("registryId")); ((ObjectNode)rootNode).set("cord_schema_id", anchoredSchema.get("schemaId")); return rootNode; @@ -289,7 +274,7 @@ public JsonNode anchorToCord(JsonNode rootNode) throws Exception{ } /* Anchor documents to the CORD chain - * The below function first calls the search schema endpoint to get the registry_id & schema_id + * The below function first calls the search schema endpoint to get the schema_id * to create a proper json structure for issuer agent credentials api * * Schema for the search API @@ -306,9 +291,7 @@ public JsonNode anchorToCord(JsonNode rootNode) throws Exception{ * Schema accepted by ISSUER AGENT Credentials api * { * "schemaId":"", - * "registryId":"", - * "holderDid":"", - * "property":{ + * "properties":{ * "":"" * } * } @@ -332,23 +315,21 @@ public void anchorCredentialsToCord(String schemaName,JsonNode credentials) thro JsonNode schemaArray=getDetails.get("Schema"); JsonNode firstSchema = schemaArray.get(0); - appendCredentialsToCord(firstSchema.get("cord_schema_id").asText(),firstSchema.get("cord_registry_id").asText(), credentials); + appendCredentialsToCord(firstSchema.get("cord_schema_id").asText(), credentials); } catch (Exception e) { logger.error("EXCEPTION OCCURRED",e); } } - // The holderDid is hardcoded for now. - private void appendCredentialsToCord(String schemaId,String registryId,JsonNode document){ + + private void appendCredentialsToCord(String schemaId,JsonNode document){ try { ObjectNode documentObject = (ObjectNode) document; if(documentObject.has("osid")) documentObject.remove("osid"); if(documentObject.has("osOwner")) documentObject.remove("osOwner"); JsonNode rootNode=new ObjectMapper().createObjectNode() .put("schemaId",schemaId) - .put("registryId",registryId) - .put("holderDid","did:cord:3yxVe6KTeexjYkK43q1SZxthbBVhnBdxwh1SYLTxzWxPobSS") - .set("property",documentObject); + .set("properties",documentObject); JsonNode anchorVC=apiHelper(rootNode,issuer_credential_url); } catch (Exception e) { diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index 47a7f309c..c9bdf32a3 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -67,9 +67,8 @@ registry: port: ${redis_port:6379} cord: anchor_to_cord: ${anchor_to_cord:true} - issuer_schema_url: ${issuer_schema_url:http://172.24.0.1:5106/api/v1/schema} - issuer_registry_url : ${issuer_registry_url:http://172.24.0.1:5106/api/v1/registry} - issuer_credential_url: ${issuer_credential_url:http://172.24.0.1:5106/api/v1/cred} + issuer_schema_url: ${issuer_schema_url:http://172.17.0.1:5106/api/v1/schema} + issuer_credential_url: ${issuer_credential_url:http://172.17.0.1:5106/api/v1/cred} workflow: enabled: ${workflow.enable:true} From caa80e2ee52ac9d0db162a993937b88edf2adc68 Mon Sep 17 00:00:00 2001 From: vikastc Date: Sat, 23 Mar 2024 13:15:22 +0530 Subject: [PATCH 6/9] fix: Naming convention change to camelCase Signed-off-by: vikastc --- .../registry/controller/RegistryEntityController.java | 6 +----- .../dev/sunbirdrc/registry/helper/RegistryHelper.java | 8 ++++---- java/registry/src/main/resources/application.yml | 6 +++--- 3 files changed, 8 insertions(+), 12 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 d2a5e5298..943a31817 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 @@ -80,13 +80,9 @@ public class RegistryEntityController extends AbstractController { private boolean signatureEnabled; @Value("${certificate.enabled}") private boolean certificateEnabled; - @Autowired(required = false) - private ICertificateService certificateService; @Value("${filestorage.enabled}") private boolean fileStorageEnabled; - @Autowired(required = false) - private FileStorageService fileStorageService; @Autowired @@ -99,7 +95,7 @@ public class RegistryEntityController extends AbstractController { boolean securityEnabled; @Value("${certificate.enableExternalTemplates:false}") boolean externalTemplatesEnabled; - @Value("${cord.anchor_to_cord:true}") + @Value("${cord.anchorToCord:true}") boolean anchorToCord; @RequestMapping( 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 d7c7e1d8b..23c40f121 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 @@ -98,8 +98,8 @@ public class RegistryHelper { @Value("${invite.required_validation_enabled}") boolean skipRequiredValidationForInvite = true; @Value("${invite.signature_enabled}") boolean skipSignatureForInvite = true; - @Value("${registry.cord.issuer_schema_url}") String issuer_schema_url; - @Value("${registry.cord.issuer_credential_url}") String issuer_credential_url; + @Value("${registry.cord.issuerSchemaUrl}") String issuerSchemaUrl; + @Value("${registry.cord.issuerCredentialUrl}") String issuerCredentialUrl; @Autowired(required = false) @@ -235,7 +235,7 @@ public JsonNode apiHelper(JsonNode obj,String url) throws Exception{ /** Anchors schema to the CORD CHAIN*/ public JsonNode anchorSchemaAPI(JsonNode obj) throws Exception{ - JsonNode schema=apiHelper(obj,issuer_schema_url); + JsonNode schema=apiHelper(obj,issuerSchemaUrl); return schema; } @@ -331,7 +331,7 @@ private void appendCredentialsToCord(String schemaId,JsonNode document){ .put("schemaId",schemaId) .set("properties",documentObject); - JsonNode anchorVC=apiHelper(rootNode,issuer_credential_url); + JsonNode anchorVC=apiHelper(rootNode,issuerCredentialUrl); } catch (Exception e) { logger.error("EXCEPTION OCCURRED WHILE APPENDING TO CORD"); } diff --git a/java/registry/src/main/resources/application.yml b/java/registry/src/main/resources/application.yml index c9bdf32a3..fb880c42c 100644 --- a/java/registry/src/main/resources/application.yml +++ b/java/registry/src/main/resources/application.yml @@ -66,9 +66,9 @@ registry: host: ${redis_host:localhost} port: ${redis_port:6379} cord: - anchor_to_cord: ${anchor_to_cord:true} - issuer_schema_url: ${issuer_schema_url:http://172.17.0.1:5106/api/v1/schema} - issuer_credential_url: ${issuer_credential_url:http://172.17.0.1:5106/api/v1/cred} + anchorToCord: ${anchor_to_cord:true} + issuerSchemaUrl: ${issuer_schema_url:http://172.17.0.1:5106/api/v1/schema} + issuerCredentialUrl: ${issuer_credential_url:http://172.17.0.1:5106/api/v1/cred} workflow: enabled: ${workflow.enable:true} From b385c836acd1b2edaf4553768930ea8a97ee2d58 Mon Sep 17 00:00:00 2001 From: vikastc Date: Sat, 23 Mar 2024 14:14:08 +0530 Subject: [PATCH 7/9] fix: required = false for certificateService and fileStorageService Signed-off-by: vikastc --- .../registry/controller/RegistryEntityController.java | 6 +++--- 1 file changed, 3 insertions(+), 3 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 943a31817..a78d61ea7 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 @@ -70,10 +70,10 @@ public class RegistryEntityController extends AbstractController { RegistryEntityController.class ); - @Autowired - private ICertificateService certificateService; + @Autowired(required = false) + private ICertificateService certificateService; - @Autowired + @Autowired(required = false) private FileStorageService fileStorageService; @Value("${signature.enabled}") From 243a2bc5b9ad116cc71338019cc6b94c26c91eff Mon Sep 17 00:00:00 2001 From: vikastc Date: Sat, 23 Mar 2024 15:31:41 +0530 Subject: [PATCH 8/9] fix: key name change from properties to property Signed-off-by: vikastc --- .../main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 23c40f121..b71ece240 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 @@ -329,7 +329,7 @@ private void appendCredentialsToCord(String schemaId,JsonNode document){ if(documentObject.has("osOwner")) documentObject.remove("osOwner"); JsonNode rootNode=new ObjectMapper().createObjectNode() .put("schemaId",schemaId) - .set("properties",documentObject); + .set("property",documentObject); JsonNode anchorVC=apiHelper(rootNode,issuerCredentialUrl); } catch (Exception e) { From b70cb38d7a65c2bfee7704af6b764803b35da379 Mon Sep 17 00:00:00 2001 From: vikastc Date: Sat, 23 Mar 2024 16:32:12 +0530 Subject: [PATCH 9/9] fix: revert property to properties Signed-off-by: vikastc --- .../main/java/dev/sunbirdrc/registry/helper/RegistryHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 b71ece240..23c40f121 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 @@ -329,7 +329,7 @@ private void appendCredentialsToCord(String schemaId,JsonNode document){ if(documentObject.has("osOwner")) documentObject.remove("osOwner"); JsonNode rootNode=new ObjectMapper().createObjectNode() .put("schemaId",schemaId) - .set("property",documentObject); + .set("properties",documentObject); JsonNode anchorVC=apiHelper(rootNode,issuerCredentialUrl); } catch (Exception e) {