diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 7f8521b698..720b945a6d 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -333,3 +333,75 @@ jobs: file: ./web-proxy/Dockerfile.demo push: true tags: 'gcr.io/hedera-registry/frontend-demo:${{ steps.package-version.outputs.current-version}}' + + - name: indexer-worker-service-latest + if: ${{ steps.latestTag.outputs.value == 'latest'}} + uses: docker/build-push-action@v2 + with: + context: . + file: ./indexer-worker-service/Dockerfile + push: true + tags: 'gcr.io/hedera-registry/indexer-worker-service:${{ steps.package-version.outputs.current-version}}, gcr.io/hedera-registry/indexer-worker-service:latest' + + - name: indexer-worker-service + if: ${{ steps.latestTag.outputs.value == 'hotfix'}} + uses: docker/build-push-action@v2 + with: + context: . + file: ./indexer-worker-service/Dockerfile + push: true + tags: 'gcr.io/hedera-registry/indexer-worker-service:${{ steps.package-version.outputs.current-version}}' + + - name: indexer-service-latest + if: ${{ steps.latestTag.outputs.value == 'latest'}} + uses: docker/build-push-action@v2 + with: + context: . + file: ./indexer-service/Dockerfile + push: true + tags: 'gcr.io/hedera-registry/indexer-service:${{ steps.package-version.outputs.current-version}}, gcr.io/hedera-registry/indexer-service:latest' + + - name: indexer-service + if: ${{ steps.latestTag.outputs.value == 'hotfix'}} + uses: docker/build-push-action@v2 + with: + context: . + file: ./indexer-service/Dockerfile + push: true + tags: 'gcr.io/hedera-registry/indexer-service:${{ steps.package-version.outputs.current-version}}' + + - name: indexer-api-gateway-latest + if: ${{ steps.latestTag.outputs.value == 'latest'}} + uses: docker/build-push-action@v2 + with: + context: . + file: ./indexer-api-gateway/Dockerfile + push: true + tags: 'gcr.io/hedera-registry/indexer-api-gateway:${{ steps.package-version.outputs.current-version}}, gcr.io/hedera-registry/indexer-api-gateway:latest' + + - name: indexer-api-gateway + if: ${{ steps.latestTag.outputs.value == 'hotfix'}} + uses: docker/build-push-action@v2 + with: + context: . + file: ./indexer-api-gateway/Dockerfile + push: true + tags: 'gcr.io/hedera-registry/indexer-api-gateway:${{ steps.package-version.outputs.current-version}}' + + - name: indexer-web-proxy-latest + if: ${{ steps.latestTag.outputs.value == 'latest'}} + uses: docker/build-push-action@v2 + with: + context: . + file: ./indexer-web-proxy/Dockerfile + push: true + tags: 'gcr.io/hedera-registry/indexer-web-proxy:${{ steps.package-version.outputs.current-version}}, gcr.io/hedera-registry/indexer-web-proxy:latest' + + - name: indexer-web-proxy + if: ${{ steps.latestTag.outputs.value == 'hotfix'}} + uses: docker/build-push-action@v2 + with: + context: . + file: ./indexer-web-proxy/Dockerfile + push: true + tags: 'gcr.io/hedera-registry/indexer-web-proxy:${{ steps.package-version.outputs.current-version}}' diff --git a/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/GS Rice Methodology Schema Design Review Ready.xlsx b/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/GS Rice Methodology Schema Design Review Ready.xlsx new file mode 100644 index 0000000000..56ca5f4bb2 Binary files /dev/null and b/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/GS Rice Methodology Schema Design Review Ready.xlsx differ diff --git a/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/Gold Standard Rice.policy b/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/Gold Standard Rice.policy new file mode 100644 index 0000000000..a682772cb6 Binary files /dev/null and b/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/Gold Standard Rice.policy differ diff --git a/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/readme.md b/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/readme.md new file mode 100644 index 0000000000..4ffb1c7f04 --- /dev/null +++ b/Methodology Library/GoldStandard/Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation/readme.md @@ -0,0 +1,185 @@ +## Table of Contents + + +- Introduction +- Key Features +- Potential Impacts & Benefits +- Demo Video +- Policy Workflow +- Policy Guide +- Available Roles +- Important Documents & Schemas +- Token (Verified Emission Reduction) +- Step by Step + + + +## Introduction + +The Methane Emission Reduction in Rice Cultivation methodology offers a comprehensive approach to mitigating greenhouse gas emissions associated with rice production. Rice cultivation accounts for approximately 8% of agricultural greenhouse gas emissions globally, primarily due to methane emissions. This methodology addresses this issue by implementing various measures to reduce methane generation during rice cultivation. + +## Key Features + +- Water Regime Optimization: By transitioning from continuously flooded conditions to intermittently flooded conditions or shortening the period of flooded conditions, this methodology reduces the anaerobic decomposition of organic matter, thereby lowering methane emissions. +- Alternate Wetting and Drying (AWD) Method: AWD method allows for periodic drying and re-flooding of rice fields, creating aerobic conditions that inhibit methane production. +- Aerobic Rice Cultivation Methods: Adopting aerobic rice cultivation techniques further promotes aerobic conditions in the soil, minimizing methane emissions. +- Direct-Seeded Rice (DSR) Cultivation: Switching from transplanted to direct-seeded rice helps in reducing methane emissions by altering the water management practices and organic matter decomposition dynamics. + +## Potential Impacts and Benefits + +- Implementing this methodology not only contributes to mitigating climate change by reducing methane emissions but also offers additional benefits: +- Income Generation for Farmers: By participating in emission reduction activities, farmers can generate additional income through the sale of carbon credits, contributing to their livelihoods. +- Corporate Sustainability Goals: Companies can use purchased carbon credits to offset their emissions and meet sustainability targets, including Scope 3 emissions related to their supply chains. +- Global Food Security: Sustainable rice production practices help safeguard local economies and ensure food security for millions of people worldwide, without compromising agricultural productivity. + +## Demo Video + +[Youtube](https://www.youtube.com/watch?v=UjngB_hnUUs) + +## Policy Workflow + +![image](https://github.com/hashgraph/guardian/assets/79293833/59232f98-81e2-4803-9692-6e339d2eef89) + +## Policy Guide + +This policy is published to Hedera network and can either be imported via Github (.policy file) or IPFS timestamp. + +### Available Roles + +- *Project Proponent - The project proponent is responsible for executing the emission reduction project. The project proponent must adhere to the requirements outlined by Gold Standard’s Methodology for Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation. Upon successful verification, the project proponent receives VERs as an incentive for their emission reduction activities. +- Gold Standard Verification and Validation Body (GS-VVB) - The VVB plays a critical role in independently verifying and validating the project data submitted by the project proponent. They thoroughly assess the project's emission reductions potential, methodologies, and adherence to the policy guidelines. Based on their evaluation, the VVB either approves or rejects the project for registration and certification. +- Registry (Gold Standard) – With Gold Standard as the registry they take on responsibilities that encompass project intake, pipeline management, and final review of project descriptions and monitoring reports. This process ensures that emissions reduction projects meet the highest standards before credits are issued. + +## Important Documents & Schemas + +- Key Project Information - Key Information regarding the project activities and project developers. +- Project Design Document - The project design document (PDD) is used by project developers to submit documentation for certification purposes. +- Stakeholder Consultation – The aim of the stakeholder consultation is to meaningfully engage stakeholders and collect feedback. +- Emission Reductions – The standard and simplified emission reductions form will collect all data that is required to calculate the projects reductions. +- Annual Report - An annual report will be submitted with the monitoring report. This annual report will collect information about any changes that have occurred. +- Monitoring Report – This monitoring report will cover information from all previous schemas allowing the project developer to make updates as needed. + +## Token (Verified Emission Reductions) + +Verified Emission Reductions (VER), each Gold Standard VER represents one metric ton of carbon dioxide equivalent (CO2e) emissions that the project has reduced or removed. + +## Step By Step + +1. Log in as the Standard Registry and import the policy either by file or through IPFS timestamp by selecting the third button at the top right. + +![image](https://github.com/hashgraph/guardian/assets/79293833/6fadd4b4-b6aa-47f3-ab10-1ea990321377) + +![image](https://github.com/hashgraph/guardian/assets/79293833/3d2cb45d-73d9-4693-a04b-219d9706d058) + +![image](https://github.com/hashgraph/guardian/assets/79293833/441116f0-251f-429e-8287-b5d7acdfceb3) + +![image](https://github.com/hashgraph/guardian/assets/79293833/1db37409-613f-4f2c-a26a-f310b5b4ddbd) + +2. Once the policy has successfully imported, you will be redirected to the policy configurator. To start using the policy you must first change the status of the policy from “Draft” to “Dry Run” or “Publish”, then select the “Register” or “Go” button. This can be done through the policy configurator page or though the “Manage Policies” page. + +![image](https://github.com/hashgraph/guardian/assets/79293833/74f3bb73-86ed-4d48-bba9-69dd9bbb71fa) + +![image](https://github.com/hashgraph/guardian/assets/79293833/19172971-7c0c-4cfb-af10-4bfecd2f358e) + +![image](https://github.com/hashgraph/guardian/assets/79293833/0c18e672-fe1e-4013-8876-363ef7f79d26) + +3. Create additional users by clicking the “Create User” button. + +![image](https://github.com/hashgraph/guardian/assets/79293833/36a37ff9-eef2-4810-8a3d-5de106db626c) + +4. Once the users have been created go to each one and assign the appropriate role (i.e. Project Proponent, VVB, Technical Advisory Committee and NGO Supporters). + +![image](https://github.com/hashgraph/guardian/assets/79293833/611a68ad-f761-432a-aec1-1a40fee509a8) + +5. The VVB can provide their name or the name they would like users to see when reviewing projects. + +![image](https://github.com/hashgraph/guardian/assets/79293833/75dc662f-a6cc-420f-a6f4-3db15d73b04e) + +6. Log in as the SR and select the “Approve VVB” tab to view the documents submitted by the VVB. The SR can approve their request by clicking on the “Approve" button. + +![image](https://github.com/hashgraph/guardian/assets/79293833/ba3b58e9-7c2e-4150-b196-a1290ed767c1) + +7. Log in as the Project Proponent and create a new project by clicking on the "New Project" button. + +![image](https://github.com/hashgraph/guardian/assets/79293833/8be3c01b-6668-4740-a497-bf04f78fb4d5) + +8. You can input all the project details and data associated with the project in the “New Project” form. + +![image](https://github.com/hashgraph/guardian/assets/79293833/6a4e6961-284e-4085-af0e-03e48afb06e2) + +9. The next step is to access the SR profile and include the project in the ”Project pipeline”. This can be achieved by navigating to the "Project Pipeline" tab and clicking on the "List" option. + +![image](https://github.com/hashgraph/guardian/assets/79293833/4f4660cf-a489-4a73-a534-3a6d302cc5fb) + +10. The Project Proponent assigns the VVB to verify it by navigating to the “Projects” tab and selecting the dropdown under “Assign”. + +![image](https://github.com/hashgraph/guardian/assets/79293833/21720ded-22a2-4c25-99db-287397a3a4aa) + +11. After successfully assigning the VVB to the project, the next step is to access the VVB profile and click on the "validate" option located in the "Projects" tab. After clicking on the "Validate" button, the VVb needs to add a comment. + +![image](https://github.com/hashgraph/guardian/assets/79293833/0f6c6779-5a27-4ee5-af2f-d2de6a692d98) + +![image](https://github.com/hashgraph/guardian/assets/79293833/f90d5ca6-b771-4769-85cb-e52e32eed58a) + +12. Log in as Project Proponent and create a monitoring report by clicking on the “Add Report” button then fill out the monitoring report form. + +![image](https://github.com/hashgraph/guardian/assets/79293833/05afba8e-1004-4364-a0aa-1b1acb5a4ee9) + +![image](https://github.com/hashgraph/guardian/assets/79293833/38db13a0-5275-4215-b6bb-a606546f5359) + +13. Log in as the VVB and click the “Monitoring Reports” tab to review the document submitted by the Project Proponent. After reviewing the monitoring report by selecting “View Document”, the VVB can select “Verify”. + +![image](https://github.com/hashgraph/guardian/assets/79293833/069fddeb-9a2a-41c2-a0a2-ba62ae872b7c) + +14. Log in as the SR to review the monitoring report by selecting the “View Document” button in the “Monitoring Reports” tab. The SR can approve the monitoring report by selecting “Approve”. + +![image](https://github.com/hashgraph/guardian/assets/79293833/ad56c96a-9b9e-47a0-896b-e7cf40b19905) + +15. After reviewing the monitoring report, the Technical Advisory Committee can provide comments. Log in as theTechnical Advisory Committee and create a comment by clicking on the “Comment” button in the “Monitoring Reports” tab. + +![image](https://github.com/hashgraph/guardian/assets/79293833/b89f9221-028a-4970-8003-1d92f217948d) + +16. Similarly, you can leave comments for the “NGO supporter” profile. Log in as the NGO supporter and create a comment by clicking on the “Comment” button in the “Monitoring Reports” tab. + +![image](https://github.com/hashgraph/guardian/assets/79293833/bb1a1f38-5171-4c31-a4c7-f92b8702bbac) + +17. The SR after approval of the monitoring report can start the minting process by clicking on the “mint” button. + +![image](https://github.com/hashgraph/guardian/assets/79293833/778549b6-5273-46fb-b30a-16125704c4f4) + +18. Once the minting process is completed, you can view the token amount by navigating to the “Token History” tab + +![image](https://github.com/hashgraph/guardian/assets/79293833/3ff4b16a-2d28-44e0-8ff9-e9b078f59482) + +19. The TrustChain can also be viewed by clicking on the “View TrustChain” button. + +![image](https://github.com/hashgraph/guardian/assets/79293833/c05ecadd-8ae8-49da-a2e3-b9188f4ad6e9) + +![image](https://github.com/hashgraph/guardian/assets/79293833/fcf30065-f138-465e-b90c-0ade2e577c4d) + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ai-service/package.json b/ai-service/package.json index e6203a958c..f7f19606c2 100644 --- a/ai-service/package.json +++ b/ai-service/package.json @@ -1,13 +1,13 @@ { "name": "ai-service", - "version": "2.24.1", + "version": "2.25.0", "main": "dist/app.js", "license": "Apache-2.0", "dependencies": { - "@guardian/common": "^2.24.1", - "@guardian/interfaces": "^2.24.1", - "@mikro-orm/core": "^6.1.11", - "@mikro-orm/mongodb": "^6.1.11", + "@guardian/common": "^2.25.0", + "@guardian/interfaces": "^2.25.0", + "@mikro-orm/core": "6.2.2", + "@mikro-orm/mongodb": "6.2.2", "@nestjs/common": "^9.4.1", "@nestjs/core": "^9.4.1", "@types/express": "^4.17.18", diff --git a/analytics-service/package.json b/analytics-service/package.json index 49c0e2bc20..89cf74106a 100644 --- a/analytics-service/package.json +++ b/analytics-service/package.json @@ -13,8 +13,8 @@ }, "author": "Envision Blockchain Solutions ", "dependencies": { - "@guardian/common": "^2.24.1", - "@guardian/interfaces": "^2.24.1", + "@guardian/common": "^2.25.0", + "@guardian/interfaces": "^2.25.0", "@nestjs/common": "^9.4.1", "@nestjs/core": "^9.4.1", "@nestjs/jwt": "^10.0.3", @@ -82,5 +82,5 @@ "test": "mocha tests/**/*.test.js --reporter mocha-junit-reporter --reporter-options mochaFile=../test_results/ui-service.xml" }, "type": "module", - "version": "2.24.1" + "version": "2.25.0" } diff --git a/api-gateway/package.json b/api-gateway/package.json index c05f8e816e..f4040e8912 100644 --- a/api-gateway/package.json +++ b/api-gateway/package.json @@ -1,82 +1,91 @@ { - "packageManager": "yarn@1.22.21", - "resolutions": { - "@azure/core-rest-pipeline": "1.12.1", - "image-size": "1.0.2" - }, - "author": "Envision Blockchain Solutions ", - "dependencies": { - "@guardian/common": "^2.24.1", - "@guardian/interfaces": "^2.24.1", - "@nestjs/common": "^9.4.1", - "@nestjs/core": "^9.4.1", - "@nestjs/jwt": "^10.0.3", - "@nestjs/microservices": "^9.4.1", - "@nestjs/platform-express": "^9.4.2", - "@nestjs/swagger": "^6.3.0", - "@types/express-fileupload": "^1.4.1", - "async-mutex": "^0.4.0", - "axios": "^1.3.6", - "class-transformer": "^0.5.1", - "class-validator": "^0.14.0", - "dotenv": "^16.0.0", - "express": "^4.17.1", - "express-fileupload": "^1.4.0", - "gulp": "^4.0.2", - "gulp-copy": "^4.0.1", - "gulp-rename": "^2.0.0", - "gulp-sourcemaps": "^3.0.0", - "gulp-typescript": "^6.0.0-alpha.1", - "hpp": "^0.2.3", - "http-errors": "^2.0.0", - "ioredis": "^5.3.2", - "jsonwebtoken": "^8.5.1", - "jszip": "^3.7.1", - "module-alias": "^2.2.2", - "prom-client": "^14.1.1", - "prometheus-api-metrics": "3.2.2", - "reflect-metadata": "^0.1.13", - "rxjs": "^7.8.1", - "ws": "^8.2.1", - "yaml": "^2.3.1", - "yup": "^1.1.1" - }, - "description": "", - "devDependencies": { - "@types/express": "^4.17.13", - "@types/gulp": "^4", - "@types/gulp-rename": "^2", - "@types/jszip": "^3.4.1", - "@types/node": "^18.16.0", - "@types/ws": "^8.2.2", - "chai": "^4.3.4", - "cross-env": "^7.0.3", - "mocha": "^9.2.0", - "mocha-junit-reporter": "^2.0.2", - "nodemon": "^2.0.12", - "rewire": "^6.0.0", - "sinon": "^15.0.4", - "tslint": "^6.1.3", - "typescript": "^4.5.5" - }, - "files": [ - "dist" - ], - "license": "Apache-2.0", - "main": "dist/index.js", - "module": "dist/index.js", - "name": "api-gateway", - "scripts": { - "build": "gulp build:demo", - "build:prod": "gulp build:prod", - "build:demo": "gulp build:demo", - "debug": "nodemon dist/index.js", - "dev:docker": "npm run build && nodemon .", - "dev": "gulp watch", - "lint": "tslint --config ../tslint.json --project .", - "start": "node dist/index.js", - "test": "mocha tests/**/*.test.js --reporter mocha-junit-reporter --reporter-options mochaFile=../test_results/ui-service.xml" - }, - "type": "module", - "version": "2.24.1" + "author": "Envision Blockchain Solutions ", + "dependencies": { + "@fastify/formbody": "^7.4.0", + "@fastify/multipart": "^8.2.0", + "@fastify/static": "^7.0.0", + "@guardian/common": "^2.25.0", + "@guardian/interfaces": "^2.25.0", + "@nestjs/common": "^9.4.1", + "@nestjs/core": "^9.4.1", + "@nestjs/jwt": "^10.0.3", + "@nestjs/microservices": "^9.4.1", + "@nestjs/platform-express": "^9.4.2", + "@nestjs/platform-fastify": "^9.4.2", + "@nestjs/swagger": "^6.3.0", + "@types/express-fileupload": "^1.4.1", + "async-mutex": "^0.4.0", + "axios": "^1.3.6", + "class-transformer": "^0.5.1", + "class-validator": "^0.14.0", + "dotenv": "^16.0.0", + "express": "^4.17.1", + "express-fileupload": "^1.4.0", + "gulp": "^4.0.2", + "gulp-copy": "^4.0.1", + "gulp-rename": "^2.0.0", + "gulp-sourcemaps": "^3.0.0", + "gulp-typescript": "^6.0.0-alpha.1", + "hpp": "^0.2.3", + "http-errors": "^2.0.0", + "ioredis": "^5.3.2", + "jsonwebtoken": "^8.5.1", + "jszip": "^3.7.1", + "module-alias": "^2.2.2", + "prom-client": "^14.1.1", + "prometheus-api-metrics": "3.2.2", + "reflect-metadata": "^0.1.13", + "rxjs": "^7.8.1", + "ws": "^8.2.1", + "yaml": "^2.3.1", + "yup": "^1.1.1" + }, + "description": "", + "devDependencies": { + "@types/express": "^4.17.13", + "@types/gulp": "^4", + "@types/gulp-rename": "^2", + "@types/jszip": "^3.4.1", + "@types/node": "^18.16.0", + "@types/ws": "^8.2.2", + "chai": "^4.3.4", + "cross-env": "^7.0.3", + "mocha": "^9.2.0", + "mocha-junit-reporter": "^2.0.2", + "nodemon": "^2.0.12", + "rewire": "^6.0.0", + "sinon": "^15.0.4", + "tslint": "^6.1.3", + "typescript": "^4.5.5" + }, + "files": [ + "dist" + ], + "imports": { + "#auth": "./dist/auth/index.js", + "#helpers": "./dist/helpers/index.js", + "#middlewares": "./dist/middlewares/index.js" + }, + "license": "Apache-2.0", + "main": "dist/index.js", + "module": "dist/index.js", + "name": "api-gateway", + "packageManager": "yarn@1.22.21", + "resolutions": { + "@azure/core-rest-pipeline": "1.12.1", + "image-size": "1.0.2" + }, + "scripts": { + "build": "gulp build:demo", + "build:demo": "gulp build:demo", + "build:prod": "gulp build:prod", + "debug": "nodemon dist/index.js", + "dev": "gulp watch", + "dev:docker": "npm run build && nodemon .", + "lint": "tslint --config ../tslint.json --project .", + "start": "node dist/index.js", + "test": "mocha tests/**/*.test.js --reporter mocha-junit-reporter --reporter-options mochaFile=../test_results/ui-service.xml" + }, + "type": "module", + "version": "2.25.0" } diff --git a/api-gateway/src/api/service/account.ts b/api-gateway/src/api/service/account.ts index b7da1f3d82..ad16cc007a 100644 --- a/api-gateway/src/api/service/account.ts +++ b/api-gateway/src/api/service/account.ts @@ -1,19 +1,15 @@ -import { Users } from '../../helpers/users.js'; import { IAuthUser, Logger, NotificationHelper } from '@guardian/common'; -import { Guardians } from '../../helpers/guardians.js'; -import { SchemaEntity, UserRole } from '@guardian/interfaces'; -import { PolicyEngine } from '../../helpers/policy-engine.js'; -import { PolicyListResponse } from '../../entities/policy.js'; -import { StandardRegistryAccountResponse } from '../../entities/account.js'; +import { Permissions, PolicyType, SchemaEntity, UserRole } from '@guardian/interfaces'; import { ClientProxy } from '@nestjs/microservices'; import { Body, Controller, Get, Headers, HttpCode, HttpException, HttpStatus, Inject, Post, Req } from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { AccountsResponseDTO, AccountsSessionResponseDTO, AggregatedDTOItem, BalanceResponseDTO, LoginUserDTO, RegisterUserDTO } from '../../middlewares/validation/schemas/accounts.js'; -import { ApiBearerAuth, ApiExtraModels, ApiForbiddenResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiSecurity, ApiTags, ApiUnauthorizedResponse, getSchemaPath } from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; +import { ApiBearerAuth, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { AccountsResponseDTO, AccountsSessionResponseDTO, AggregatedDTOItem, BalanceResponseDTO, LoginUserDTO, RegisterUserDTO, InternalServerErrorDTO } from '#middlewares'; +import { AuthUser, checkPermission, Auth } from '#auth'; +import { Users, PolicyEngine, Guardians, UseCache, InternalException, EntityOwner } from '#helpers'; +import { PolicyListResponse } from '../../entities/policy.js'; +import { StandardRegistryAccountResponse } from '../../entities/account.js'; import { ApplicationEnvironment } from '../../environment.js'; import { CACHE } from '../../constants/index.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; /** * User account route @@ -22,34 +18,33 @@ import { UseCache } from '../../helpers/decorators/cache.js'; @ApiTags('accounts') export class AccountApi { - constructor(@Inject('GUARDIANS') public readonly client: ClientProxy) { - } + constructor(@Inject('GUARDIANS') public readonly client: ClientProxy) { + } /** * getSession * @param headers */ + @Get('/session') + @ApiBearerAuth() @ApiOperation({ summary: 'Returns current session of the user.', description: 'Returns current user session.', }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(AccountsSessionResponseDTO), - }, + type: AccountsSessionResponseDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiBearerAuth() - @HttpCode(HttpStatus.OK) - @Get('/session') + @ApiExtraModels(AccountsSessionResponseDTO, InternalServerErrorDTO) @UseCache() - async getSession(@Headers() headers: { [key: string]: string }): Promise { + @HttpCode(HttpStatus.OK) + async getSession( + @Headers() headers: { [key: string]: string }, + ): Promise { const users = new Users(); try { const authHeader = headers.authorization; @@ -58,7 +53,6 @@ export class AccountApi { } catch (error) { new Logger().error(error, ['API_GATEWAY']); return null; - // throw new HttpException(error.message, HttpStatus.UNAUTHORIZED); } } @@ -66,59 +60,47 @@ export class AccountApi { * register * @param body */ + @Post('/register') @ApiOperation({ summary: 'Registers a new user account.', description: 'Object that contain username, password and role (optional) fields.', }) - @ApiExtraModels(AccountsResponseDTO, InternalServerErrorDTO) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(AccountsResponseDTO), - }, + type: AccountsResponseDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO }) - @Post('/register') + @ApiExtraModels(AccountsResponseDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async register(@Body() body: RegisterUserDTO, @Req() req: any): Promise { + async register( + @Body() body: RegisterUserDTO, + @Req() req: any + ): Promise { const users = new Users(); if (!ApplicationEnvironment.demoMode) { const authHeader = req.headers.authorization; const token = authHeader?.split(' ')[1]; - let user; + let user: IAuthUser | null; try { user = await users.getUserByToken(token) as IAuthUser; } catch (e) { user = null; } - if (!user) { throw new HttpException('UNAUTHORIZED', HttpStatus.UNAUTHORIZED); } try { await checkPermission(UserRole.STANDARD_REGISTRY)(user); } catch (error) { - new Logger().error(error.message, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } try { - const {username, password} = body; - let {role} = body; - // @deprecated 2022-10-01 - if (role === 'ROOT_AUTHORITY') { - role = UserRole.STANDARD_REGISTRY; - } - const user = (await users.registerNewUser( - username, - password, - role - )) as any; + const { role, username, password } = body; + const user = (await users.registerNewUser(username, password, role)); await NotificationHelper.info( 'Welcome to guardian', 'Next register your account in hedera', @@ -128,7 +110,7 @@ export class AccountApi { } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error.message.includes('already exists')) { - throw new HttpException('An account with the same name already exists.', HttpStatus.INTERNAL_SERVER_ERROR); + throw new HttpException(error.message, HttpStatus.CONFLICT); } throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); } @@ -137,28 +119,26 @@ export class AccountApi { /** * Login */ + @Post('/login') @ApiOperation({ summary: 'Logs user into the system.', }) - @ApiExtraModels(AccountsSessionResponseDTO, InternalServerErrorDTO) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(AccountsSessionResponseDTO), - }, + type: AccountsSessionResponseDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/login') + @ApiExtraModels(AccountsSessionResponseDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async login(@Body() body: LoginUserDTO): Promise { - const users = new Users(); + async login( + @Body() body: LoginUserDTO + ): Promise { try { - const {username, password} = body; + const { username, password } = body; + const users = new Users(); return await users.generateNewToken(username, password) as any; } catch (error) { new Logger().warn(error.message, ['API_GATEWAY']); @@ -166,22 +146,24 @@ export class AccountApi { } } + /** + * Get Access Token + */ + @Post('access-token') @ApiOperation({ summary: 'Returns access token.', description: 'Returns access token.' }) @ApiOkResponse({ - description: 'Successful operation.', - // schema: { - // $ref: getSchemaPath(AccountsResponseDTO), - // }, + description: 'Successful operation.' }) - @Post('access-token') - async getAccessToken(@Body() body: any): Promise { + async getAccessToken( + @Body() body: any + ): Promise { try { - const {refreshToken} = body; + const { refreshToken } = body; const users = new Users(); - const {accessToken} = await users.generateNewAccessToken(refreshToken); + const { accessToken } = await users.generateNewAccessToken(refreshToken); if (!accessToken) { throw new HttpException('UNAUTHORIZED', HttpStatus.UNAUTHORIZED); } @@ -196,238 +178,169 @@ export class AccountApi { /** * Accounts */ + @Get('/') + @Auth( + Permissions.ACCOUNTS_ACCOUNT_READ + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Returns a list of users, excluding Standard Registry and Auditors.', description: 'Returns all users except those with roles Standard ' + 'Registry and Auditor. Only users with the Standard ' + 'Registry role are allowed to make the request.', }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(AccountsResponseDTO, InternalServerErrorDTO) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(AccountsResponseDTO), - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: AccountsResponseDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - // @UseGuards(AuthGuard) - @HttpCode(HttpStatus.OK) - @Get() + @ApiExtraModels(AccountsResponseDTO, InternalServerErrorDTO) @UseCache() - async getAllAccounts(@Req() req): Promise { - // await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const authHeader = req.headers.authorization; - const token = authHeader?.split(' ')[1]; - const users = new Users(); - let user; - try { - user = await users.getUserByToken(token) as IAuthUser; - } catch (e) { - user = null; - } - - if (!user) { - throw new HttpException('UNAUTHORIZED', HttpStatus.UNAUTHORIZED); - } + @HttpCode(HttpStatus.OK) + async getAllAccounts(): Promise { try { - await checkPermission(UserRole.STANDARD_REGISTRY)(user); - return await users.getAllUserAccounts() as any[]; + return await (new Users()).getAllUserAccounts(); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } /** - * Get SAs + * Get Standard Registries */ + @Get('/standard-registries') + @Auth( + Permissions.ACCOUNTS_STANDARD_REGISTRY_READ + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR + ) @ApiOperation({ summary: 'Returns all Standard Registries.', description: 'Returns all Standard Registries.' }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(AccountsResponseDTO, InternalServerErrorDTO) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(AccountsResponseDTO), - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: AccountsResponseDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Get('/standard-registries') - @HttpCode(HttpStatus.OK) + @ApiExtraModels(AccountsResponseDTO, InternalServerErrorDTO) @UseCache() - async getStandatdRegistries(@Req() req): Promise { - const authHeader = req.headers.authorization; - const token = authHeader?.split(' ')[1]; - const users = new Users(); - let user; - try { - user = await users.getUserByToken(token) as IAuthUser; - } catch (e) { - throw new HttpException(e.message, HttpStatus.UNAUTHORIZED); - } - if (!user) { - throw new HttpException('UNAUTHORIZED', HttpStatus.UNAUTHORIZED); - } - try { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER, UserRole.AUDITOR)(user); - } catch (e) { - throw new HttpException(e.message, HttpStatus.FORBIDDEN); - } + @HttpCode(HttpStatus.OK) + async getStandardRegistries(): Promise { try { - return await users.getAllStandardRegistryAccounts(); + return await (new Users()).getAllStandardRegistryAccounts(); } catch (error) { - new Logger().error(error.message, ['API_GATEWAY']); - throw error; + await InternalException(error); } } /** - * Get aggregated SAs + * Get aggregated standard registries */ + @Get('/standard-registries/aggregated') + @Auth( + Permissions.ACCOUNTS_STANDARD_REGISTRY_READ + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR + ) @ApiOperation({ summary: 'Returns all Standard Registries aggregated with polices and vcDocuments.', description: 'Returns all Standard Registries aggregated with polices and vcDocuments' }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(AggregatedDTOItem, InternalServerErrorDTO) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'array', - items: { - '$ref': getSchemaPath(AggregatedDTOItem) - } - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + isArray: true, + type: AggregatedDTOItem }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Get('/standard-registries/aggregated') - @HttpCode(HttpStatus.OK) + @ApiExtraModels(AggregatedDTOItem, InternalServerErrorDTO) @UseCache() + @HttpCode(HttpStatus.OK) async getAggregatedStandardRegistries(): Promise { const engineService = new PolicyEngine(); const guardians = new Guardians(); try { const users = new Users(); const standardRegistries = await users.getAllStandardRegistryAccounts() as StandardRegistryAccountResponse[]; - const promises = standardRegistries.filter(({did, username}) => !!did && !!username) - .map(async ({did, username}) => { - let vcDocument = {}; - const user = await users.getUser(username); - const vcDocuments = await guardians.getVcDocuments({ - owner: did, - type: SchemaEntity.STANDARD_REGISTRY - }); - if (vcDocuments && vcDocuments.length) { - vcDocument = vcDocuments[vcDocuments.length - 1]; - } - const { policies } = await engineService.getPolicies( - { filters: { owner: did }, userDid: did } - ) as PolicyListResponse; - return { - did, - vcDocument, - policies, - username, - hederaAccountId: user.hederaAccountId - } + const promises = standardRegistries + .filter(({ did, username }) => !!did && !!username) + .map(async ({ did, username }) => { + let vcDocument = {}; + const user = await users.getUser(username); + const vcDocuments = await guardians.getVcDocuments({ + owner: did, + type: SchemaEntity.STANDARD_REGISTRY + }); + if (vcDocuments && vcDocuments.length) { + vcDocument = vcDocuments[vcDocuments.length - 1]; + } + + const { policies } = await engineService.getPolicies( + { + filters: { + status: { $in: [PolicyType.PUBLISH, PolicyType.DISCONTINUED] } + }, + userDid: did + }, + EntityOwner.sr(did) + ) as PolicyListResponse; + return { + did, + vcDocument, + policies, + username, + hederaAccountId: user.hederaAccountId + } }); return await Promise.all(promises); } catch (error) { - new Logger().error(error.message, ['API_GATEWAY']); - throw error; + await InternalException(error); } } /** - * @param headers + * Get Hedera account balance */ + @Get('/balance') + @Auth( + Permissions.PROFILES_BALANCE_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR + ) @ApiOperation({ summary: 'Returns user\'s Hedera account balance.', description: 'Requests current Hedera account balance.' }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(BalanceResponseDTO, InternalServerErrorDTO) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(BalanceResponseDTO) - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: BalanceResponseDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Get('/balance') - @HttpCode(HttpStatus.OK) + @ApiExtraModels(BalanceResponseDTO, InternalServerErrorDTO) @UseCache({ ttl: CACHE.SHORT_TTL }) - async getBalance(@Headers() headers): Promise { + @HttpCode(HttpStatus.OK) + async getBalance( + @AuthUser() user: IAuthUser, + ): Promise { try { - const authHeader = headers.authorization; - const users = new Users(); - if (authHeader) { - const token = authHeader.split(' ')[1]; - try { - const user = await users.getUserByToken(token) as any; - if (user) { - const guardians = new Guardians(); - return await guardians.getBalance(user.username); - // const balance = await this.client.send(MessageAPI.GET_BALANCE, { username: user.username }).toPromise() - // return balance; - } - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED) - - } catch (error) { - throw new HttpException(error.message, HttpStatus.UNAUTHORIZED) - } - } - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED) + return await (new Guardians()).getBalance(user.username); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/ai-suggestions.ts b/api-gateway/src/api/service/ai-suggestions.ts index 77b7c62c88..80ff807388 100644 --- a/api-gateway/src/api/service/ai-suggestions.ts +++ b/api-gateway/src/api/service/ai-suggestions.ts @@ -1,10 +1,8 @@ -import { Logger } from '@guardian/common'; import { ClientProxy } from '@nestjs/microservices'; -import { Controller, Get, HttpCode, HttpStatus, Inject, Put, Req } from '@nestjs/common'; -import { ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, getSchemaPath } from '@nestjs/swagger'; -import { AISuggestions } from '../../helpers/ai-suggestions.js'; -import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator.js'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/index.js'; +import { Controller, Get, HttpCode, HttpStatus, Inject, Put, Query } from '@nestjs/common'; +import { ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, ApiQuery, ApiExtraModels } from '@nestjs/swagger'; +import { AISuggestions, InternalException } from '#helpers'; +import { InternalServerErrorDTO } from '#middlewares'; /** * AI suggestions route @@ -18,7 +16,6 @@ export class AISuggestionsAPI { /** * Ask */ - @Get('/ask') @ApiOperation({ summary: 'Get methodology suggestion', @@ -30,7 +27,7 @@ export class AISuggestionsAPI { example: 'ACM0001, ACM0002, ACM0006, ACM0007, ACM0018' }, }) - @ApiImplicitParam({ + @ApiQuery({ name: 'q', type: String, description: 'The question of choosing a methodology', @@ -39,42 +36,45 @@ export class AISuggestionsAPI { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getAIAnswer(@Req() req): Promise { - const question = req.query.q as string; - const aiSuggestions = new AISuggestions(); - let aiResponse; + async getAIAnswer( + @Query('q') q: string, + ): Promise { try { - aiResponse = await aiSuggestions.getAIAnswer(question); - } catch (e) { - aiResponse = null; - new Logger().error(e, ['API_GATEWAY']); - throw e; + const aiSuggestions = new AISuggestions(); + return await aiSuggestions.getAIAnswer(q); + } catch (error) { + await InternalException(error); } - - return aiResponse; } + /** + * Rebuild AI vector + */ @Put('/rebuild-vector') @ApiOperation({ summary: 'Rebuild AI vector', description: 'Rebuilds vector based on policy data in the DB', }) + @ApiOkResponse({ + description: 'Successful operation.', + type: Boolean + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async rebuildVector(@Req() req): Promise { - const aiSuggestions = new AISuggestions(); - let result = false; + async rebuildVector(): Promise { try { - result = await aiSuggestions.rebuildAIVector(); - } catch (e) { - new Logger().error(e, ['API_GATEWAY']); - throw e; + const aiSuggestions = new AISuggestions(); + return await aiSuggestions.rebuildAIVector(); + } catch (error) { + await InternalException(error); } - - return result; } } diff --git a/api-gateway/src/api/service/analytics.ts b/api-gateway/src/api/service/analytics.ts index 7aee58253f..155bc49b62 100644 --- a/api-gateway/src/api/service/analytics.ts +++ b/api-gateway/src/api/service/analytics.ts @@ -1,34 +1,10 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { Body, Controller, HttpCode, HttpException, HttpStatus, Post, Req } from '@nestjs/common'; -import { - ApiInternalServerErrorResponse, - ApiUnauthorizedResponse, - ApiForbiddenResponse, - ApiBody, - ApiOkResponse, - ApiOperation, - ApiSecurity, - ApiTags -} from '@nestjs/swagger'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { UserRole } from '@guardian/interfaces'; -import { - FilterDocumentsDTO, - FilterModulesDTO, - FilterPoliciesDTO, - FilterSchemasDTO, - FilterSearchPoliciesDTO, - InternalServerErrorDTO, - CompareDocumentsDTO, - CompareModulesDTO, - ComparePoliciesDTO, - CompareSchemasDTO, - SearchPoliciesDTO, - FilterToolsDTO, - CompareToolsDTO -} from '../../middlewares/validation/schemas/index.js'; - -const ONLY_SR = ' Only users with the Standard Registry role are allowed to make the request.' +import { Body, Controller, HttpCode, HttpException, HttpStatus, Post, Query } from '@nestjs/common'; +import { ApiInternalServerErrorResponse, ApiBody, ApiOkResponse, ApiOperation, ApiTags, ApiExtraModels, ApiQuery } from '@nestjs/swagger'; +import { Permissions } from '@guardian/interfaces'; +import { FilterDocumentsDTO, FilterModulesDTO, FilterPoliciesDTO, FilterSchemasDTO, FilterSearchPoliciesDTO, InternalServerErrorDTO, CompareDocumentsDTO, CompareModulesDTO, ComparePoliciesDTO, CompareSchemasDTO, SearchPoliciesDTO, FilterToolsDTO, CompareToolsDTO, FilterSearchBlocksDTO, SearchBlocksDTO, Examples } from '#middlewares'; +import { AuthUser, Auth } from '#auth'; +import { IAuthUser } from '@guardian/common'; +import { Guardians, ONLY_SR, InternalException } from '#helpers'; @Controller('analytics') @ApiTags('analytics') @@ -37,7 +13,10 @@ export class AnalyticsApi { * Search policies */ @Post('/search/policies') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_POLICY_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Search policies.', description: 'Search policies.' + ONLY_SR, @@ -49,7 +28,7 @@ export class AnalyticsApi { examples: { Filter: { value: { - policyId: '000000000000000000000000' + policyId: Examples.DB_ID } } } @@ -58,35 +37,25 @@ export class AnalyticsApi { description: 'Successful operation.', type: SearchPoliciesDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterSearchPoliciesDTO, SearchPoliciesDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async searchPolicies(@Body() body, @Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardians = new Guardians(); - const policyId = body ? body.policyId : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async searchPolicies( + @AuthUser() user: IAuthUser, + @Body() filters: FilterSearchPoliciesDTO + ): Promise { + const policyId = filters ? filters.policyId : null; if (!policyId) { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { - return await guardians.searchPolicies( - user, - policyId, - ); + const guardians = new Guardians(); + return await guardians.searchPolicies(user, policyId); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -94,7 +63,10 @@ export class AnalyticsApi { * Compare policies */ @Post('/compare/policies') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_POLICY_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare policies.', description: 'Compare policies.' + ONLY_SR, @@ -106,8 +78,8 @@ export class AnalyticsApi { examples: { Filter1: { value: { - policyId1: '000000000000000000000001', - policyId2: '000000000000000000000002', + policyId1: Examples.DB_ID, + policyId2: Examples.DB_ID, eventsLvl: '0', propLvl: '0', childrenLvl: '0', @@ -116,7 +88,7 @@ export class AnalyticsApi { }, Filter2: { value: { - policyIds: ['000000000000000000000001', '000000000000000000000002'], + policyIds: [Examples.DB_ID, Examples.DB_ID], eventsLvl: '0', propLvl: '0', childrenLvl: '0', @@ -129,31 +101,23 @@ export class AnalyticsApi { description: 'Successful operation.', type: ComparePoliciesDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterPoliciesDTO, ComparePoliciesDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async comparePolicies(@Body() body, @Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardians = new Guardians(); - const policyId1 = body ? body.policyId1 : null; - const policyId2 = body ? body.policyId2 : null; - const policyIds = body ? body.policyIds : null; - const eventsLvl = body ? body.eventsLvl : null; - const propLvl = body ? body.propLvl : null; - const childrenLvl = body ? body.childrenLvl : null; - const idLvl = body ? body.idLvl : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async comparePolicies( + @AuthUser() user: IAuthUser, + @Body() filters: FilterPoliciesDTO + ): Promise { + const policyId1 = filters ? filters.policyId1 : null; + const policyId2 = filters ? filters.policyId2 : null; + const policyIds = filters ? filters.policyIds : null; + const eventsLvl = filters ? filters.eventsLvl : null; + const propLvl = filters ? filters.propLvl : null; + const childrenLvl = filters ? filters.childrenLvl : null; + const idLvl = filters ? filters.idLvl : null; let ids: string[]; if (policyId1 && policyId2) { @@ -166,6 +130,7 @@ export class AnalyticsApi { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.comparePolicies( user, null, @@ -176,7 +141,7 @@ export class AnalyticsApi { idLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -184,7 +149,10 @@ export class AnalyticsApi { * Compare modules */ @Post('/compare/modules') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_MODULE_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare modules.', description: 'Compare modules.' + ONLY_SR, @@ -196,8 +164,8 @@ export class AnalyticsApi { examples: { Filter: { value: { - moduleId1: '000000000000000000000001', - moduleId2: '000000000000000000000002', + moduleId1: Examples.DB_ID, + moduleId2: Examples.DB_ID, propLvl: '0', childrenLvl: '0', idLvl: '0' @@ -209,34 +177,27 @@ export class AnalyticsApi { description: 'Successful operation.', type: CompareModulesDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterModulesDTO, CompareModulesDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareModules(@Body() body, @Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardians = new Guardians(); - const moduleId1 = body ? body.moduleId1 : null; - const moduleId2 = body ? body.moduleId2 : null; - const eventsLvl = body ? body.eventsLvl : null; - const propLvl = body ? body.propLvl : null; - const childrenLvl = body ? body.childrenLvl : null; - const idLvl = body ? body.idLvl : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async compareModules( + @AuthUser() user: IAuthUser, + @Body() filters: FilterModulesDTO + ): Promise { + const moduleId1 = filters ? filters.moduleId1 : null; + const moduleId2 = filters ? filters.moduleId2 : null; + const eventsLvl = filters ? filters.eventsLvl : null; + const propLvl = filters ? filters.propLvl : null; + const childrenLvl = filters ? filters.childrenLvl : null; + const idLvl = filters ? filters.idLvl : null; if (!moduleId1 || !moduleId2) { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.compareModules( user, null, @@ -248,7 +209,7 @@ export class AnalyticsApi { idLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -256,7 +217,10 @@ export class AnalyticsApi { * Compare schemas */ @Post('/compare/schemas') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare schemas.', description: 'Compare schemas.' + ONLY_SR, @@ -268,8 +232,8 @@ export class AnalyticsApi { examples: { Filter: { value: { - schemaId1: '000000000000000000000001', - schemaId2: '000000000000000000000002', + schemaId1: Examples.DB_ID, + schemaId2: Examples.DB_ID, idLvl: '0' } } @@ -279,34 +243,27 @@ export class AnalyticsApi { description: 'Successful operation.', type: CompareSchemasDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterSchemasDTO, CompareSchemasDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareSchemas(@Body() body, @Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardians = new Guardians(); - const schemaId1 = body ? body.schemaId1 : null; - const schemaId2 = body ? body.schemaId2 : null; - const idLvl = body ? body.idLvl : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async compareSchemas( + @AuthUser() user: IAuthUser, + @Body() filters: FilterSchemasDTO + ): Promise { + const schemaId1 = filters ? filters.schemaId1 : null; + const schemaId2 = filters ? filters.schemaId2 : null; + const idLvl = filters ? filters.idLvl : null; if (!schemaId1 || !schemaId2) { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.compareSchemas(user, null, schemaId1, schemaId2, idLvl); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -314,7 +271,10 @@ export class AnalyticsApi { * Compare documents */ @Post('/compare/documents') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_DOCUMENT_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare documents.', description: 'Compare documents.' + ONLY_SR, @@ -326,13 +286,13 @@ export class AnalyticsApi { examples: { Filter1: { value: { - documentId1: '000000000000000000000001', - documentId2: '000000000000000000000002' + documentId1: Examples.DB_ID, + documentId2: Examples.DB_ID } }, Filter2: { value: { - documentIds: ['000000000000000000000001', '000000000000000000000002'], + documentIds: [Examples.DB_ID, Examples.DB_ID], } } } @@ -341,32 +301,25 @@ export class AnalyticsApi { description: 'Successful operation.', type: CompareDocumentsDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterDocumentsDTO, CompareDocumentsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareDocuments(@Body() body, @Req() req): Promise { - const guardians = new Guardians(); - const documentId1 = body ? body.documentId1 : null; - const documentId2 = body ? body.documentId2 : null; - const documentIds = body ? body.documentIds : null; - const eventsLvl = body ? body.eventsLvl : null; - const propLvl = body ? body.propLvl : null; - const childrenLvl = body ? body.childrenLvl : null; - const idLvl = body ? body.idLvl : null; + async compareDocuments( + @AuthUser() user: IAuthUser, + @Body() filters: FilterDocumentsDTO + ): Promise { + const documentId1 = filters ? filters.documentId1 : null; + const documentId2 = filters ? filters.documentId2 : null; + const documentIds = filters ? filters.documentIds : null; + const eventsLvl = filters ? filters.eventsLvl : null; + const propLvl = filters ? filters.propLvl : null; + const childrenLvl = filters ? filters.childrenLvl : null; + const idLvl = filters ? filters.idLvl : null; const keyLvl = 0; const refLvl = 0; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } let ids: string[]; if (documentId1 && documentId2) { @@ -378,6 +331,7 @@ export class AnalyticsApi { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.compareDocuments( user, null, @@ -390,7 +344,7 @@ export class AnalyticsApi { refLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -398,7 +352,10 @@ export class AnalyticsApi { * Compare tools */ @Post('/compare/tools') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_TOOL_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare tools.', description: 'Compare tools.' + ONLY_SR, @@ -410,13 +367,13 @@ export class AnalyticsApi { examples: { Filter1: { value: { - toolId1: '000000000000000000000001', - toolId2: '000000000000000000000002' + toolId1: Examples.DB_ID, + toolId2: Examples.DB_ID } }, Filter2: { value: { - toolIds: ['000000000000000000000001', '000000000000000000000002'], + toolIds: [Examples.DB_ID, Examples.DB_ID], } } } @@ -425,30 +382,23 @@ export class AnalyticsApi { description: 'Successful operation.', type: CompareToolsDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterToolsDTO, CompareToolsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareTools(@Body() body, @Req() req): Promise { - const guardians = new Guardians(); - const toolId1 = body ? body.toolId1 : null; - const toolId2 = body ? body.toolId2 : null; - const toolIds = body ? body.toolIds : null; - const eventsLvl = body ? body.eventsLvl : null; - const propLvl = body ? body.propLvl : null; - const childrenLvl = body ? body.childrenLvl : null; - const idLvl = body ? body.idLvl : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async compareTools( + @AuthUser() user: IAuthUser, + @Body() filters: FilterToolsDTO + ): Promise { + const toolId1 = filters ? filters.toolId1 : null; + const toolId2 = filters ? filters.toolId2 : null; + const toolIds = filters ? filters.toolIds : null; + const eventsLvl = filters ? filters.eventsLvl : null; + const propLvl = filters ? filters.propLvl : null; + const childrenLvl = filters ? filters.childrenLvl : null; + const idLvl = filters ? filters.idLvl : null; let ids: string[]; if (toolId1 && toolId2) { @@ -460,6 +410,7 @@ export class AnalyticsApi { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.compareTools( user, null, @@ -470,7 +421,7 @@ export class AnalyticsApi { idLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -478,11 +429,21 @@ export class AnalyticsApi { * Compare policies (CSV) */ @Post('/compare/policies/export') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_POLICY_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare policies.', description: 'Compare policies.' + ONLY_SR, }) + @ApiQuery({ + name: 'type', + type: String, + description: 'File type', + required: true, + example: 'csv' + }) @ApiBody({ description: 'Filters.', required: true, @@ -490,8 +451,8 @@ export class AnalyticsApi { examples: { Filter1: { value: { - policyId1: '000000000000000000000001', - policyId2: '000000000000000000000002', + policyId1: Examples.DB_ID, + policyId2: Examples.DB_ID, eventsLvl: '0', propLvl: '0', childrenLvl: '0', @@ -500,7 +461,7 @@ export class AnalyticsApi { }, Filter2: { value: { - policyIds: ['000000000000000000000001', '000000000000000000000002'], + policyIds: [Examples.DB_ID, Examples.DB_ID], eventsLvl: '0', propLvl: '0', childrenLvl: '0', @@ -513,32 +474,25 @@ export class AnalyticsApi { description: 'Successful operation.', type: String }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterPoliciesDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async comparePoliciesExport(@Body() body, @Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardians = new Guardians(); - const type = req.query ? req.query.type : null; - const policyId1 = body ? body.policyId1 : null; - const policyId2 = body ? body.policyId2 : null; - const policyIds = body ? body.policyIds : null; - const eventsLvl = body ? body.eventsLvl : null; - const propLvl = body ? body.propLvl : null; - const childrenLvl = body ? body.childrenLvl : null; - const idLvl = body ? body.idLvl : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async comparePoliciesExport( + @AuthUser() user: IAuthUser, + @Body() filters: FilterPoliciesDTO, + @Query('type') type: string + ): Promise { + const policyId1 = filters ? filters.policyId1 : null; + const policyId2 = filters ? filters.policyId2 : null; + const policyIds = filters ? filters.policyIds : null; + const eventsLvl = filters ? filters.eventsLvl : null; + const propLvl = filters ? filters.propLvl : null; + const childrenLvl = filters ? filters.childrenLvl : null; + const idLvl = filters ? filters.idLvl : null; + let ids: string[]; if (policyId1 && policyId2) { ids = [policyId1, policyId2]; @@ -549,6 +503,7 @@ export class AnalyticsApi { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.comparePolicies( user, type, @@ -559,7 +514,7 @@ export class AnalyticsApi { idLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -567,11 +522,21 @@ export class AnalyticsApi { * Compare modules (CSV) */ @Post('/compare/modules/export') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_MODULE_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare modules.', description: 'Compare modules.' + ONLY_SR, }) + @ApiQuery({ + name: 'type', + type: String, + description: 'File type', + required: true, + example: 'csv' + }) @ApiBody({ description: 'Filters.', required: true, @@ -579,8 +544,8 @@ export class AnalyticsApi { examples: { Filter: { value: { - moduleId1: '000000000000000000000001', - moduleId2: '000000000000000000000002', + moduleId1: Examples.DB_ID, + moduleId2: Examples.DB_ID, propLvl: '0', childrenLvl: '0', idLvl: '0' @@ -592,35 +557,28 @@ export class AnalyticsApi { description: 'Successful operation.', type: String }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterModulesDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareModulesExport(@Body() body, @Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardians = new Guardians(); - const type = req.query ? req.query.type : null; - const moduleId1 = body ? body.moduleId1 : null; - const moduleId2 = body ? body.moduleId2 : null; - const eventsLvl = body ? body.eventsLvl : null; - const propLvl = body ? body.propLvl : null; - const childrenLvl = body ? body.childrenLvl : null; - const idLvl = body ? body.idLvl : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async compareModulesExport( + @AuthUser() user: IAuthUser, + @Body() filters: FilterModulesDTO, + @Query('type') type: string + ): Promise { + const moduleId1 = filters ? filters.moduleId1 : null; + const moduleId2 = filters ? filters.moduleId2 : null; + const eventsLvl = filters ? filters.eventsLvl : null; + const propLvl = filters ? filters.propLvl : null; + const childrenLvl = filters ? filters.childrenLvl : null; + const idLvl = filters ? filters.idLvl : null; if (!moduleId1 || !moduleId2) { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.compareModules( user, type, @@ -632,7 +590,7 @@ export class AnalyticsApi { idLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -640,11 +598,21 @@ export class AnalyticsApi { * Compare schemas (CSV) */ @Post('/compare/schemas/export') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare schemas.', description: 'Compare schemas.' + ONLY_SR, }) + @ApiQuery({ + name: 'type', + type: String, + description: 'File type', + required: true, + example: 'csv' + }) @ApiBody({ description: 'Filters.', required: true, @@ -652,8 +620,8 @@ export class AnalyticsApi { examples: { Filter: { value: { - schemaId1: '000000000000000000000001', - schemaId2: '000000000000000000000002', + schemaId1: Examples.DB_ID, + schemaId2: Examples.DB_ID, idLvl: '0' } } @@ -663,35 +631,28 @@ export class AnalyticsApi { description: 'Successful operation.', type: String }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterSchemasDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareSchemasExport(@Body() body, @Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardians = new Guardians(); - const type = req.query ? req.query.type : null; - const schemaId1 = body ? body.schemaId1 : null; - const schemaId2 = body ? body.schemaId2 : null; - const idLvl = body ? body.idLvl : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async compareSchemasExport( + @AuthUser() user: IAuthUser, + @Body() filters: FilterSchemasDTO, + @Query('type') type: string + ): Promise { + const schemaId1 = filters ? filters.schemaId1 : null; + const schemaId2 = filters ? filters.schemaId2 : null; + const idLvl = filters ? filters.idLvl : null; if (!schemaId1 || !schemaId2) { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.compareSchemas(user, type, schemaId1, schemaId2, idLvl); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -699,11 +660,21 @@ export class AnalyticsApi { * Compare documents (CSV) */ @Post('/compare/documents/export') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_DOCUMENT_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare documents.', description: 'Compare documents.' + ONLY_SR, }) + @ApiQuery({ + name: 'type', + type: String, + description: 'File type', + required: true, + example: 'csv' + }) @ApiBody({ description: 'Filters.', required: true, @@ -711,13 +682,13 @@ export class AnalyticsApi { examples: { Filter1: { value: { - documentId1: '000000000000000000000001', - documentId2: '000000000000000000000002' + documentId1: Examples.DB_ID, + documentId2: Examples.DB_ID } }, Filter2: { value: { - documentIds: ['000000000000000000000001', '000000000000000000000002'], + documentIds: [Examples.DB_ID, Examples.DB_ID], } } } @@ -726,33 +697,26 @@ export class AnalyticsApi { description: 'Successful operation.', type: String }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterDocumentsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareDocumentsExport(@Body() body, @Req() req): Promise { - const guardians = new Guardians(); - const type = req.query ? req.query.type : null; - const documentId1 = body ? body.documentId1 : null; - const documentId2 = body ? body.documentId2 : null; - const documentIds = body ? body.documentIds : null; - const eventsLvl = body ? body.eventsLvl : null; - const propLvl = body ? body.propLvl : null; - const childrenLvl = body ? body.childrenLvl : null; - const idLvl = body ? body.idLvl : null; + async compareDocumentsExport( + @AuthUser() user: IAuthUser, + @Body() filters: FilterDocumentsDTO, + @Query('type') type: string + ): Promise { + const documentId1 = filters ? filters.documentId1 : null; + const documentId2 = filters ? filters.documentId2 : null; + const documentIds = filters ? filters.documentIds : null; + const eventsLvl = filters ? filters.eventsLvl : null; + const propLvl = filters ? filters.propLvl : null; + const childrenLvl = filters ? filters.childrenLvl : null; + const idLvl = filters ? filters.idLvl : null; const keyLvl = 0; const refLvl = 0; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } let ids: string[]; if (documentId1 && documentId2) { ids = [documentId1, documentId2]; @@ -763,6 +727,7 @@ export class AnalyticsApi { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.compareDocuments( user, type, @@ -775,7 +740,7 @@ export class AnalyticsApi { refLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -783,11 +748,21 @@ export class AnalyticsApi { * Compare tools (CSV) */ @Post('/compare/tools/export') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_TOOL_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Compare tools.', description: 'Compare tools.' + ONLY_SR, }) + @ApiQuery({ + name: 'type', + type: String, + description: 'File type', + required: true, + example: 'csv' + }) @ApiBody({ description: 'Filters.', required: true, @@ -795,13 +770,13 @@ export class AnalyticsApi { examples: { Filter1: { value: { - toolId1: '000000000000000000000001', - toolId2: '000000000000000000000002' + toolId1: Examples.DB_ID, + toolId2: Examples.DB_ID } }, Filter2: { value: { - toolIds: ['000000000000000000000001', '000000000000000000000002'], + toolIds: [Examples.DB_ID, Examples.DB_ID], } } } @@ -810,31 +785,24 @@ export class AnalyticsApi { description: 'Successful operation.', type: String }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterToolsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareToolsExport(@Body() body, @Req() req): Promise { - const guardians = new Guardians(); - const type = req.query ? req.query.type : null; - const toolId1 = body ? body.toolId1 : null; - const toolId2 = body ? body.toolId2 : null; - const toolIds = body ? body.toolIds : null; - const eventsLvl = body ? body.eventsLvl : null; - const propLvl = body ? body.propLvl : null; - const childrenLvl = body ? body.childrenLvl : null; - const idLvl = body ? body.idLvl : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async compareToolsExport( + @AuthUser() user: IAuthUser, + @Body() filters: FilterToolsDTO, + @Query('type') type: string + ): Promise { + const toolId1 = filters ? filters.toolId1 : null; + const toolId2 = filters ? filters.toolId2 : null; + const toolIds = filters ? filters.toolIds : null; + const eventsLvl = filters ? filters.eventsLvl : null; + const propLvl = filters ? filters.propLvl : null; + const childrenLvl = filters ? filters.childrenLvl : null; + const idLvl = filters ? filters.idLvl : null; let ids: string[]; if (toolId1 && toolId2) { ids = [toolId1, toolId2]; @@ -845,6 +813,7 @@ export class AnalyticsApi { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { + const guardians = new Guardians(); return await guardians.compareTools( user, type, @@ -855,7 +824,7 @@ export class AnalyticsApi { idLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -863,7 +832,10 @@ export class AnalyticsApi { * Search same blocks */ @Post('/search/blocks') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ANALYTIC_POLICY_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Search same blocks.', description: 'Search same blocks.' + ONLY_SR, @@ -871,7 +843,7 @@ export class AnalyticsApi { @ApiBody({ description: 'Filters.', required: true, - type: FilterSearchPoliciesDTO, + type: FilterSearchBlocksDTO, examples: { Filter: { value: { @@ -883,35 +855,29 @@ export class AnalyticsApi { }) @ApiOkResponse({ description: 'Successful operation.', - type: SearchPoliciesDTO, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: SearchBlocksDTO, + isArray: true }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterSearchBlocksDTO, SearchBlocksDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async searchBlocks(@Body() body, @Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async searchBlocks( + @AuthUser() user: IAuthUser, + @Body() filters: FilterSearchBlocksDTO + ): Promise { const guardians = new Guardians(); - const id = body ? body.id : null; - const config = body ? body.config : null; - const user = req.user; - if (!user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + const id = filters ? filters.id : null; + const config = filters ? filters.config : null; if (!id || !config) { throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); } try { return await guardians.searchBlocks(config, id, user); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/artifact.ts b/api-gateway/src/api/service/artifact.ts index 118a2b6344..4703e56809 100644 --- a/api-gateway/src/api/service/artifact.ts +++ b/api-gateway/src/api/service/artifact.ts @@ -1,128 +1,115 @@ -import { UserRole } from '@guardian/interfaces'; -import { Logger } from '@guardian/common'; -import { Guardians } from '../../helpers/guardians.js'; -import { - Controller, - Delete, - Get, - HttpCode, - HttpException, - HttpStatus, - Post, - Req, - Response, - UploadedFiles, - UseInterceptors, -} from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { - ApiExtraModels, - ApiInternalServerErrorResponse, - ApiOkResponse, - ApiOperation, - ApiSecurity, - ApiTags, - ApiUnauthorizedResponse, - ApiForbiddenResponse, - getSchemaPath, - ApiBody, - ApiConsumes -} from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; -import { ApiImplicitQuery } from '@nestjs/swagger/dist/decorators/api-implicit-query.decorator.js'; -import { ArtifactDTOItem } from '../../middlewares/validation/schemas/artifacts.js'; -import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator.js'; -import { FilesInterceptor } from '@nestjs/platform-express'; +import { Permissions } from '@guardian/interfaces'; +import { Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Post, Query, Param, Response, UseInterceptors, } from '@nestjs/common'; +import { ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, ApiBody, ApiConsumes, ApiQuery, ApiParam } from '@nestjs/swagger'; +import { AuthUser, Auth } from '#auth'; +import { IAuthUser } from '@guardian/common'; +import { Guardians, InternalException, AnyFilesInterceptor, UploadedFiles, EntityOwner } from '#helpers'; +import { pageHeader, Examples, InternalServerErrorDTO, ArtifactDTOItem } from '#middlewares'; @Controller('artifacts') @ApiTags('artifacts') export class ArtifactApi { /** * Get artifacts - * @param req - * @param res */ @Get('/') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ARTIFACTS_FILE_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Returns all artifacts.', description: 'Returns all artifacts.', }) - @ApiImplicitQuery({ + @ApiQuery({ + name: 'id', + type: String, + description: 'Artifact identifier', + required: false, + example: Examples.DB_ID + }) + @ApiQuery({ name: 'type', enum: ['tool', 'policy'], description: 'Tool|Policy', - required: false + required: false, + example: 'policy' }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'policyId', type: String, description: 'Policy identifier', - required: false + required: false, + example: Examples.DB_ID }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'toolId', type: String, description: 'Tool identifier', - required: false + required: false, + example: Examples.DB_ID }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageIndex', type: Number, description: 'The number of pages to skip before starting to collect the result set', - required: false + required: false, + example: 0 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageSize', type: Number, description: 'The numbers of items to return', - required: false + required: false, + example: 20 }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'array', - items: { - $ref: getSchemaPath(ArtifactDTOItem), - } - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + isArray: true, + headers: pageHeader, + type: ArtifactDTOItem }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO }) @ApiExtraModels(ArtifactDTOItem, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getArtifacts(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getArtifacts( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('id') id: string, + @Query('type') type?: string, + @Query('policyId') policyId?: string, + @Query('toolId') toolId?: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { try { - const guardians = new Guardians(); const options: any = { - owner: req.user.did, + owner: new EntityOwner(user) + }; + if (type) { + options.type = type; + } + if (policyId) { + options.policyId = policyId; } - if (req.query) { - options.type = req.query.type; - options.policyId = req.query.policyId; - options.toolId = req.query.toolId; - options.id = req.query.id; + if (toolId) { + options.toolId = toolId; } - if (req.query && req.query.pageIndex && req.query.pageSize) { - options.pageIndex = req.query.pageIndex; - options.pageSize = req.query.pageSize; + if (id) { + options.id = id; } + if (pageIndex && pageSize) { + options.pageIndex = pageIndex; + options.pageSize = pageSize; + } + const guardians = new Guardians(); const { artifacts, count } = await guardians.getArtifacts(options); - return res.setHeader('X-Total-Count', count).json(artifacts); + return res.header('X-Total-Count', count).send(artifacts); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -130,17 +117,20 @@ export class ArtifactApi { * Upload artifact */ @Post('/:parentId') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ARTIFACTS_FILE_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Upload artifact.', description: 'Upload artifact. For users with the Standard Registry role only.', }) - @ApiImplicitParam({ + @ApiParam({ name: 'parentId', type: String, description: 'Parent ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiConsumes('multipart/form-data') @ApiBody({ @@ -161,36 +151,26 @@ export class ArtifactApi { }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'array', - items: { - $ref: getSchemaPath(ArtifactDTOItem), - } - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + isArray: true, + type: ArtifactDTOItem }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO }) @ApiExtraModels(ArtifactDTOItem, InternalServerErrorDTO) - @UseInterceptors(FilesInterceptor('artifacts')) + @UseInterceptors(AnyFilesInterceptor()) @HttpCode(HttpStatus.CREATED) - async uploadArtifacts(@Req() req, @UploadedFiles() files): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async uploadArtifacts( + @AuthUser() user: IAuthUser, + @Param('parentId') parentId: string, + @UploadedFiles() files: any + ): Promise { try { if (!files) { - throw new HttpException('There are no files to upload', HttpStatus.UNPROCESSABLE_ENTITY) + throw new HttpException('There are no files to upload', HttpStatus.BAD_REQUEST) } - const owner = req.user.did; - const parentId = req.params.parentId; + const owner = new EntityOwner(user); const uploadedArtifacts = []; const guardian = new Guardians(); for (const artifact of files) { @@ -201,8 +181,7 @@ export class ArtifactApi { } return uploadedArtifacts; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -210,50 +189,40 @@ export class ArtifactApi { * Delete artifact */ @Delete('/:artifactId') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.ARTIFACTS_FILE_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Delete artifact.', description: 'Delete artifact.', }) - @ApiImplicitParam({ + @ApiParam({ name: 'artifactId', type: String, description: 'Artifact ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'array', - items: { - $ref: getSchemaPath(ArtifactDTOItem), - } - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO }) @ApiExtraModels(ArtifactDTOItem, InternalServerErrorDTO) - @HttpCode(HttpStatus.NO_CONTENT) - async deleteArtifact(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @HttpCode(HttpStatus.OK) + async deleteArtifact( + @AuthUser() user: IAuthUser, + @Param('artifactId') artifactId: string, + ): Promise { try { const guardian = new Guardians(); - await guardian.deleteArtifact(req.params.artifactId, req.user.did) - return res.status(204).send(); + return await guardian.deleteArtifact(artifactId, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/branding.ts b/api-gateway/src/api/service/branding.ts index 3b8d6642ca..bf036f956a 100644 --- a/api-gateway/src/api/service/branding.ts +++ b/api-gateway/src/api/service/branding.ts @@ -1,22 +1,45 @@ import { Body, Controller, Get, HttpCode, HttpStatus, Post } from '@nestjs/common'; -import { Logger } from '@guardian/common'; -import { Guardians } from '../../helpers/guardians.js'; -import { ApiTags } from '@nestjs/swagger'; -import { Auth } from '../../auth/auth.decorator.js'; -import { UserRole } from '@guardian/interfaces'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { ApiExtraModels, ApiTags, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiBody } from '@nestjs/swagger'; +import { Auth } from '#auth'; +import { Permissions } from '@guardian/interfaces'; +import { BrandingDTO, InternalServerErrorDTO } from '#middlewares'; +import { ONLY_SR, Guardians, UseCache, InternalException } from '#helpers'; /** * Branding route */ @Controller('branding') @ApiTags('branding') -export class BrandingApi{ - - @Auth(UserRole.STANDARD_REGISTRY) - @HttpCode(HttpStatus.NO_CONTENT) +export class BrandingApi { + /** + * Set branding + */ @Post('/') - async setBranding(@Body() body: any): Promise { + @Auth( + Permissions.BRANDING_CONFIG_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Update branding.', + description: 'Update branding.' + ONLY_SR, + }) + @ApiBody({ + description: 'Object that contains config.', + required: true, + type: BrandingDTO + }) + @ApiOkResponse({ + description: 'Successful operation.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(BrandingDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.NO_CONTENT) + async setBranding( + @Body() body: BrandingDTO + ): Promise { try { const { headerColor, @@ -39,27 +62,35 @@ export class BrandingApi{ headerColor1, termsAndConditions }; - - const guardians = new Guardians(); - await guardians.setBranding(JSON.stringify(data)); + const guardians = new Guardians(); + await guardians.setBranding(JSON.stringify(data)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } - - return; } + /** + * Get branding + */ @Get('/') + @ApiOkResponse({ + description: 'Successful operation.', + type: BrandingDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(BrandingDTO, InternalServerErrorDTO) @UseCache() + @HttpCode(HttpStatus.OK) async getBranding(): Promise { try { const guardians = new Guardians(); const brandingDataString = await guardians.getBranding(); return JSON.parse(brandingDataString.config); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/contract.ts b/api-gateway/src/api/service/contract.ts index e5317b459f..e97f24d896 100644 --- a/api-gateway/src/api/service/contract.ts +++ b/api-gateway/src/api/service/contract.ts @@ -1,42 +1,10 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { ContractType, UserRole } from '@guardian/interfaces'; -import { Logger } from '@guardian/common'; -import { - Controller, - Delete, - Get, - HttpCode, - HttpException, - HttpStatus, - Post, - Req, - Response, -} from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { - ApiInternalServerErrorResponse, - ApiOkResponse, - ApiCreatedResponse, - ApiOperation, - ApiUnauthorizedResponse, - ApiExtraModels, - ApiForbiddenResponse, - ApiTags, - ApiBody, - ApiBearerAuth, - ApiQuery, - ApiParam, -} from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; -import { - ContractDTO, - RetirePoolDTO, - RetirePoolTokenDTO, - RetireRequestDTO, - RetireRequestTokenDTO, - WiperRequestDTO, -} from '../../middlewares/validation/schemas/contracts.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { ContractType, Permissions } from '@guardian/interfaces'; +import { IAuthUser } from '@guardian/common'; +import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Query, Response, } from '@nestjs/common'; +import { ApiInternalServerErrorResponse, ApiOkResponse, ApiCreatedResponse, ApiOperation, ApiExtraModels, ApiTags, ApiBody, ApiQuery, ApiParam, } from '@nestjs/swagger'; +import { ContractConfigDTO, ContractDTO, RetirePoolDTO, RetirePoolTokenDTO, RetireRequestDTO, RetireRequestTokenDTO, WiperRequestDTO, InternalServerErrorDTO, pageHeader } from '#middlewares'; +import { AuthUser, Auth } from '#auth'; +import { Guardians, UseCache, InternalException, EntityOwner } from '#helpers'; /** * Contracts api @@ -45,9 +13,16 @@ import { UseCache } from '../../helpers/decorators/cache.js'; @ApiTags('contracts') export class ContractsApi { //#region Common contract endpoints + + /** + * Get all contracts + */ @Get() - @ApiBearerAuth() - @ApiExtraModels(ContractDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_CONTRACT_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER + ) @ApiOperation({ summary: 'Return a list of all contracts.', description: 'Returns all contracts.', @@ -55,8 +30,7 @@ export class ContractsApi { @ApiQuery({ name: 'pageIndex', type: Number, - description: - 'The number of pages to skip before starting to collect the result set', + description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0, }) @@ -77,107 +51,87 @@ export class ContractsApi { @ApiOkResponse({ description: 'Contracts.', isArray: true, - headers: { - 'x-total-count': { - schema: { - type: 'integer', - }, - description: 'Total items in the collection.', - }, - }, + headers: pageHeader, type: ContractDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(ContractDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getContracts(@Req() req, @Response() res): Promise { - await checkPermission( - UserRole.STANDARD_REGISTRY, - UserRole.USER - )(req.user); + async getContracts( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('type') type?: ContractType, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); const [contracts, count] = await guardians.getContracts( - user.parent || user.did, - req.query.type as any, - req.query.pageIndex as any, - req.query.pageSize as any + owner, + type, + pageIndex, + pageSize ); - return res.setHeader('X-Total-Count', count).json(contracts); + return res.header('X-Total-Count', count).send(contracts); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Create new smart-contract + */ @Post('/') - @ApiBearerAuth() - @ApiExtraModels(ContractDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_CONTRACT_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Create contract.', - description: - 'Create smart-contract. Only users with the Standard Registry role are allowed to make the request.', + description: 'Create smart-contract. Only users with the Standard Registry role are allowed to make the request.', }) @ApiBody({ - schema: { - type: 'object', - properties: { - description: { - type: 'string', - }, - }, - }, + type: ContractConfigDTO, }) @ApiCreatedResponse({ description: 'Created contract.', type: ContractDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(ContractDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async createContract(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async createContract( + @AuthUser() user: IAuthUser, + @Body() body: ContractConfigDTO + ): Promise { try { - const user = req.user; - const { description, type } = req.body; + const owner = new EntityOwner(user); + const { description, type } = body; const guardians = new Guardians(); - return await guardians.createContract(user.did, description, type); + return await guardians.createContract(owner, description, type); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Import new smart-contract + */ @Post('/import') - @ApiBearerAuth() - @ApiExtraModels(ContractDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_CONTRACT_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Import contract.', - description: - 'Import smart-contract. Only users with the Standard Registry role are allowed to make the request.', + description: 'Import smart-contract. Only users with the Standard Registry role are allowed to make the request.', }) @ApiBody({ schema: { @@ -199,47 +153,37 @@ export class ContractsApi { description: 'Imported contract.', type: ContractDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(ContractDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async importContract(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async importContract( + @AuthUser() user: IAuthUser, + @Body() body: any + ): Promise { try { - const user = req.user; - const { contractId, description } = req.body; + const owner = new EntityOwner(user); + const { contractId, description } = body; const guardians = new Guardians(); - return await guardians.importContract( - user.did, - contractId, - description - ); + return await guardians.importContract(owner, contractId, description); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } /** - * @param req + * Get contract permissions */ @Get('/:contractId/permissions') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_PERMISSIONS_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Get contract permissions.', - description: - 'Get smart-contract permissions. Only users with the Standard Registry role are allowed to make the request.', + description: 'Get smart-contract permissions. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -252,43 +196,37 @@ export class ContractsApi { description: 'Contract permissions.', type: Number, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(InternalServerErrorDTO) @UseCache() - async contractPermissions(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @HttpCode(HttpStatus.OK) + async contractPermissions( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return await guardians.checkContractPermissions( - user.did, - req.params.contractId - ); + return await guardians.checkContractPermissions(owner, contractId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Remove contract + */ @Delete('/:contractId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_CONTRACT_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Remove contract.', - description: - 'Remove smart-contract. Only users with the Standard Registry role are allowed to make the request.', + description: 'Remove smart-contract. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -301,56 +239,43 @@ export class ContractsApi { description: 'Successful operation.', type: Boolean, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async removeContract(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async removeContract( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.removeContract( - user?.did, - req.params?.contractId as string - ) - ); + return await guardians.removeContract(owner, contractId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } //#endregion //#region Wipe contract endpoints /** - * @param req - * @param res + * Get list of all wipe requests */ @Get('/wipe/requests') - @ApiBearerAuth() - @ApiExtraModels(ContractDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_REQUEST_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return a list of all wipe requests.', - description: - 'Returns all wipe requests. Only users with the Standard Registry role are allowed to make the request.', + description: 'Returns all wipe requests. Only users with the Standard Registry role are allowed to make the request.', }) @ApiQuery({ name: 'pageIndex', type: Number, - description: - 'The number of pages to skip before starting to collect the result set', + description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0, }) @@ -371,155 +296,133 @@ export class ContractsApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - type: 'integer', - }, - description: 'Total items in the collection.', - }, - }, + headers: pageHeader, type: WiperRequestDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) - @HttpCode(HttpStatus.OK) // @UseCache({ isExpress: true }) - async getWipeRequests(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @ApiExtraModels(ContractDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getWipeRequests( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('contractId') contractId?: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); const [contracts, count] = await guardians.getWipeRequests( - user.parent || user.did, - req.query.contractId as any, - req.query.pageIndex as any, - req.query.pageSize as any + owner, + contractId, + pageIndex, + pageSize ); - res.locals.data = contracts - return res.setHeader('X-Total-Count', count).json(contracts); + return res.header('X-Total-Count', count).send(contracts); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Enable wipe requests + */ @Post('/wipe/:contractId/requests/enable') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_REQUEST_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Enable wipe requests.', - description: - 'Enable wipe contract requests. Only users with the Standard Registry role are allowed to make the request.', + description: 'Enable wipe contract requests. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', type: String, + required: true, description: 'Contract identifier', - required: false, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async enableWipeRequests(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async enableWipeRequests( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.enableWipeRequests( - user.did, - req.params.contractId - ) - ); + return await guardians.enableWipeRequests(owner, contractId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Disable wipe requests + */ @Post('/wipe/:contractId/requests/disable') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_REQUEST_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Disable wipe requests.', - description: - 'Disable wipe contract requests. Only users with the Standard Registry role are allowed to make the request.', + description: 'Disable wipe contract requests. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', type: String, + required: true, description: 'Contract identifier', - required: false, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async disableWipeRequests(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async disableWipeRequests( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.disableWipeRequests( - user.did, - req.params.contractId - ) - ); + return await guardians.disableWipeRequests(owner, contractId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Approve wipe request + */ @Post('/wipe/requests/:requestId/approve') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_REQUEST_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Approve wipe request.', - description: - 'Approve wipe contract request. Only users with the Standard Registry role are allowed to make the request.', + description: 'Approve wipe contract request. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'requestId', @@ -530,45 +433,38 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async approveWipeRequest(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async approveWipeRequest( + @AuthUser() user: IAuthUser, + @Param('requestId') requestId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.approveWipeRequest( - user.did, - req.params.requestId - ) - ); + return await guardians.approveWipeRequest(owner, requestId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Reject wipe request + */ @Delete('/wipe/requests/:requestId/reject') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_REQUEST_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Reject wipe request.', - description: - 'Reject wipe contract request. Only users with the Standard Registry role are allowed to make the request.', + description: 'Reject wipe contract request. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'requestId', @@ -582,49 +478,47 @@ export class ContractsApi { type: Boolean, description: 'Reject and ban', required: false, + example: true }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async rejectWipeRequest(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async rejectWipeRequest( + @AuthUser() user: IAuthUser, + @Param('requestId') requestId: string, + @Query('ban') ban?: boolean, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.rejectWipeRequest( - user.did, - req.params.requestId, - req.query.ban?.toLowerCase() === 'true' - ) + return await guardians.rejectWipeRequest( + owner, + requestId, + String(ban).toLowerCase() === 'true' ); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Remove all wipe requests + */ @Delete('/wipe/:contractId/requests') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_REQUEST_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Clear wipe requests.', - description: - 'Clear wipe contract requests. Only users with the Standard Registry role are allowed to make the request.', + description: 'Clear wipe contract requests. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -635,102 +529,88 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async clearWipeRequests(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async clearWipeRequests( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.clearWipeRequests( - user.did, - req.params.contractId - ) - ); + return await guardians.clearWipeRequests(owner, contractId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Add wipe admin + */ @Post('/wipe/:contractId/admin/:hederaId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_ADMIN_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Add wipe admin.', - description: - 'Add wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', + description: 'Add wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', - type: String, description: 'Contract identifier', + type: String, required: true, example: '652745597a7b53526de37c05', }) @ApiParam({ name: 'hederaId', - type: String, description: 'Hedera identifier', + type: String, required: true, example: '0.0.1', }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async wipeAddAdmin(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async wipeAddAdmin( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Param('hederaId') hederaId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.addWipeAdmin( - user.did, - req.params.contractId, - req.params.hederaId - ) - ); + return await guardians.addWipeAdmin(owner, contractId, hederaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Remove wipe admin + */ @Delete('/wipe/:contractId/admin/:hederaId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_ADMIN_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Remove wipe admin.', - description: - 'Remove wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', + description: 'Remove wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -748,46 +628,39 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async wipeRemoveAdmin(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async wipeRemoveAdmin( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Param('hederaId') hederaId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.removeWipeAdmin( - user.did, - req.params.contractId, - req.params.hederaId - ) - ); + return await guardians.removeWipeAdmin(owner, contractId, hederaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Add wipe manager + */ @Post('/wipe/:contractId/manager/:hederaId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_MANAGER_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Add wipe manager.', - description: - 'Add wipe contract manager. Only users with the Standard Registry role are allowed to make the request.', + description: 'Add wipe contract manager. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -805,46 +678,39 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async wipeAddManager(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async wipeAddManager( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Param('hederaId') hederaId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.addWipeManager( - user.did, - req.params.contractId, - req.params.hederaId - ) - ); + return await guardians.addWipeManager(owner, contractId, hederaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Remove wipe manager + */ @Delete('/wipe/:contractId/manager/:hederaId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPE_MANAGER_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Remove wipe manager.', - description: - 'Remove wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', + description: 'Remove wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -862,46 +728,39 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async wipeRemoveManager(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async wipeRemoveManager( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Param('hederaId') hederaId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.removeWipeManager( - user.did, - req.params.contractId, - req.params.hederaId - ) - ); + return await guardians.removeWipeManager(owner, contractId, hederaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Add wipe wiper + */ @Post('/wipe/:contractId/wiper/:hederaId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPER_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Add wipe wiper.', - description: - 'Add wipe contract wiper. Only users with the Standard Registry role are allowed to make the request.', + description: 'Add wipe contract wiper. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -919,46 +778,39 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async wipeAddWiper(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async wipeAddWiper( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Param('hederaId') hederaId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.addWipeWiper( - user.did, - req.params.contractId, - req.params.hederaId - ) - ); + return await guardians.addWipeWiper(owner, contractId, hederaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Remove wipe wiper + */ @Delete('/wipe/:contractId/wiper/:hederaId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_WIPER_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Remove wipe wiper.', - description: - 'Remove wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', + description: 'Remove wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -976,96 +828,82 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async wipeRemoveWiper(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async wipeRemoveWiper( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Param('hederaId') hederaId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.removeWipeWiper( - user.did, - req.params.contractId, - req.params.hederaId - ) - ); + return await guardians.removeWipeWiper(owner, contractId, hederaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } //#endregion //#region Retire contract endpoints + /** + * Sync retire contract pools + */ @Post('/retire/:contractId/pools/sync') - @ApiBearerAuth() - @ApiExtraModels(RetireRequestDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_POOL_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Sync retire pools.', - description: - 'Sync retire contract pools. Only users with the Standard Registry role are allowed to make the request.', + description: 'Sync retire contract pools. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', type: String, + required: true, description: 'Contract identifier', - required: false, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Sync date.', type: Date, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(RetireRequestDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async retireSyncPools(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async retireSyncPools( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.syncRetirePools(user.did, req.params.contractId) - ); + return await guardians.syncRetirePools(owner, contractId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } /** - * @param req - * @param res + * Get list of all retire requests */ @Get('/retire/requests') - @ApiBearerAuth() - @ApiExtraModels(RetireRequestDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_RETIRE_REQUEST_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER + ) @ApiOperation({ summary: 'Return a list of all retire requests.', description: 'Returns all retire requests.', @@ -1073,8 +911,7 @@ export class ContractsApi { @ApiQuery({ name: 'pageIndex', type: Number, - description: - 'The number of pages to skip before starting to collect the result set', + description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0, }) @@ -1095,60 +932,47 @@ export class ContractsApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - type: 'integer', - }, - description: 'Total items in the collection.', - }, - }, + headers: pageHeader, type: RetireRequestDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(RetireRequestDTO, InternalServerErrorDTO) // @UseCache({ isExpress: true }) - async getRetireRequests(@Req() req, @Response() res): Promise { - await checkPermission( - UserRole.STANDARD_REGISTRY, - UserRole.USER - )(req.user); + @HttpCode(HttpStatus.OK) + async getRetireRequests( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('contractId') contractId?: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); const [contracts, count] = await guardians.getRetireRequests( - user.did, - req.query.contractId as any, - req.query.pageIndex as any, - req.query.pageSize as any + owner, + contractId, + pageIndex, + pageSize ); - res.locals.data = contracts - return res.setHeader('X-Total-Count', count).json(contracts); + return res.header('X-Total-Count', count).send(contracts); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } /** - * @param req - * @param res + * Get list of all retire pools */ @Get('/retire/pools') - @ApiBearerAuth() - @ApiExtraModels(RetirePoolDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_POOL_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER + ) @ApiOperation({ summary: 'Return a list of all retire pools.', description: 'Returns all retire pools.', @@ -1156,8 +980,7 @@ export class ContractsApi { @ApiQuery({ name: 'pageIndex', type: Number, - description: - 'The number of pages to skip before starting to collect the result set', + description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0, }) @@ -1185,161 +1008,135 @@ export class ContractsApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - type: 'integer', - }, - description: 'Total items in the collection.', - }, - }, + headers: pageHeader, type: RetirePoolDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(RetirePoolDTO, InternalServerErrorDTO) // @UseCache({ isExpress: true }) - async getRetirePools(@Req() req, @Response() res): Promise { - await checkPermission( - UserRole.STANDARD_REGISTRY, - UserRole.USER - )(req.user); + @HttpCode(HttpStatus.OK) + async getRetirePools( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('contractId') contractId?: string, + @Query('tokens') tokens?: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); const [contracts, count] = await guardians.getRetirePools( - user.did, - req.query.tokens?.split(','), - req.query.contractId as any, - req.query.pageIndex as any, - req.query.pageSize as any + owner, + tokens?.split(','), + contractId, + pageIndex, + pageSize ); - res.locals.data = contracts - return res.setHeader('X-Total-Count', count).json(contracts); + return res.header('X-Total-Count', count).send(contracts); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Remove retire requests. + */ @Delete('/retire/:contractId/requests') - @ApiBearerAuth() - @ApiExtraModels(RetireRequestDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_RETIRE_REQUEST_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Clear retire requests.', - description: - 'Clear retire contract requests. Only users with the Standard Registry role are allowed to make the request.', + description: 'Clear retire contract requests. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', type: String, + required: true, description: 'Contract identifier', - required: false, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Successful operation.', type: Boolean, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(RetireRequestDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async clearRetireRequests(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async clearRetireRequests( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.clearRetireRequests( - user.did, - req.params.contractId - ) - ); + return await guardians.clearRetireRequests(owner, contractId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Clear retire pools. + */ @Delete('/retire/:contractId/pools') - @ApiBearerAuth() - @ApiExtraModels(RetireRequestDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_POOL_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Clear retire pools.', - description: - 'Clear retire contract pools. Only users with the Standard Registry role are allowed to make the request.', + description: 'Clear retire contract pools. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', type: String, + required: true, description: 'Contract identifier', - required: false, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Successful operation.', type: Boolean, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(RetireRequestDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async clearRetirePools(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async clearRetirePools( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.clearRetirePools( - user.did, - req.params.contractId - ) - ); + return await guardians.clearRetirePools(owner, contractId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Set retire pool. + */ @Post('/retire/:contractId/pools') - @ApiBearerAuth() - @ApiExtraModels(RetirePoolDTO, RetirePoolTokenDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_POOL_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Set retire pool.', - description: - 'Set retire contract pool. Only users with the Standard Registry role are allowed to make the request.', + description: 'Set retire contract pool. Only users with the Standard Registry role are allowed to make the request.', }) @ApiBody({ type: RetirePoolTokenDTO, @@ -1348,145 +1145,126 @@ export class ContractsApi { name: 'contractId', type: String, description: 'Contract identifier', - required: false, + required: true, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Successful operation.', type: RetirePoolDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(RetirePoolDTO, RetirePoolTokenDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setRetirePool(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async setRetirePool( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Body() body: any + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.setRetirePool( - user.did, - req.params.contractId, - req.body - ) - ); + return await guardians.setRetirePool(owner, contractId, body); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Unset retire pool. + */ @Delete('/retire/pools/:poolId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_POOL_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Unset retire pool.', - description: - 'Unset retire contract pool. Only users with the Standard Registry role are allowed to make the request.', + description: 'Unset retire contract pool. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'poolId', type: String, description: 'Pool Identifier', - required: false, + required: true, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Successful operation.', type: Boolean, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async unsetRetirePool(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async unsetRetirePool( + @AuthUser() user: IAuthUser, + @Param('poolId') poolId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.unsetRetirePool(user.did, req.params.poolId) - ); + return await guardians.unsetRetirePool(owner, poolId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Unset retire request. + */ @Delete('/retire/requests/:requestId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_RETIRE_REQUEST_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Unset retire request.', - description: - 'Unset retire contract request. Only users with the Standard Registry role are allowed to make the request.', + description: 'Unset retire contract request. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'requestId', type: String, description: 'Request Identifier', - required: false, + required: true, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Successful operation.', type: Boolean, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async unsetRetireRequest(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async unsetRetireRequest( + @AuthUser() user: IAuthUser, + @Param('requestId') requestId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.unsetRetireRequest( - user.did, - req.params.requestId - ) - ); + return await guardians.unsetRetireRequest(owner, requestId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Retire tokens. + */ @Post('/retire/pools/:poolId/retire') - @ApiBearerAuth() - @ApiExtraModels(RetireRequestTokenDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_RETIRE_REQUEST_CREATE, + //???? UserRole.STANDARD_REGISTRY, + // UserRole.USER + ) @ApiOperation({ summary: 'Retire tokens.', description: 'Retire tokens.', @@ -1498,51 +1276,44 @@ export class ContractsApi { name: 'poolId', type: String, description: 'Pool Identifier', - required: false, + required: true, example: '652745597a7b53526de37c05', }) @ApiOkResponse({ description: 'Successful operation.', type: Boolean, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(RetireRequestTokenDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async retire(@Req() req, @Response() res): Promise { - await checkPermission( - UserRole.STANDARD_REGISTRY, - UserRole.USER - )(req.user); + async retire( + @AuthUser() user: IAuthUser, + @Param('poolId') poolId: string, + @Body() body: any + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.retire(user.did, req.params.poolId, req.body) - ); + return await guardians.retire(owner, poolId, body); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Approve retire request + */ @Post('/retire/requests/:requestId/approve') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_RETIRE_REQUEST_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Approve retire request.', - description: - 'Approve retire contract request. Only users with the Standard Registry role are allowed to make the request.', + description: 'Approve retire contract request. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'requestId', @@ -1553,38 +1324,36 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async approveRetire(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async approveRetire( + @AuthUser() user: IAuthUser, + @Param('requestId') requestId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.approveRetire(user.did, req.params.requestId) - ); + return await guardians.approveRetire(owner, requestId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Cancel retire request. + */ @Delete('/retire/requests/:requestId/cancel') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_RETIRE_REQUEST_CREATE, + //???? UserRole.STANDARD_REGISTRY, + // UserRole.USER + ) @ApiOperation({ summary: 'Cancel retire request.', description: 'Cancel retire contract request.', @@ -1598,45 +1367,38 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async cancelRetireRequest(@Req() req, @Response() res): Promise { - await checkPermission( - UserRole.STANDARD_REGISTRY, - UserRole.USER - )(req.user); + async cancelRetireRequest( + @AuthUser() user: IAuthUser, + @Param('requestId') requestId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.cancelRetire(user.did, req.params.requestId) - ); + return await guardians.cancelRetire(owner, requestId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Add retire admin. + */ @Post('/retire/:contractId/admin/:hederaId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_RETIRE_ADMIN_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Add retire admin.', - description: - 'Add retire contract admin. Only users with the Standard Registry role are allowed to make the request.', + description: 'Add retire contract admin. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -1654,46 +1416,39 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async retireAddAdmin(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async retireAddAdmin( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Param('hederaId') hederaId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.addRetireAdmin( - user.did, - req.params.contractId, - req.params.hederaId - ) - ); + return await guardians.addRetireAdmin(owner, contractId, hederaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Remove wipe admin. + */ @Delete('/retire/:contractId/admin/:hederaId') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_RETIRE_ADMIN_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Remove wipe admin.', - description: - 'Remove wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', + description: 'Remove wipe contract admin. Only users with the Standard Registry role are allowed to make the request.', }) @ApiParam({ name: 'contractId', @@ -1711,46 +1466,37 @@ export class ContractsApi { }) @ApiOkResponse({ description: 'Successful operation.', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async retireRemoveAdmin(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async retireRemoveAdmin( + @AuthUser() user: IAuthUser, + @Param('contractId') contractId: string, + @Param('hederaId') hederaId: string + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.json( - await guardians.removeRetireAdmin( - user.did, - req.params.contractId, - req.params.hederaId - ) - ); + return await guardians.removeRetireAdmin(owner, contractId, hederaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } /** - * @param req - * @param res + * Get a list of all retire vcs */ @Get('/retire') - @ApiBearerAuth() - @ApiExtraModels(RetirePoolDTO, InternalServerErrorDTO) + @Auth( + Permissions.CONTRACTS_DOCUMENT_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER + ) @ApiOperation({ summary: 'Return a list of all retire vcs.', description: 'Returns all retire vcs.', @@ -1758,8 +1504,7 @@ export class ContractsApi { @ApiQuery({ name: 'pageIndex', type: Number, - description: - 'The number of pages to skip before starting to collect the result set', + description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0, }) @@ -1773,49 +1518,34 @@ export class ContractsApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - type: 'integer', - }, - description: 'Total items in the collection.', - }, - }, - type: 'object', - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + headers: pageHeader, + schema: { + type: 'array', + items: { + type: 'object' + } + } }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(RetirePoolDTO, InternalServerErrorDTO) // @UseCache({ isExpress: true }) - async getRetireVCs(@Req() req, @Response() res): Promise { - await checkPermission( - UserRole.STANDARD_REGISTRY, - UserRole.USER - )(req.user); + @HttpCode(HttpStatus.OK) + async getRetireVCs( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - const [vcs, count] = await guardians.getRetireVCs( - user.did, - req.query.pageIndex as any, - req.query.pageSize as any - ); - res.locals.data = vcs - return res.setHeader('X-Total-Count', count).json(vcs); + const [vcs, count] = await guardians.getRetireVCs(owner, pageIndex, pageSize); + return res.header('X-Total-Count', count).send(vcs); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } //#endregion diff --git a/api-gateway/src/api/service/demo.ts b/api-gateway/src/api/service/demo.ts index 81c584950a..031fb7e82f 100644 --- a/api-gateway/src/api/service/demo.ts +++ b/api-gateway/src/api/service/demo.ts @@ -1,33 +1,33 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { Users } from '../../helpers/users.js'; import { Logger, RunFunctionAsync } from '@guardian/common'; -import { TaskManager } from '../../helpers/task-manager.js'; -import { ServiceError } from '../../helpers/service-requests-base.js'; -import { Controller, Get, HttpCode, HttpException, HttpStatus } from '@nestjs/common'; -import { ApiOkResponse, ApiOperation, ApiTags, getSchemaPath } from '@nestjs/swagger'; -import { TaskAction, UserRole } from '@guardian/interfaces'; -import { RegisteredUsersDTO } from '../../middlewares/validation/schemas/index.js'; -import { AuthUser } from '../../auth/authorization-helper.js'; -import { Auth } from '../../auth/auth.decorator.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { Controller, Get, HttpCode, HttpStatus } from '@nestjs/common'; +import { ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { Permissions, TaskAction } from '@guardian/interfaces'; +import { InternalServerErrorDTO, RegisteredUsersDTO, TaskDTO } from '#middlewares'; +import { AuthUser, Auth } from '#auth'; +import { ServiceError, NewTask, TaskManager, Users, Guardians, UseCache, InternalException } from '#helpers'; @Controller('demo') @ApiTags('demo') export class DemoApi { + /** + * Returns list of registered users + */ + @Get('/registered-users') @ApiOperation({ summary: 'Returns list of registered users.', description: 'Returns list of registered users.', }) - // @ApiExtraModels(AccountsSessionResponseDTO, InternalServerErrorDTO) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(RegisteredUsersDTO), - }, + type: RegisteredUsersDTO }) - @Get('/registered-users') - @HttpCode(HttpStatus.OK) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(RegisteredUsersDTO, InternalServerErrorDTO) @UseCache() + @HttpCode(HttpStatus.OK) async registeredUsers(): Promise { const users = new Users(); const guardians = new Guardians(); @@ -44,26 +44,43 @@ export class DemoApi { return demoUsers } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Generate demo key + */ @Get('/random-key') @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR + Permissions.DEMO_KEY_CREATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR ) + @ApiOperation({ + summary: 'Generate demo key.', + description: 'Generate demo key.', + }) + @ApiOkResponse({ + description: 'Successful operation.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async randomKey(@AuthUser() user: any): Promise { + async randomKey( + @AuthUser() user: any + ): Promise { try { const guardians = new Guardians(); const role = user?.role; return await guardians.generateDemoKey(role); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR) + await InternalException(error); } // try { // const guardians = new Guardians(); @@ -87,14 +104,33 @@ export class DemoApi { // } } + /** + * Generate demo key (async) + */ @Get('/push/random-key') @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR + Permissions.DEMO_KEY_CREATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR ) + @ApiOperation({ + summary: 'Generate demo key.', + description: 'Generate demo key.', + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async pushRandomKey(@AuthUser() user: any): Promise { + async pushRandomKey( + @AuthUser() user: any + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.CREATE_RANDOM_KEY, user?.id); RunFunctionAsync(async () => { @@ -104,8 +140,6 @@ export class DemoApi { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return task; } - } diff --git a/api-gateway/src/api/service/external.ts b/api-gateway/src/api/service/external.ts index be1e952428..d3484d8c13 100644 --- a/api-gateway/src/api/service/external.ts +++ b/api-gateway/src/api/service/external.ts @@ -1,60 +1,41 @@ -import { PolicyEngine } from '../../helpers/policy-engine.js'; -import { Logger } from '@guardian/common'; -import { Controller, HttpCode, HttpStatus, Post, Req, Response } from '@nestjs/common'; -import { ApiBody, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, getSchemaPath } from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; +import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common'; +import { ApiExtraModels, ApiBody, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { InternalServerErrorDTO, ExternalDocumentDTO } from '#middlewares'; +import { PolicyEngine, InternalException } from '#helpers'; @Controller('external') @ApiTags('external') export class ExternalApi { + /** + * Sends data from an external source + */ + @Post('/') @ApiOperation({ summary: 'Sends data from an external source.', description: 'Sends data from an external source.', }) @ApiBody({ description: 'Object that contains a VC Document.', - schema: { - 'type': 'object', - 'required': [ - 'owner', - 'policyTag', - 'document' - ], - 'properties': { - 'owner': { - 'type': 'string' - }, - 'policyTag': { - 'type': 'string' - }, - 'document': { - 'type': 'object' - } - } - } + type: ExternalDocumentDTO }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'boolean' - } + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO }) - @Post('/') + @ApiExtraModels(ExternalDocumentDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async receiveExternalData(@Req() req, @Response() res): Promise { - const engineService = new PolicyEngine(); - + async receiveExternalData( + @Body() document: ExternalDocumentDTO + ): Promise { try { - return res.send(await engineService.receiveExternalData(req.body)); + const engineService = new PolicyEngine(); + return await engineService.receiveExternalData(document); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/ipfs.ts b/api-gateway/src/api/service/ipfs.ts index bc78b0ba5a..63cf928998 100644 --- a/api-gateway/src/api/service/ipfs.ts +++ b/api-gateway/src/api/service/ipfs.ts @@ -1,142 +1,209 @@ -import { Logger } from '@guardian/common'; -import { Guardians } from '../../helpers/guardians.js'; -import { Body, Controller, Get, HttpCode, HttpException, HttpStatus, Param, Post, Req, Response } from '@nestjs/common'; -import { ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger'; -import { Auth } from '../../auth/auth.decorator.js'; -import { UserRole } from '@guardian/interfaces'; -import { CACHE } from '../../constants/index.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { Body, Controller, Get, HttpCode, HttpException, HttpStatus, Param, Post, StreamableFile } from '@nestjs/common'; +import { ApiBody, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'; +import { Permissions } from '@guardian/interfaces'; +import { Auth } from '#auth'; +import { Examples, InternalServerErrorDTO } from '#middlewares'; +import { Guardians, InternalException } from '#helpers'; @Controller('ipfs') @ApiTags('ipfs') export class IpfsApi { + /** + * Add file from ipfs + */ + @Post('/file') + @Auth( + Permissions.IPFS_FILE_CREATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR + ) @ApiOperation({ summary: 'Add file from ipfs.', description: 'Add file from ipfs.', }) - @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR - ) - @Post('/file') + @ApiBody({ + description: 'Binary data.', + required: true, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: String + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async postFile(@Body() body: any): Promise { + async postFile( + @Body() body: any + ): Promise { try { if (!Object.values(body).length) { throw new HttpException('Body content in request is empty', HttpStatus.UNPROCESSABLE_ENTITY) } const guardians = new Guardians(); - const {cid} = await guardians.addFileIpfs(body); + const { cid } = await guardians.addFileIpfs(body); if (!cid) { throw new HttpException('File is not uploaded', HttpStatus.BAD_REQUEST); } return JSON.stringify(cid); } catch (error) { - new Logger().error(error.message, ['API_GATEWAY']); - throw error; + await InternalException(error); } } /** - * @param body - * @param policyId + * Add file from ipfs for dry run mode */ + @Post('/file/dry-run/:policyId') + @Auth( + Permissions.IPFS_FILE_CREATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR + ) @ApiOperation({ summary: 'Add file from ipfs for dry run mode.', description: 'Add file from ipfs for dry run mode.', }) - @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR - ) - @Post('/file/dry-run/:policyId') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy id', + required: true, + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Binary data.', + required: true, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: String + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async postFileDryRun(@Body() body: any, @Param('policyId') policyId: any): Promise { + async postFileDryRun( + @Param('policyId') policyId: string, + @Body() body: any + ): Promise { try { if (!Object.values(body).length) { throw new HttpException('Body content in request is empty', HttpStatus.UNPROCESSABLE_ENTITY) } const guardians = new Guardians(); - const {cid} = await guardians.addFileToDryRunStorage(body, policyId); + const { cid } = await guardians.addFileToDryRunStorage(body, policyId); return JSON.stringify(cid); } catch (error) { - new Logger().error(error.message, ['API_GATEWAY']); - throw error; + await InternalException(error); } } /** - * @param req - * @param res + * Get file */ + @Get('/file/:cid') + @Auth( + Permissions.IPFS_FILE_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR + ) @ApiOperation({ summary: 'Get file from ipfs.', description: 'Get file from ipfs.', }) - @ApiSecurity('bearerAuth') - @Get('/file/:cid') + @ApiParam({ + name: 'cid', + type: String, + description: 'File cid', + required: true, + }) + @ApiOkResponse({ + description: 'Successful operation.', + schema: { + type: 'string', + format: 'binary' + }, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) + // @UseCache({ ttl: CACHE.LONG_TTL }) @HttpCode(HttpStatus.OK) - @UseCache({ ttl: CACHE.LONG_TTL, isExpress: true }) - async getFile(@Req() req, @Response() res): Promise { - if (!req.user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); - } + async getFile( + @Param('cid') cid: string + ): Promise { try { const guardians = new Guardians(); - const result = await guardians.getFileIpfs(req.params.cid, 'raw'); + const result = await guardians.getFileIpfs(cid, 'raw'); if (result.type !== 'Buffer') { throw new HttpException('File is not found', HttpStatus.NOT_FOUND) } - const resultBuffer = Buffer.from(result); - res.writeHead(200, { - 'Content-Type': 'binary/octet-stream', - 'Content-Length': resultBuffer.length, - }); - return res.end(resultBuffer, 'binary'); + return new StreamableFile(Buffer.from(result)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } /** - * @param cid - * @param res + * Get file (dry run) */ + @Get('/file/:cid/dry-run') + @Auth( + Permissions.IPFS_FILE_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR + ) @ApiOperation({ summary: 'Get file from ipfs for dry run mode.', description: 'Get file from ipfs for dry run mode.', }) - @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR - ) - @Get('/file/:cid/dry-run') + @ApiParam({ + name: 'cid', + type: String, + description: 'File cid', + required: true, + }) + @ApiOkResponse({ + description: 'Successful operation.', + schema: { + type: 'string', + format: 'binary' + }, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) + // @UseCache({ ttl: CACHE.LONG_TTL }) @HttpCode(HttpStatus.OK) - @UseCache({ ttl: CACHE.LONG_TTL, isExpress: true }) - async getFileDryRun(@Param('cid') cid: string, @Response() res): Promise { + async getFileDryRun( + @Param('cid') cid: string + ): Promise { try { const guardians = new Guardians(); const result = await guardians.getFileFromDryRunStorage(cid, 'raw'); if (result.type !== 'Buffer') { throw new HttpException('File is not found', HttpStatus.NOT_FOUND) } - const resultBuffer = Buffer.from(result); - res.writeHead(200, { - 'Content-Type': 'binary/octet-stream', - 'Content-Length': resultBuffer.length, - }); - return res.end(resultBuffer, 'binary'); + return new StreamableFile(Buffer.from(result)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/logger.ts b/api-gateway/src/api/service/logger.ts index 3b13125e9a..515f97d4cf 100644 --- a/api-gateway/src/api/service/logger.ts +++ b/api-gateway/src/api/service/logger.ts @@ -1,11 +1,11 @@ -import { IPageParameters, MessageAPI, UserRole } from '@guardian/interfaces'; -import { Logger } from '@guardian/common'; -import { Controller, Get, HttpCode, HttpStatus, Inject, Injectable, Post, Req, Response } from '@nestjs/common'; +import { Body, Controller, Get, HttpCode, HttpStatus, Inject, Injectable, Post, Query } from '@nestjs/common'; +import { ApiTags, ApiBody, ApiOperation, ApiOkResponse, ApiInternalServerErrorResponse, ApiQuery, ApiExtraModels } from '@nestjs/swagger'; +import { IPageParameters, MessageAPI, Permissions } from '@guardian/interfaces'; import { ClientProxy } from '@nestjs/microservices'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { ApiTags } from '@nestjs/swagger'; +import { Auth } from '#auth'; +import { InternalServerErrorDTO, LogFilterDTO, LogResultDTO } from '#middlewares'; +import { UseCache, InternalException } from '#helpers'; import axios from 'axios'; -import { UseCache } from '../../helpers/decorators/cache.js'; @Injectable() export class LoggerService { @@ -33,68 +33,133 @@ export class LoggerApi { constructor(private readonly loggerService: LoggerService) { } + /** + * Get logs + */ @Post('/') + @Auth( + Permissions.LOG_LOG_READ, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Return a list of all logs.', + description: 'Return a list of all logs. Only users with the Standard Registry role are allowed to make the request.', + }) + @ApiBody({ + description: 'Filters.', + required: true, + type: LogFilterDTO + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: LogResultDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(LogFilterDTO, LogResultDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getLogs(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getLogs( + @Body() body: LogFilterDTO + ): Promise { try { const filters: any = {}; const pageParameters: IPageParameters = {}; - if (req.body.type) { - filters.type = req.body.type; + if (!body) { + body = {}; } - if (req.body.startDate && req.body.endDate) { - const sDate = new Date(req.body.startDate); + if (body.type) { + filters.type = body.type; + } + if (body.startDate && body.endDate) { + const sDate = new Date(body.startDate); sDate.setHours(0, 0, 0, 0); - const eDate = new Date(req.body.endDate); + const eDate = new Date(body.endDate); eDate.setHours(23, 59, 59, 999); filters.datetime = { $gte: sDate, $lt: eDate }; } - if (req.body.attributes && req.body.attributes.length !== 0) { - filters.attributes = { $in: req.body.attributes }; + if (body.attributes && body.attributes.length !== 0) { + filters.attributes = { $in: body.attributes }; } - if (req.body.message) { + if (body.message) { filters.message = { - $regex: `.*${escapeRegExp(req.body.message)}.*`, + $regex: `.*${escapeRegExp(body.message)}.*`, $options: 'i' } } - if (req.body.pageSize) { - pageParameters.offset = (req.body.pageIndex || 0) * req.body.pageSize; - pageParameters.limit = req.body.pageSize; + if (body.pageSize) { + pageParameters.offset = (body.pageIndex || 0) * body.pageSize; + pageParameters.limit = body.pageSize; } - const logsObj = await this.loggerService.getLogs(filters, pageParameters, req.body.sortDirection); + const logsObj = await this.loggerService.getLogs(filters, pageParameters, body.sortDirection); const logs = await axios.get(logsObj.directLink); - return res.send({ + return { totalCount: logsObj.totalCount, logs: logs.data - }); + }; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } /** - * @param req + * Get attributes */ @Get('attributes') - @HttpCode(HttpStatus.OK) + @Auth( + Permissions.LOG_LOG_READ, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Return a list of attributes.', + description: 'Return a list of attributes. Only users with the Standard Registry role are allowed to make the request.', + }) + @ApiQuery({ + name: 'name', + type: Number, + description: 'Name', + required: false, + example: 'Search' + }) + @ApiQuery({ + name: 'existingAttributes', + type: String, + isArray: true, + description: 'Existing attributes', + required: false, + example: ['WORKER'] + }) + @ApiOkResponse({ + description: 'Successful operation.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @UseCache() - async getAttributes(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @HttpCode(HttpStatus.OK) + async getAttributes( + @Query('name') name: string, + @Query('existingAttributes') existingAttributes: string | string[], + ): Promise { try { - if (req.query.existingAttributes && !Array.isArray(req.query.existingAttributes)) { - req.query.existingAttributes = [req.query.existingAttributes as string]; + let attributes: string[]; + if (existingAttributes) { + if (!Array.isArray(existingAttributes)) { + attributes = [existingAttributes as string]; + } else { + attributes = existingAttributes + } } - return await this.loggerService.getAttributes(escapeRegExp(req.query.name as string), req.query.existingAttributes as string[]); + return await this.loggerService.getAttributes(escapeRegExp(name), attributes); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } @@ -113,6 +178,5 @@ function escapeRegExp(text: string): string { if (!text) { return ''; } - return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); } diff --git a/api-gateway/src/api/service/map.ts b/api-gateway/src/api/service/map.ts index ceece1cbb1..47fd5bb765 100644 --- a/api-gateway/src/api/service/map.ts +++ b/api-gateway/src/api/service/map.ts @@ -1,24 +1,56 @@ -import { Guardians } from '../../helpers/guardians.js'; import { Controller, Get, HttpCode, HttpStatus } from '@nestjs/common'; -import { ApiTags } from '@nestjs/swagger'; +import { ApiExtraModels, ApiTags, ApiOperation, ApiOkResponse, ApiInternalServerErrorResponse } from '@nestjs/swagger'; import { CACHE } from '../../constants/index.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { UseCache, Guardians } from '#helpers'; +import { InternalServerErrorDTO } from '#middlewares'; @Controller('map') @ApiTags('map') export class MapApi { + /** + * Get map key + */ @Get('/key') + @ApiOperation({ + summary: 'Return map key.', + description: 'Return map key.', + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: String + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) @UseCache({ ttl: CACHE.LONG_TTL }) - async getKey() { + async getKey(): Promise { const guardians = new Guardians(); return await guardians.getMapApiKey(); } + /** + * Get map sh + */ @Get('/sh') + @ApiOperation({ + summary: 'Return map key.', + description: 'Return map key.', + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: String + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) @UseCache({ ttl: CACHE.LONG_TTL }) - async getSentinelKey() { + async getSentinelKey(): Promise { const guardians = new Guardians(); return await guardians.getSentinelApiKey(); } diff --git a/api-gateway/src/api/service/metrics.ts b/api-gateway/src/api/service/metrics.ts index fb4c43ff47..4abf0d1481 100644 --- a/api-gateway/src/api/service/metrics.ts +++ b/api-gateway/src/api/service/metrics.ts @@ -8,7 +8,7 @@ export class MetricsApi { @Get('/') @HttpCode(HttpStatus.OK) async getMetrics(@Response() res) { - res.set('Content-Type', client.register.contentType); + res.header('Content-Type', client.register.contentType); return res.send(await client.register.metrics()); } } diff --git a/api-gateway/src/api/service/module.ts b/api-gateway/src/api/service/module.ts index 2b416f440d..b1d9f69d5d 100644 --- a/api-gateway/src/api/service/module.ts +++ b/api-gateway/src/api/service/module.ts @@ -1,658 +1,744 @@ -import { Logger } from '@guardian/common'; -import { Guardians } from '../../helpers/guardians.js'; -import { Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Post, Put, Query, Req, Res, Response } from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { SchemaCategory, SchemaHelper, UserRole } from '@guardian/interfaces'; -import { ApiForbiddenResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiSecurity, ApiTags, ApiUnauthorizedResponse, getSchemaPath } from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; -import { ApiImplicitQuery } from '@nestjs/swagger/dist/decorators/api-implicit-query.decorator.js'; -import { SchemaUtils } from '../../helpers/schema-utils.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { Logger, IAuthUser } from '@guardian/common'; +import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Query, Response } from '@nestjs/common'; +import { Permissions, SchemaCategory, SchemaHelper } from '@guardian/interfaces'; +import { ApiParam, ApiCreatedResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, ApiBody, ApiExtraModels, ApiQuery } from '@nestjs/swagger'; +import { AuthUser, Auth } from '#auth'; +import { ExportMessageDTO, ImportMessageDTO, ModuleDTO, ModulePreviewDTO, SchemaDTO, ModuleValidationDTO, Examples, pageHeader, InternalServerErrorDTO } from '#middlewares'; +import { Guardians, SchemaUtils, UseCache, InternalException, EntityOwner } from '#helpers'; + +const ONLY_SR = ' Only users with the Standard Registry role are allowed to make the request.' @Controller('modules') @ApiTags('modules') export class ModulesApi { + /** + * Creates a new module + */ + @Post('/') + @Auth( + Permissions.MODULES_MODULE_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new module.', - description: 'Creates a new module. Only users with the Standard Registry role are allowed to make the request.', + description: 'Creates a new module.' + ONLY_SR, + }) + @ApiBody({ + description: 'Module config.', + type: ModuleDTO, }) - @ApiSecurity('bearerAuth') @ApiOkResponse({ - description: 'Successful operation.' + description: 'Created module.', + type: ModuleDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/') + @ApiExtraModels(ModuleDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async postModules(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async postModules( + @AuthUser() user: IAuthUser, + @Body() body: ModuleDTO + ): Promise { try { const guardian = new Guardians(); - const module = req.body; + const module = body; if (!module.config || module.config.blockType !== 'module') { throw new HttpException('Invalid module config', HttpStatus.UNPROCESSABLE_ENTITY); } - const item = await guardian.createModule(module, req.user.did); - return res.status(201).json(item); + return await guardian.createModule(module, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get list of all modules + */ + @Get('/') + @Auth( + Permissions.MODULES_MODULE_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return a list of all modules.', - description: 'Returns all modules. Only users with the Standard Registry and Installer role are allowed to make the request.', - }) - @ApiSecurity('bearerAuth') - @ApiImplicitQuery({ - name: 'policyId', - type: String, - description: 'Policy identifier', - required: false + description: 'Returns all modules.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageIndex', type: Number, description: 'The number of pages to skip before starting to collect the result set', - required: false + required: false, + example: 0 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageSize', type: Number, description: 'The numbers of items to return', - required: false + required: false, + example: 20 }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object', - 'properties': { - 'id': { - 'type': 'string' - }, - 'uuid': { - 'type': 'string' - }, - 'name': { - 'type': 'string' - }, - 'description': { - 'type': 'string' - }, - 'config': { - 'type': 'object' - }, - 'status': { - 'type': 'string' - }, - 'creator': { - 'type': 'string' - }, - 'owner': { - 'type': 'string' - }, - 'topicId': { - 'type': 'string' - }, - 'messageId': { - 'type': 'string' - }, - 'codeVersion': { - 'type': 'string' - }, - 'createDate': { - 'type': 'string' - }, - 'type': { - 'type': 'string' - } - } - }, + isArray: true, + headers: pageHeader, + type: ModuleDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Get('/') + @ApiExtraModels(ModuleDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getModules(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getModules( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { try { - const guardians = new Guardians(); - - let pageIndex: any; - let pageSize: any; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } - const { items, count } = await guardians.getModule({ - owner: req.user.did, + const options: any = { pageIndex, pageSize - }); - return res.setHeader('X-Total-Count', count).json(items); + }; + const guardians = new Guardians(); + const { items, count } = await guardians.getModule(options, new EntityOwner(user)); + return res.header('X-Total-Count', count).send(items); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** - * @param req - * @param res - * @param pageIndex - * @param pageSize - * @param topicId + * Get list of all schemas */ @Get('/schemas') + @Auth( + Permissions.SCHEMAS_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Return a list of all module schemas.', + description: 'Returns all module schemas.' + ONLY_SR, + }) + @ApiQuery({ + name: 'topicId', + type: String, + description: 'Topic id', + required: false, + example: Examples.ACCOUNT_ID + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + headers: pageHeader, + type: SchemaDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) + // @UseCache({ isExpress: true }) @HttpCode(HttpStatus.OK) - @UseCache({ isExpress: true }) async getModuleSchemas( - @Req() req, - @Res() res, - @Query('pageIndex') pageIndex, - @Query('pageSize') pageSize, - @Query('topicId') topicId - ): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + @Query('topicId') topicId?: string, + ): Promise { try { - const user = req.user; const guardians = new Guardians(); - const owner = user.did; - + const owner = new EntityOwner(user); const { items, count } = await guardians.getSchemasByOwner({ category: SchemaCategory.MODULE, - owner, topicId, pageIndex, pageSize - }); + }, owner); items.forEach((s) => { - s.readonly = s.readonly || s.owner !== owner + s.readonly = s.readonly || s.owner !== owner.owner }); - res.locals.data = SchemaUtils.toOld(items) + // res.locals.data = SchemaUtils.toOld(items) return res - .setHeader('X-Total-Count', count) - .json(SchemaUtils.toOld(items)); + .header('X-Total-Count', count) + .send(SchemaUtils.toOld(items)); } catch (error) { await (new Logger()).error(error, ['API_GATEWAY']); - throw error; + throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); } } + /** + * Create schema + */ @Post('/schemas') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Creates a new module schema.', + description: 'Creates a new module schema.' + ONLY_SR, + }) + @ApiBody({ + description: 'Schema config.', + type: SchemaDTO, + }) + @ApiCreatedResponse({ + description: 'Created schema.', + type: SchemaDTO, + isArray: true, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async postSchemas(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async postSchemas( + @AuthUser() user: IAuthUser, + @Body() newSchema: SchemaDTO + ): Promise { try { - const user = req.user; - const newSchema = req.body; - if (!newSchema) { throw new HttpException('Schema does not exist.', HttpStatus.UNPROCESSABLE_ENTITY) } const guardians = new Guardians(); - const owner = user.did; - - SchemaUtils.fromOld(newSchema); - delete newSchema.version; - delete newSchema.id; - delete newSchema._id; - delete newSchema.status; - delete newSchema.topicId; + const owner = new EntityOwner(user); newSchema.category = SchemaCategory.MODULE; + SchemaUtils.fromOld(newSchema); + SchemaUtils.clearIds(newSchema); SchemaHelper.updateOwner(newSchema, owner); - const schema = await guardians.createSchema(newSchema); - return res.status(201).json(SchemaUtils.toOld(schema)); + const schemas = await guardians.createSchema(newSchema, owner); + + return SchemaUtils.toOld(schemas); } catch (error) { await (new Logger()).error(error, ['API_GATEWAY']); - throw error; + throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); } } + /** + * Remove module + */ + @Delete('/:uuid') + @Auth( + Permissions.MODULES_MODULE_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ - summary: 'Deletes the module with the provided module ID. Only users with the Standard Registry role are allowed to make the request.', - description: 'Deletes the module.' + summary: 'Deletes the module.', + description: 'Deletes the module with the provided module ID.' + ONLY_SR }) - @ApiSecurity('bearerAuth') - @Delete('/:uuid') + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Module Identifier', + example: Examples.UUID, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: Boolean, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async deleteModule(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async deleteModule( + @AuthUser() user: IAuthUser, + @Param('uuid') uuid: string, + ): Promise { try { const guardian = new Guardians(); - if (!req.params.uuid) { - throw new Error('Invalid uuid') + if (!uuid) { + throw new Error('Invalid uuid'); } - const result = await guardian.deleteModule(req.params.uuid, req.user.did); - return res.status(200).json(result); + return await guardian.deleteModule(uuid, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** - * @param req + * Get all modules */ + @Get('/menu') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + Permissions.MODULES_MODULE_UPDATE, + Permissions.TOOLS_TOOL_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return a list of modules.', - description: 'Returns modules menu. Only users with the Standard Registry and Installer role are allowed to make the request.' + description: 'Returns modules menu.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') @ApiOkResponse({ - schema: { - type: 'array' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + description: 'Modules.', + isArray: true, + type: ModuleDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Get('/menu') - @HttpCode(HttpStatus.OK) + @ApiExtraModels(ModuleDTO, InternalServerErrorDTO) @UseCache() - async getMenu(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @HttpCode(HttpStatus.OK) + async getMenu( + @AuthUser() user: IAuthUser, + ): Promise { try { const guardians = new Guardians(); - return await guardians.getMenuModule(req.user.did); + return await guardians.getMenuModule(new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** - * @param req - * @param res + * Retrieves module configuration */ + @Get('/:uuid') + @Auth( + Permissions.MODULES_MODULE_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Retrieves module configuration.', - description: 'Retrieves module configuration for the specified module ID. Only users with the Standard Registry role are allowed to make the request.' + description: 'Retrieves module configuration for the specified module ID.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Module Identifier', + example: Examples.UUID }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Successful operation.', + type: ModuleDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Get('/:uuid') + @ApiExtraModels(ModuleDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getModule(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getModule( + @AuthUser() user: IAuthUser, + @Param('uuid') uuid: string, + ): Promise { try { - const guardian = new Guardians(); - if (!req.params.uuid) { + if (!uuid) { throw new HttpException('Invalid uuid', HttpStatus.UNPROCESSABLE_ENTITY) } - const item = await guardian.getModuleById(req.params.uuid, req.user.did); - return res.json(item); + const guardian = new Guardians(); + return await guardian.getModuleById(uuid, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Updates module configuration + */ + @Put('/:uuid') + @Auth( + Permissions.MODULES_MODULE_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Updates module configuration.', - description: 'Updates module configuration for the specified module ID. Only users with the Standard Registry role are allowed to make the request.' + description: 'Updates module configuration for the specified module ID.' + ONLY_SR, }) - @ApiOkResponse({ - schema: { - type: 'object' - } + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Module Identifier', + example: Examples.UUID }) - @ApiSecurity('bearerAuth') - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'Module config.', + type: ModuleDTO, }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Successful operation.', + type: ModuleDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Put('/:uuid') + @ApiExtraModels(ModuleDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async putModule(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - if (!req.params.uuid) { + async putModule( + @AuthUser() user: IAuthUser, + @Param('uuid') uuid: string, + @Body() module: ModuleDTO + ): Promise { + if (!uuid) { throw new HttpException('Invalid uuid', HttpStatus.UNPROCESSABLE_ENTITY); } - const guardian = new Guardians(); - const module = req.body; if (!module.config || module.config.blockType !== 'module') { throw new HttpException('Invalid module config', HttpStatus.UNPROCESSABLE_ENTITY) } try { - const result = await guardian.updateModule(req.params.uuid, module, req.user.did); - return res.status(201).json(result); + const guardian = new Guardians(); + return await guardian.updateModule(uuid, module, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Export module + */ + @Get('/:uuid/export/file') + @Auth( + Permissions.MODULES_MODULE_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return module and its artifacts in a zip file format for the specified module.', - description: 'Returns a zip file containing the published module and all associated artifacts, i.e. schemas and VCs. Only users with the Standard Registry role are allowed to make the request.' + description: 'Returns a zip file containing the published module and all associated artifacts, i.e. schemas and VCs.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Module Identifier', + example: Examples.UUID }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'File.', }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Get('/:uuid/export/file') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async moduleExportFile(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async moduleExportFile( + @AuthUser() user: IAuthUser, + @Param('uuid') uuid: string, + @Response() res: any + ): Promise { try { - const file: any = await guardian.exportModuleFile(req.params.uuid, req.user.did); - res.setHeader('Content-disposition', `attachment; filename=module_${Date.now()}`); - res.setHeader('Content-type', 'application/zip'); + const guardian = new Guardians(); + const file: any = await guardian.exportModuleFile(uuid, new EntityOwner(user)); + res.header('Content-disposition', `attachment; filename=module_${Date.now()}`); + res.header('Content-type', 'application/zip'); return res.send(file); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Export module + */ + @Get('/:uuid/export/message') + @Auth( + Permissions.MODULES_MODULE_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return Heder message ID for the specified published module.', - description: 'Returns the Hedera message ID for the specified module published onto IPFS. Only users with the Standard Registry role are allowed to make the request.' + description: 'Returns the Hedera message ID for the specified module published onto IPFS.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Module Identifier', + example: Examples.UUID, }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Message.', + type: ExportMessageDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Get('/:uuid/export/message') + @ApiExtraModels(ExportMessageDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async moduleExportMessage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async moduleExportMessage( + @AuthUser() user: IAuthUser, + @Param('uuid') uuid: string + ): Promise { try { - return res.send(await guardian.exportModuleMessage(req.params.uuid, req.user.did)); + const guardian = new Guardians(); + return await guardian.exportModuleMessage(uuid, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Imports new module from IPFS + */ + @Post('/import/message') + @Auth( + Permissions.MODULES_MODULE_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new module from IPFS.', - description: 'Imports new module and all associated artifacts from IPFS into the local DB. Only users with the Standard Registry role are allowed to make the request.' + description: 'Imports new module and all associated artifacts from IPFS into the local DB.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Created module.', + type: ModuleDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/import/message') + @ApiExtraModels(ImportMessageDTO, ModuleDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async moduleImportMessage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async moduleImportMessage( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } try { - const module = await guardian.importModuleMessage(req.body.messageId, req.user.did); - return res.status(201).send(module); + const guardian = new Guardians(); + return await guardian.importModuleMessage(messageId, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Imports new module from a zip file + */ + @Post('/import/file') + @Auth( + Permissions.MODULES_MODULE_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new module from a zip file.', - description: 'Imports new module and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB. Only users with the Standard Registry role are allowed to make the request.' + description: 'Imports new module and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'File.', }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Created module.', + type: ModuleDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/import/file') + @ApiExtraModels(ModuleDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async moduleImportFile(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async moduleImportFile( + @AuthUser() user: IAuthUser, + @Body() body: any + ): Promise { const guardian = new Guardians(); try { - const module = await guardian.importModuleFile(req.body, req.user.did); - return res.status(201).send(module); + return await guardian.importModuleFile(body, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Import preview + */ + @Post('/import/message/preview') + @Auth( + Permissions.MODULES_MODULE_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new module from IPFS.', - description: 'Imports new module and all associated artifacts from IPFS into the local DB. Only users with the Standard Registry role are allowed to make the request.' - }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } + description: 'Imports new module and all associated artifacts from IPFS into the local DB.' + ONLY_SR, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Module preview.', + type: ModulePreviewDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/import/message/preview') + @ApiExtraModels(ImportMessageDTO, ModulePreviewDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async moduleImportMessagePreview(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async moduleImportMessagePreview( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } try { - const module = await guardian.previewModuleMessage(req.body.messageId, req.user.did); - return res.send(module); + const guardian = new Guardians(); + return await guardian.previewModuleMessage(messageId, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Import preview + */ + @Post('/import/file/preview') + @Auth( + Permissions.MODULES_MODULE_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new module from a zip file.', - description: 'Imports new module and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB. Only users with the Standard Registry role are allowed to make the request.' - }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } + description: 'Imports new module and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'File.', }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Module preview.', + type: ModulePreviewDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/import/file/preview') + @ApiExtraModels(ModulePreviewDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async moduleImportFilePreview(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async moduleImportFilePreview( + @AuthUser() user: IAuthUser, + @Body() body: any + ): Promise { try { - const module = await guardian.previewModuleFile(req.body, req.user.did); - return res.send(module); + const guardian = new Guardians(); + return await guardian.previewModuleFile(body, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Publish module + */ + @Put('/:uuid/publish') + @Auth( + Permissions.MODULES_MODULE_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Publishes the module onto IPFS.', - description: 'Publishes the module with the specified (internal) module ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera topic. Only users with the Standard Registry role are allowed to make the request.' + description: 'Publishes the module with the specified (internal) module ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera topic.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Module Identifier', + example: Examples.UUID }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'Module.', + type: ModuleDTO, }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Successful operation.', + type: ModuleDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Put('/:uuid/publish') + @ApiExtraModels(ModuleDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async publishModule(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async publishModule( + @AuthUser() user: IAuthUser, + @Param('uuid') uuid: string, + @Body() module: ModuleDTO + ): Promise { try { - const module = await guardian.publishModule(req.params.uuid, req.user.did, req.body); - return res.json(module); + const guardian = new Guardians(); + return await guardian.publishModule(uuid, new EntityOwner(user), module); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Validates selected module + */ + @Post('/validate') + @Auth( + Permissions.MODULES_MODULE_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Validates selected module.', - description: 'Validates selected module. Only users with the Standard Registry role are allowed to make the request.' - }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - schema: { - type: 'object' - } + description: 'Validates selected module.' + ONLY_SR, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'Module config.', + type: ModuleDTO, }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Validation result.', + type: ModuleValidationDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/validate') + @ApiExtraModels(ModuleDTO, ModuleValidationDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async validateModule(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async validateModule( + @AuthUser() user: IAuthUser, + @Body() module: ModuleDTO + ): Promise { try { - return res.send(await guardian.validateModule(req.user.did, req.body)); + const guardian = new Guardians(); + return await guardian.validateModule(new EntityOwner(user), module); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/notifications.ts b/api-gateway/src/api/service/notifications.ts index 1ffa720cc7..9e3983a12b 100644 --- a/api-gateway/src/api/service/notifications.ts +++ b/api-gateway/src/api/service/notifications.ts @@ -1,235 +1,201 @@ -import { AuthGuard } from '../../auth/auth-guard.js'; -import { Logger, NotificationService } from '@guardian/common'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; -import { NotificationDTO, ProgressDTO, } from '../../middlewares/validation/schemas/notifications.js'; -import { Controller, Delete, Get, HttpCode, HttpStatus, Post, Req, Response, UseGuards, } from '@nestjs/common'; -import { ApiBearerAuth, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiParam, ApiSecurity, ApiTags, ApiUnauthorizedResponse, getSchemaPath, } from '@nestjs/swagger'; +import { IAuthUser, NotificationService } from '@guardian/common'; +import { Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Query, Response, } from '@nestjs/common'; +import { ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'; +import { Examples, InternalServerErrorDTO, NotificationDTO, ProgressDTO, pageHeader } from '#middlewares'; +import { AuthUser, Auth } from '#auth'; +import { InternalException, parseInteger } from '#helpers'; @Controller('notifications') @ApiTags('notifications') export class NotificationsApi { - constructor(private readonly notifier: NotificationService) {} + constructor(private readonly notifier: NotificationService) { } + /** + * Get all notifications + */ + @Get('/') + @Auth() @ApiOperation({ summary: 'Get all notifications', description: 'Returns all notifications.', }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(NotificationDTO, InternalServerErrorDTO) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) @ApiOkResponse({ - description: - 'Successful operation. Returns notifications and count.', - schema: { - type: 'array', - items: { - $ref: getSchemaPath(NotificationDTO), - }, - }, - headers: { - 'X-Total-Count': { - description: 'Count of notifications', - }, - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + description: 'Successful operation. Returns notifications and count.', + isArray: true, + headers: pageHeader, + type: NotificationDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO, }) - @ApiBearerAuth() - @UseGuards(AuthGuard) - @Get('/') + @ApiExtraModels(NotificationDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getAllNotifications(@Req() req, @Response() res) { + async getAllNotifications( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + ): Promise { try { - let pageIndex: number; - let pageSize: number; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = Number.parseInt(req.query.pageIndex, 10); - pageSize = Number.parseInt(req.query.pageSize, 10); - } const [notifications, count] = await this.notifier.all( - req.user.id, - pageIndex, - pageSize + user.id, + parseInteger(pageIndex), + parseInteger(pageSize) ); - return res.setHeader('X-Total-Count', count).json(notifications); + return res.header('X-Total-Count', count).send(notifications); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Get new notifications + */ + @Get('/new') + @Auth() @ApiOperation({ summary: 'Get new notifications', description: 'Returns new notifications.', }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(NotificationDTO, InternalServerErrorDTO) @ApiOkResponse({ - description: - 'Successful operation. Returns new notifications.', - schema: { - type: 'array', - items: { - $ref: getSchemaPath(NotificationDTO), - }, - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + description: 'Successful operation. Returns new notifications.', + isArray: true, + type: NotificationDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO, }) - @ApiBearerAuth() - @UseGuards(AuthGuard) - @Get('/new') + @ApiExtraModels(NotificationDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getNewNotifications(@Req() req, @Response() res): Promise { + async getNewNotifications( + @AuthUser() user: IAuthUser + ): Promise { try { - if (!req.user.id) { + if (!user.id) { throw Error('User is not registered'); } - return res.json( - await this.notifier.getNewNotifications(req.user.id) - ); + return await this.notifier.getNewNotifications(user.id); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Get progresses + */ + @Get('/progresses') + @Auth() @ApiOperation({ summary: 'Get progresses', description: 'Returns progresses.', }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(ProgressDTO, InternalServerErrorDTO) @ApiOkResponse({ - description: - 'Successful operation. Returns progresses.', - schema: { - type: 'array', - items: { - $ref: getSchemaPath(ProgressDTO), - }, - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + description: 'Successful operation. Returns progresses.', + isArray: true, + type: ProgressDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO, }) - @ApiBearerAuth() - @UseGuards(AuthGuard) - @Get('/progresses') + @ApiExtraModels(ProgressDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getProgresses(@Req() req, @Response() res): Promise { + async getProgresses( + @AuthUser() user: IAuthUser + ): Promise { try { - if (!req.user.id) { + if (!user.id) { throw Error('User is not registered'); } - return res.json(await this.notifier.getProgresses(req.user.id)); + return await this.notifier.getProgresses(user.id); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Read all notifications + */ + @Post('/read/all') + @Auth() @ApiOperation({ summary: 'Read all notifications', - description: 'Returns new notifications.', + description: 'Returns new notifications.' }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(NotificationDTO, InternalServerErrorDTO) @ApiOkResponse({ - description: - 'Successful operation. Returns notifications.', - schema: { - type: 'array', - items: { - $ref: getSchemaPath(NotificationDTO), - }, - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + description: 'Successful operation. Returns notifications.', + isArray: true, + type: NotificationDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO }) - @ApiBearerAuth() - @UseGuards(AuthGuard) - @Post('/read/all') + @ApiExtraModels(NotificationDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async readAll(@Req() req, @Response() res): Promise { + async readAll( + @AuthUser() user: IAuthUser + ): Promise { try { - if (!req.user.id) { + if (!user.id) { throw Error('User is not registered'); } - return res.json(await this.notifier.readAll(req.user.id)); + return await this.notifier.readAll(user.id); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Delete notifications up to this point + */ + @Delete('/delete/:notificationId') + @Auth() @ApiOperation({ summary: 'Delete notifications up to this point', - description: 'Returns deleted notifications count.', + description: 'Returns deleted notifications count.' }) - @ApiSecurity('bearerAuth') - @ApiExtraModels(InternalServerErrorDTO) @ApiParam({ name: 'notificationId', type: 'string', + required: true, + description: 'Notification Identifier', + example: Examples.UUID }) @ApiOkResponse({ - description: - 'Successful operation. Returns deleted notifications count.', - schema: { - type: 'number', - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + description: 'Successful operation. Returns deleted notifications count.', + type: Number }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO }) - @ApiBearerAuth() - @UseGuards(AuthGuard) - @Delete('/delete/:notificationId') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async delete(@Req() req, @Response() res) { + async delete( + @AuthUser() user: IAuthUser, + @Param('notificationId') notificationId: string, + ): Promise { try { - return res.json( - await this.notifier.deleteUpTo( - req.user.id, - req.params.notificationId - ) - ); + return await this.notifier.deleteUpTo(user.id, notificationId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/permissions.ts b/api-gateway/src/api/service/permissions.ts new file mode 100644 index 0000000000..e1979b0541 --- /dev/null +++ b/api-gateway/src/api/service/permissions.ts @@ -0,0 +1,796 @@ +import { IAuthUser } from '@guardian/common'; +import { AssignedEntityType, Permissions, UserPermissions } from '@guardian/interfaces'; +import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Query, Response } from '@nestjs/common'; +import { ApiTags, ApiInternalServerErrorResponse, ApiExtraModels, ApiOperation, ApiBody, ApiOkResponse, ApiParam, ApiQuery } from '@nestjs/swagger'; +import { AssignPolicyDTO, Examples, InternalServerErrorDTO, PermissionsDTO, PolicyDTO, RoleDTO, UserDTO, pageHeader } from '#middlewares'; +import { AuthUser, Auth } from '#auth'; +import { EntityOwner, Guardians, InternalException, Users } from '#helpers'; +import { WebSocketsService } from './websockets.js'; + +@Controller('permissions') +@ApiTags('permissions') +export class PermissionsApi { + /** + * Return a list of all permissions + */ + @Get('/') + @Auth( + Permissions.PERMISSIONS_ROLE_READ, + Permissions.DELEGATION_ROLE_MANAGE + ) + @ApiOperation({ + summary: 'Return a list of all permissions.', + description: 'Returns all permissions.', + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + type: PermissionsDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(RoleDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getPermissions(): Promise { + try { + return await (new Users()).getPermissions(); + } catch (error) { + await InternalException(error); + } + } + + /** + * Return a list of all roles + */ + @Get('/roles/') + @Auth( + Permissions.PERMISSIONS_ROLE_READ, + Permissions.DELEGATION_ROLE_MANAGE + ) + @ApiOperation({ + summary: 'Return a list of all roles.', + description: 'Returns all roles.', + }) + @ApiQuery({ + name: 'name', + type: String, + description: 'Filter by role name', + required: false, + example: 'name' + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + headers: pageHeader, + type: RoleDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(RoleDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getRoles( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('name') name?: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { + try { + const owner = user.parent || user.did; + const options: any = { + name, + owner, + user: user.did, + onlyOwn: !UserPermissions.has(user, Permissions.PERMISSIONS_ROLE_READ), + pageIndex, + pageSize + }; + const { items, count } = await (new Users()).getRoles(options); + return res.header('X-Total-Count', count).send(items); + } catch (error) { + await InternalException(error); + } + } + + /** + * Create role + */ + @Post('/roles/') + @Auth( + Permissions.PERMISSIONS_ROLE_CREATE + ) + @ApiOperation({ + summary: 'Creates new role.', + description: 'Creates new role.', + }) + @ApiBody({ + description: 'Object that contains role information.', + required: true, + type: RoleDTO, + }) + @ApiOkResponse({ + description: 'Created role.', + type: RoleDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(RoleDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.CREATED) + async createRole( + @AuthUser() user: IAuthUser, + @Body() body: RoleDTO + ): Promise { + try { + const owner = new EntityOwner(user); + const role = await (new Users()).createRole(body, owner); + await (new Guardians()).createRole(role, owner); + return role; + } catch (error) { + await InternalException(error); + } + } + + /** + * Updates role + */ + @Put('/roles/:id') + @Auth( + Permissions.PERMISSIONS_ROLE_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Updates role configuration.', + description: 'Updates role configuration for the specified role ID.' + }) + @ApiParam({ + name: 'id', + type: 'string', + required: true, + description: 'Role Identifier', + example: Examples.DB_ID, + }) + @ApiBody({ + description: 'Role configuration.', + type: RoleDTO, + }) + @ApiOkResponse({ + description: 'Role configuration.', + type: RoleDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(RoleDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async updateRole( + @AuthUser() user: IAuthUser, + @Param('id') id: string, + @Body() role: RoleDTO + ): Promise { + let row: any; + const userService = new Users(); + try { + row = await userService.getRoleById(id); + } catch (error) { + await InternalException(error); + } + if (!row) { + throw new HttpException('Role does not exist.', HttpStatus.NOT_FOUND) + } + try { + const owner = new EntityOwner(user); + const result = await userService.updateRole(id, role, owner); + const users = await userService.refreshUserPermissions(id, user.did); + await (new Guardians()).updateRole(result, owner); + const wsService = new WebSocketsService(); + wsService.updatePermissions(users); + return result; + } catch (error) { + await InternalException(error); + } + } + + /** + * Remove role + */ + @Delete('/roles/:id') + @Auth( + Permissions.PERMISSIONS_ROLE_DELETE + ) + @ApiOperation({ + summary: 'Deletes the role.', + description: 'Deletes the role with the provided role ID.' + }) + @ApiParam({ + name: 'id', + type: 'string', + required: true, + description: 'Role Identifier', + example: Examples.DB_ID, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: Boolean, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async deleteModule( + @AuthUser() user: IAuthUser, + @Param('id') id: string, + ): Promise { + try { + if (!id) { + throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); + const userService = new Users(); + const result = await userService.deleteRole(id, owner); + const users = await userService.refreshUserPermissions(id, user.did); + await (new Guardians()).deleteRole(result, owner); + const wsService = new WebSocketsService(); + wsService.updatePermissions(users); + return result; + } catch (error) { + await InternalException(error); + } + } + + /** + * Set default role + */ + @Post('/roles/default') + @Auth( + Permissions.PERMISSIONS_ROLE_CREATE + ) + @ApiOperation({ + summary: 'Set default role.', + description: 'Set the role as default for new users.', + }) + @ApiBody({ + description: 'Object that contains role information.', + required: true, + schema: { + type: 'object', + properties: { + id: { + type: 'string', + description: 'Role Identifier', + example: Examples.DB_ID + } + }, + required: ['id'] + }, + examples: { + Default: { + value: { + id: Examples.DB_ID + } + } + } + }) + @ApiOkResponse({ + description: 'Created role.', + type: RoleDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(RoleDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.CREATED) + async setDefaultRole( + @AuthUser() user: IAuthUser, + @Body() body: { id: string } + ): Promise { + try { + return await (new Users()).setDefaultRole(body?.id, user.did); + } catch (error) { + await InternalException(error); + } + } + + /** + * Return a list of all users + */ + @Get('/users/') + @Auth( + Permissions.PERMISSIONS_ROLE_MANAGE, + Permissions.DELEGATION_ROLE_MANAGE + ) + @ApiOperation({ + summary: 'Return a list of all users.', + description: 'Returns all users.', + }) + @ApiQuery({ + name: 'role', + type: String, + description: 'Filter by role', + required: false, + example: Examples.DB_ID + }) + @ApiQuery({ + name: 'status', + type: String, + enum: ['Active', 'Inactive'], + description: 'Filter by status', + required: false, + example: 'Active' + }) + @ApiQuery({ + name: 'username', + type: String, + description: 'Filter by username', + required: false, + example: 'username' + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + headers: pageHeader, + type: UserDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(UserDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getUsers( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + @Query('role') role?: string, + @Query('status') status?: string, + @Query('username') username?: string + ): Promise { + try { + const options: any = { + filters: { + role, + status, + username, + did: { $ne: user.did } + }, + parent: user.parent ? user.parent : user.did, + pageIndex, + pageSize + }; + const { items, count } = await (new Users()).getWorkers(options); + const guardians = new Guardians(); + for (const item of items) { + item.assignedEntities = await guardians.assignedEntities(item.did); + } + return res.header('X-Total-Count', count).send(items); + } catch (error) { + await InternalException(error); + } + } + + /** + * Get user + */ + @Get('/users/:username') + @Auth( + Permissions.PERMISSIONS_ROLE_MANAGE, + Permissions.DELEGATION_ROLE_MANAGE + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Updates user permissions.', + description: 'Updates user permissions for the specified username.' + }) + @ApiParam({ + name: 'username', + type: String, + description: 'User Identifier', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'User permissions.', + type: UserDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(UserDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getUser( + @AuthUser() user: IAuthUser, + @Param('username') username: string + ): Promise { + try { + const owner = user.parent || user.did; + const users = new Users(); + const row = await users.getUser(username); + if (!row || row.parent !== owner || row.did === user.did) { + throw new HttpException('User does not exist.', HttpStatus.NOT_FOUND); + } + return row as any; + } catch (error) { + await InternalException(error); + } + } + + /** + * Updates user + */ + @Put('/users/:username') + @Auth( + Permissions.PERMISSIONS_ROLE_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Updates user permissions.', + description: 'Updates user permissions for the specified username.' + }) + @ApiParam({ + name: 'username', + type: String, + description: 'User Identifier', + required: true, + example: 'username' + }) + @ApiBody({ + description: 'User permissions.', + type: String, + isArray: true, + examples: { + Roles: { + value: [Examples.DB_ID, Examples.DB_ID] + } + } + }) + @ApiOkResponse({ + description: 'User permissions.', + type: UserDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(UserDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async updateUser( + @AuthUser() user: IAuthUser, + @Param('username') username: string, + @Body() body: string[] + ): Promise { + let row: any; + const users = new Users(); + try { + row = await users.getUser(username); + } catch (error) { + await InternalException(error); + } + if (!row || row.parent !== user.did || row.did === user.did) { + throw new HttpException('User does not exist.', HttpStatus.NOT_FOUND) + } + try { + const owner = new EntityOwner(user); + const result = await users.updateUserRole(username, body, owner); + await (new Guardians()).setRole(result, owner); + const wsService = new WebSocketsService(); + wsService.updatePermissions(result); + return result; + } catch (error) { + await InternalException(error); + } + } + + /** + * Get policies + */ + @Get('/users/:username/policies') + @Auth( + Permissions.PERMISSIONS_ROLE_MANAGE, + Permissions.DELEGATION_ROLE_MANAGE + ) + @ApiOperation({ + summary: 'Return a list of all roles.', + description: 'Returns all roles.', + }) + @ApiParam({ + name: 'username', + type: String, + description: 'User Identifier', + required: true, + example: 'username' + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiQuery({ + name: 'status', + type: String, + enum: ['ALL', 'DRAFT', 'DRY-RUN', 'PUBLISH_ERROR', 'DISCONTINUED', 'PUBLISH'], + description: 'Filter by status', + required: false, + example: 'Active' + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + headers: pageHeader, + type: PolicyDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getAssignedPolicies( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Param('username') username: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + @Query('status') status?: string + ): Promise { + const owner = user.parent || user.did; + let target: any; + try { + target = await (new Users()).getUser(username); + } catch (error) { + await InternalException(error); + } + if (!target || target.parent !== owner) { + throw new HttpException('User does not exist.', HttpStatus.NOT_FOUND) + } + try { + const options: any = { + owner, + user: user.did, + target: target.did, + onlyOwn: !UserPermissions.has(user, Permissions.PERMISSIONS_ROLE_READ), + pageIndex, + pageSize, + status + }; + const { policies, count } = await (new Guardians()).getAssignedPolicies(options); + return res.header('X-Total-Count', count).send(policies); + } catch (error) { + await InternalException(error); + } + } + + /** + * Assign policy + */ + @Post('/users/:username/policies/assign') + @Auth( + Permissions.PERMISSIONS_ROLE_MANAGE + ) + @ApiOperation({ + summary: 'Assign policy.', + description: 'Assign policy.', + }) + @ApiParam({ + name: 'username', + type: String, + description: 'User Identifier', + required: true, + example: 'username' + }) + @ApiBody({ + description: 'Options.', + required: true, + type: AssignPolicyDTO, + }) + @ApiOkResponse({ + description: 'Assigned policy.', + type: PolicyDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.CREATED) + async assignPolicy( + @AuthUser() user: IAuthUser, + @Param('username') username: string, + @Body() body: AssignPolicyDTO + ): Promise { + let row: any; + const users = new Users(); + try { + row = await users.getUser(username); + } catch (error) { + await InternalException(error); + } + if (!row || row.parent !== user.did || row.did === user.did) { + throw new HttpException('User does not exist.', HttpStatus.NOT_FOUND) + } + try { + const { policyIds, assign } = body; + return await (new Guardians()).assignEntity( + AssignedEntityType.Policy, + policyIds, + assign, + row.did, + user.did + ); + } catch (error) { + await InternalException(error); + } + } + + /** + * Delegate role + */ + @Put('/users/:username/delegate') + @Auth(Permissions.DELEGATION_ROLE_MANAGE) + @ApiOperation({ + summary: 'Delegate user permissions.', + description: 'Delegate user permissions for the specified username.' + }) + @ApiParam({ + name: 'username', + type: String, + description: 'User Identifier', + required: true, + example: 'username' + }) + @ApiBody({ + description: 'User permissions.', + type: String, + isArray: true, + examples: { + Roles: { + value: [Examples.DB_ID, Examples.DB_ID] + } + } + }) + @ApiOkResponse({ + description: 'User permissions.', + type: UserDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(UserDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async delegateRole( + @AuthUser() user: IAuthUser, + @Param('username') username: string, + @Body() body: string[] + ): Promise { + let row: any; + const users = new Users(); + try { + row = await users.getUser(username); + } catch (error) { + await InternalException(error); + } + if (!row || row.parent !== user.parent || row.did === user.did) { + throw new HttpException('User does not exist.', HttpStatus.NOT_FOUND) + } + try { + const owner = new EntityOwner(user); + const result = await users.delegateUserRole(username, body, owner); + await (new Guardians()).setRole(result, owner); + const wsService = new WebSocketsService(); + wsService.updatePermissions(result); + return result; + } catch (error) { + await InternalException(error); + } + } + + /** + * Delegate policy + */ + @Post('/users/:username/policies/delegate') + @Auth( + Permissions.DELEGATION_ROLE_MANAGE + ) + @ApiOperation({ + summary: 'Delegate policy.', + description: 'Delegate policy.', + }) + @ApiParam({ + name: 'username', + type: String, + description: 'User Identifier', + required: true, + example: 'username' + }) + @ApiBody({ + description: 'Options.', + required: true, + type: AssignPolicyDTO, + }) + @ApiOkResponse({ + description: 'Assigned policy.', + type: PolicyDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.CREATED) + async delegatePolicy( + @AuthUser() user: IAuthUser, + @Param('username') username: string, + @Body() body: AssignPolicyDTO + ): Promise { + let row: any; + const users = new Users(); + try { + row = await users.getUser(username); + } catch (error) { + await InternalException(error); + } + if (!row || row.parent !== user.parent || row.did === user.did) { + throw new HttpException('User does not exist.', HttpStatus.NOT_FOUND) + } + try { + const { policyIds, assign } = body; + return await (new Guardians()).delegateEntity( + AssignedEntityType.Policy, + policyIds, + assign, + row.did, + user.did + ); + } catch (error) { + await InternalException(error); + } + } +} \ No newline at end of file diff --git a/api-gateway/src/api/service/policy.ts b/api-gateway/src/api/service/policy.ts index 78a9706595..13c5242120 100644 --- a/api-gateway/src/api/service/policy.ts +++ b/api-gateway/src/api/service/policy.ts @@ -1,158 +1,143 @@ -import { Auth } from '../../auth/auth.decorator.js'; -import { AuthUser, checkPermission } from '../../auth/authorization-helper.js'; +import { AuthUser, Auth } from '#auth'; import { IAuthUser, Logger, RunFunctionAsync } from '@guardian/common'; -import { DocumentType, PolicyType, TaskAction, UserRole } from '@guardian/interfaces'; -import { PolicyEngine } from '../../helpers/policy-engine.js'; -import { ProjectService } from '../../helpers/projects.js'; -import { ServiceError } from '../../helpers/service-requests-base.js'; -import { TaskManager } from '../../helpers/task-manager.js'; -import { Users } from '../../helpers/users.js'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; -import { MigrationConfigDTO, PolicyCategoryDTO, } from '../../middlewares/validation/schemas/policies.js'; -import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Query, Req, Response, UploadedFiles, UseInterceptors, } from '@nestjs/common'; -import { AnyFilesInterceptor } from '@nestjs/platform-express'; -import { ApiAcceptedResponse, ApiBody, ApiConsumes, ApiExtraModels, ApiForbiddenResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiParam, ApiQuery, ApiSecurity, ApiTags, ApiUnauthorizedResponse, getSchemaPath, } from '@nestjs/swagger'; -import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator.js'; -import { ApiImplicitQuery } from '@nestjs/swagger/dist/decorators/api-implicit-query.decorator.js'; +import { DocumentType, Permissions, PolicyType, TaskAction, UserRole } from '@guardian/interfaces'; +import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Query, Response, UseInterceptors, } from '@nestjs/common'; +import { ApiAcceptedResponse, ApiBody, ApiConsumes, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'; import { CACHE } from '../../constants/index.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; - -const ONLY_SR = ' Only users with the Standard Registry role are allowed to make the request.' +import { MigrationConfigDTO, PolicyCategoryDTO, InternalServerErrorDTO, PolicyDTO, TaskDTO, PolicyValidationDTO, BlockDTO, ExportMessageDTO, ImportMessageDTO, PolicyPreviewDTO, Examples, pageHeader, PoliciesValidationDTO } from '#middlewares'; +import { PolicyEngine, ProjectService, ServiceError, TaskManager, UseCache, InternalException, ONLY_SR, AnyFilesInterceptor, UploadedFiles, EntityOwner } from '#helpers'; + +async function getOldResult(user: IAuthUser): Promise { + const options: any = {}; + const owner = new EntityOwner(user); + const { policies } = await (new PolicyEngine()).getPolicies(options, owner); + return policies; +} @Controller('policies') @ApiTags('policies') export class PolicyApi { + /** + * Return a list of all policies + */ + @Get('/') + @Auth( + Permissions.POLICIES_POLICY_READ, + Permissions.POLICIES_POLICY_EXECUTE, + Permissions.POLICIES_POLICY_AUDIT, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR, + ) @ApiOperation({ summary: 'Return a list of all policies.', - description: 'Returns all policies. Only users with the Standard Registry and Installer role are allowed to make the request.', + description: 'Returns all policies.', }) - @ApiSecurity('bearerAuth') - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageIndex', type: Number, description: 'The number of pages to skip before starting to collect the result set', - required: false + required: false, + example: 0 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageSize', type: Number, description: 'The numbers of items to return', - required: false + required: false, + example: 20 }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + isArray: true, + headers: pageHeader, + type: PolicyDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/') + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getPolicies(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER, UserRole.AUDITOR)(req.user); - const users = new Users(); - const engineService = new PolicyEngine(); + async getPolicies( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { + if (!user.did && user.role !== UserRole.AUDITOR) { + return res.header('X-Total-Count', 0).send([]); + } try { - const user = await users.getUser(req.user.username); - if (!user.did && user.role !== UserRole.AUDITOR) { - return res.setHeader('X-Total-Count', 0).json([]); - } - let pageIndex: any; - let pageSize: any; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } - let result: any; - if (user.role === UserRole.STANDARD_REGISTRY) { - result = await engineService.getPolicies({ - filters: { - owner: user.did, - }, - userDid: user.did, - pageIndex, - pageSize - }); - } else if (user.role === UserRole.AUDITOR) { - const filters: any = { - status: { $in: [PolicyType.PUBLISH, PolicyType.DISCONTINUED] }, - } - result = await engineService.getPolicies({ - filters, - userDid: user.did, - pageIndex, - pageSize - }); - } else { - const filters: any = { - status: { $in: [PolicyType.PUBLISH, PolicyType.DISCONTINUED] }, - } - if (user.parent) { - filters.owner = user.parent; - } - result = await engineService.getPolicies({ - filters, - userDid: user.did, - pageIndex, - pageSize - }); - } - const { policies, count } = result; - return res.setHeader('X-Total-Count', count).json(policies); + const options: any = { + filters: {}, + pageIndex, + pageSize + }; + const engineService = new PolicyEngine(); + const owner = new EntityOwner(user); + const { policies, count } = await engineService.getPolicies(options, owner); + return res.header('X-Total-Count', count).send(policies); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Creates a new policy + */ + @Post('/') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new policy.', description: 'Creates a new policy.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiBody({ + description: 'Policy configuration.', + type: PolicyDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + isArray: true, + type: PolicyDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/') + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async createPolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async createPolicy( + @AuthUser() user: IAuthUser, + @Body() body: PolicyDTO + ): Promise { try { - const policies = await engineService.createPolicy(req.body, req.user) - return res.status(201).json(policies); + const engineService = new PolicyEngine(); + await engineService.createPolicy(body, new EntityOwner(user)); + return await getOldResult(user); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Migrate policy data + */ + @Post('/migrate-data') + @Auth( + Permissions.POLICIES_MIGRATION_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Migrate policy data.', - description: 'Migrate policy data. Only users with the Standard Registry role are allowed to make the request.', + description: 'Migrate policy data.' + ONLY_SR, }) - @ApiExtraModels(MigrationConfigDTO, InternalServerErrorDTO) @ApiBody({ description: 'Migration config.', - schema: { - $ref: getSchemaPath(MigrationConfigDTO) - } + type: MigrationConfigDTO, }) @ApiOkResponse({ description: 'Errors while migration.', @@ -173,229 +158,294 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/migrate-data') + @ApiExtraModels(MigrationConfigDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async migrateData(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async migrateData( + @AuthUser() user: IAuthUser, + @Body() body: MigrationConfigDTO + ): Promise { const engineService = new PolicyEngine(); try { - return res.send(await engineService.migrateData( - req.user.did, - req.body - )); + return await engineService.migrateData(new EntityOwner(user), body as any); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Migrate policy data + */ + @Post('/push/migrate-data') + @Auth( + Permissions.POLICIES_MIGRATION_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Migrate policy data asynchronous.', - description: 'Migrate policy data asynchronous. Only users with the Standard Registry role are allowed to make the request.', + description: 'Migrate policy data asynchronous.' + ONLY_SR, }) - @ApiExtraModels(MigrationConfigDTO, InternalServerErrorDTO) @ApiBody({ - description: 'Migration config.', - schema: { - $ref: getSchemaPath(MigrationConfigDTO) - } + description: 'Migration configuration.', + type: MigrationConfigDTO }) @ApiAcceptedResponse({ description: 'Created task.', - schema: { - 'type': 'object' - }, + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/push/migrate-data') + @ApiExtraModels(TaskDTO, MigrationConfigDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async migrateDataAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; + async migrateDataAsync( + @AuthUser() user: IAuthUser, + @Body() body: MigrationConfigDTO + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.MIGRATE_DATA, user.id); RunFunctionAsync(async () => { const engineService = new PolicyEngine(); - await engineService.migrateDataAsync(req.user.did, req.body, task); + await engineService.migrateDataAsync(new EntityOwner(user), body as any, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: 'Unknown error: ' + error.message }); }); - return res.status(202).send(task); + return task; } + /** + * Creates a new policy + */ + @Post('/push') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new policy.', description: 'Creates a new policy.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiBody({ + description: 'Policy configuration.', + type: PolicyDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/push') + @ApiExtraModels(TaskDTO, PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async createPolicyAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const model = req.body; - const user = req.user; + async createPolicyAsync( + @AuthUser() user: IAuthUser, + @Body() body: PolicyDTO + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.CREATE_POLICY, user.id); RunFunctionAsync(async () => { const engineService = new PolicyEngine(); - await engineService.createPolicyAsync(model, user, task); + await engineService.createPolicyAsync(body, new EntityOwner(user), task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return res.status(202).send(task); + return task; } - @ApiOperation({}) - @ApiSecurity('bearerAuth') + /** + * Clone policy + */ + @Post('/push/:policyId') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Clones policy.', + description: 'Clones policy.' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Policy configuration.', + type: PolicyDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/push/:policyId') + @ApiExtraModels(TaskDTO, PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async updatePolicyAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const policyId = req.params.policyId; - const model = req.body; - const user = req.user; + async updatePolicyAsync( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: PolicyDTO + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.CLONE_POLICY, user.id); RunFunctionAsync(async () => { const engineService = new PolicyEngine(); - await engineService.clonePolicyAsync(policyId, model, user, task); + await engineService.clonePolicyAsync(policyId, body, new EntityOwner(user), task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return res.status(202).send(task); + return task; } - @ApiSecurity('bearerAuth') + /** + * Delete policy + */ @Delete('/push/:policyId') + @Auth( + Permissions.POLICIES_POLICY_DELETE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Remove policy.', + description: 'Remove policy.' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async deletePolicyAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const policyId = req.params.policyId; - const user = req.user; + async deletePolicyAsync( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.DELETE_POLICY, user.id); RunFunctionAsync(async () => { const engineService = new PolicyEngine(); - await engineService.deletePolicyAsync(policyId, user, task); + await engineService.deletePolicyAsync(policyId, new EntityOwner(user), task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return res.status(202).send(task); + return task; } + /** + * Get policy configuration + */ + @Get('/:policyId') + @Auth( + Permissions.POLICIES_POLICY_READ, + Permissions.POLICIES_POLICY_EXECUTE, + Permissions.POLICIES_POLICY_AUDIT, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR, + ) @ApiOperation({ summary: 'Retrieves policy configuration.', description: 'Retrieves policy configuration for the specified policy ID.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, + description: 'Policy configuration.', + type: PolicyDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId') + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getPolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER, UserRole.AUDITOR)(req.user); - const users = new Users(); - const engineService = new PolicyEngine(); + async getPolicy( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ): Promise { try { - const user = await users.getUser(req.user.username); - const model = (await engineService.getPolicy({ - filters: req.params.policyId, + const engineService = new PolicyEngine(); + return await engineService.getPolicy({ + filters: policyId, userDid: user.did, - })) as any; - return res.send(model); + }, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Updates policy + */ + @Put('/:policyId') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Updates policy configuration.', description: 'Updates policy configuration for the specified policy ID.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Policy configuration.', + type: PolicyDTO, + }) @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, + description: 'Policy configuration.', + type: PolicyDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Put('/:policyId') + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async updatePolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async updatePolicy( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() policy: PolicyDTO + ): Promise { const engineService = new PolicyEngine(); - let model: any; - try { - model = await engineService.getPolicy({ filters: req.params.policyId }) as any; - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } + const owner = new EntityOwner(user); + const model = await engineService.accessPolicy(policyId, owner, 'update'); if (!model) { throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) } try { - const policy = req.body; model.config = policy.config; model.name = policy.name; model.version = policy.version; @@ -408,236 +458,306 @@ export class PolicyApi { model.policyGroups = policy.policyGroups; model.categories = policy.categories; model.projectSchema = policy.projectSchema; - const result = await engineService.savePolicy(model, req.user, req.params.policyId); - return res.json(result); + return await engineService.savePolicy(model, new EntityOwner(user), policyId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Publish policy + */ + @Put('/:policyId/publish') + @Auth( + Permissions.POLICIES_POLICY_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Publishes the policy onto IPFS.', description: 'Publishes the policy with the specified (internal) policy ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera topic.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: PoliciesValidationDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Put('/:policyId/publish') + @ApiExtraModels(PoliciesValidationDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async publishPolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async publishPolicy( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: PolicyDTO + ): Promise { try { - return res.json(await engineService.publishPolicy(req.body, req.user, req.params.policyId)); + const engineService = new PolicyEngine(); + const result = await engineService.publishPolicy(body, new EntityOwner(user), policyId); + result.policies = await getOldResult(user); + return result; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Publish policy + */ + @Put('/push/:policyId/publish') + @Auth( + Permissions.POLICIES_POLICY_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Publishes the policy onto IPFS.', description: 'Publishes the policy with the specified (internal) policy ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera topic.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Policy configuration.', + type: PolicyDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Put('/push/:policyId/publish') + @ApiExtraModels(TaskDTO, PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async publishPolicyAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const model = req.body; - const user = req.user; - const policyId = req.params.policyId; + async publishPolicyAsync( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: PolicyDTO + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.PUBLISH_POLICY, user.id); RunFunctionAsync(async () => { const engineService = new PolicyEngine(); - await engineService.publishPolicyAsync(model, user, policyId, task); + await engineService.publishPolicyAsync(body, new EntityOwner(user), policyId, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message || error }); }); - - return res.status(202).send(task); + return task; } + /** + * Go to dry-run policy + */ + @Put('/:policyId/dry-run') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Dry Run policy.', description: 'Run policy without making any persistent changes or executing transaction.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: PoliciesValidationDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Put('/:policyId/dry-run') + @ApiExtraModels(PoliciesValidationDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async dryRunPolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async dryRunPolicy( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ): Promise { try { - return res.json(await engineService.dryRunPolicy(req.user, req.params.policyId)); + const engineService = new PolicyEngine(); + const result = await engineService.dryRunPolicy(policyId, new EntityOwner(user)); + result.policies = await getOldResult(user); + return result; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Discontunue policy + */ + @Put('/:policyId/discontinue') + @Auth( + Permissions.POLICIES_POLICY_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ - summary: 'Discontunue policy.', - description: 'Discontunue policy. Only users with the Standard Registry role are allowed to make the request.', + summary: 'Discontinue policy.', + description: 'Discontinue policy. Only users with the Standard Registry role are allowed to make the request.', }) - @ApiExtraModels(InternalServerErrorDTO) @ApiParam({ name: 'policyId', - description: 'Policy identifier.', - required: true + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID }) @ApiBody({ description: 'Discontinue details.', schema: { type: 'object', properties: { - 'date': { - type: 'date' + date: { + type: 'string' } } } }) - @ApiSecurity('bearerAuth') @ApiOkResponse({ - description: 'Policies.', - schema: { - 'type': 'array', - items: { - type: 'object' - } - }, + description: 'Successful operation.', + isArray: true, + type: PolicyDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Put('/:policyId/discontinue') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async discontinuePolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async discontinuePolicy( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: any + ): Promise { try { - return res.json(await engineService.discontinuePolicy(req.user, req.params.policyId, req.body?.date)); + const engineService = new PolicyEngine(); + await engineService.discontinuePolicy(policyId, new EntityOwner(user), body?.date); + return await getOldResult(user); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Go to dry-run draft + */ + @Put('/:policyId/draft') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ - summary: 'Dry Run policy.', - description: 'Run policy without making any persistent changes or executing transaction.' + ONLY_SR, + summary: 'Return policy to editing.', + description: 'Return policy to editing.' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID }) - @ApiSecurity('bearerAuth') @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + isArray: true, + type: PolicyDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Put('/:policyId/draft') + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async draftPolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async draftPolicy( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ): Promise { try { - return res.json(await engineService.draft(req.user, req.params.policyId)); + const engineService = new PolicyEngine(); + await engineService.draft(policyId, new EntityOwner(user)); + return await getOldResult(user); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Validate + */ + @Post('/validate') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + Permissions.POLICIES_POLICY_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Validates policy.', description: 'Validates selected policy.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiBody({ + description: 'Policy configuration.', + type: PolicyDTO, + }) @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, + description: 'Validation result.', + type: PolicyValidationDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/validate') + @ApiExtraModels(PolicyDTO, PolicyValidationDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async validatePolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async validatePolicy( + @AuthUser() user: IAuthUser, + @Body() body: PolicyDTO + ): Promise { try { - return res.send(await engineService.validatePolicy(req.body, req.user)); + const engineService = new PolicyEngine(); + return await engineService.validatePolicy(body, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** - * use cache test dry run - * @param req + * Policy navigation */ + @Get('/:policyId/navigation') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ summary: 'Returns a policy navigation.', description: 'Returns a policy navigation.', }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) @ApiOkResponse({ description: 'Successful operation.', schema: { @@ -646,34 +766,43 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/navigation') - @HttpCode(HttpStatus.OK) + @ApiExtraModels(InternalServerErrorDTO) // @UseCache() - async getPolicyNavigation(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + @HttpCode(HttpStatus.OK) + async getPolicyNavigation( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string + ): Promise { try { - return await engineService.getNavigation(req.user, req.params.policyId); + const engineService = new PolicyEngine(); + return await engineService.getNavigation(user, policyId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** - * use cache need test - * @param req + * Policy groups */ + @Get('/:policyId/groups') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ summary: 'Returns a list of groups the user is a member of.', description: 'Returns a list of groups the user is a member of.', }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) @ApiOkResponse({ description: 'Successful operation.', schema: { @@ -682,109 +811,133 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/groups') - @HttpCode(HttpStatus.OK) + @ApiExtraModels(InternalServerErrorDTO) // @UseCache() - async getPolicyGroups(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + @HttpCode(HttpStatus.OK) + async getPolicyGroups( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ): Promise { try { - return await engineService.getGroups(req.user, req.params.policyId); + const engineService = new PolicyEngine(); + return await engineService.getGroups(user, policyId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get policy documents + */ + @Get('/:policyId/documents') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Get policy documents.', - description: 'Get policy documents. Only users with the Standard Registry role are allowed to make the request.', + description: 'Get policy documents.' + ONLY_SR, }) @ApiExtraModels(InternalServerErrorDTO) @ApiParam({ - description: 'Policy identifier.', name: 'policyId', - required: true + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID }) @ApiQuery({ - description: 'Include document field.', name: 'includeDocument', - type: 'boolean' + type: Boolean, + description: 'Include document field.', + required: false, + example: true }) @ApiQuery({ - description: 'Document type.', name: 'type', - enum: DocumentType + enum: DocumentType, + description: 'Document type.', + required: false, + example: DocumentType.VC }) @ApiQuery({ - description: 'Page index.', name: 'pageIndex', - type: 'number' + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 }) @ApiQuery({ - description: 'Page size.', name: 'pageSize', - type: 'number' + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 }) - @ApiSecurity('bearerAuth') @ApiOkResponse({ description: 'Documents.', + isArray: true, + headers: pageHeader, schema: { - 'type': 'array', + type: 'array', items: { type: 'object' } - }, - headers: { - 'X-Total-Count': { - description: 'Total documents count.' - } } }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/documents') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getPolicyDocuments(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async getPolicyDocuments( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Param('policyId') policyId: string, + @Query('type') type?: DocumentType, + @Query('includeDocument') includeDocument?: boolean, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + ): Promise { try { + const engineService = new PolicyEngine(); const [documents, count] = await engineService.getDocuments( - req.user.did, - req.params.policyId, - req.query?.includeDocument?.toLowerCase() === 'true', - req.query?.type, - req.query?.pageIndex, - req.query?.pageSize, + new EntityOwner(user), + policyId, + String(includeDocument)?.toLowerCase() === 'true', + type, + pageIndex, + pageSize, ); - return res.setHeader('X-Total-Count', count).json(documents); + return res.header('X-Total-Count', count).send(documents); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get policy data + */ + @Get('/:policyId/data') + @Auth( + Permissions.POLICIES_MIGRATION_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Get policy data.', description: 'Get policy data.' + ONLY_SR, }) @ApiExtraModels(InternalServerErrorDTO) @ApiParam({ - description: 'Policy identifier.', name: 'policyId', - required: true + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID }) - @ApiSecurity('bearerAuth') @ApiOkResponse({ description: 'Policy data.', schema: { @@ -794,49 +947,43 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/data') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async downloadPolicyData(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async downloadPolicyData( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Response() res: any + ): Promise { try { - const policy = await engineService.getPolicy({ - userDid: req.user.did, - filters: req.params.policyId, - }); - if (!policy) { - throw new Error(`Policy doesn't exist`); - } - const downloadResult = await engineService.downloadPolicyData( - req.params.policyId, - req.user.did - ); - res.setHeader( + const engineService = new PolicyEngine(); + const owner = new EntityOwner(user); + const policy = await engineService.accessPolicy(policyId, owner, 'read'); + const downloadResult = await engineService.downloadPolicyData(policyId, owner); + res.header( 'Content-Disposition', `attachment; filename=${policy.name}.data` ); - res.setHeader('Content-Type', 'application/policy-data'); + res.header('Content-Type', 'application/policy-data'); return res.send(downloadResult); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Upload policy data + */ + @Post('/data') + @Auth( + Permissions.POLICIES_MIGRATION_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Upload policy data.', description: 'Upload policy data.' + ONLY_SR, }) - @ApiExtraModels(InternalServerErrorDTO) - @ApiSecurity('bearerAuth') @ApiBody({ description: 'Policy data file', schema: { @@ -852,38 +999,41 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/data') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async uploadPolicyData(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async uploadPolicyData( + @AuthUser() user: IAuthUser, + @Body() body: any + ): Promise { try { - return await engineService.uploadPolicyData(req.user.did, req.body); + const engineService = new PolicyEngine(); + return await engineService.uploadPolicyData(new EntityOwner(user), body); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Get policy tag map + */ + @Get('/:policyId/tag-block-map') + @Auth( + Permissions.POLICIES_MIGRATION_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Get policy tag block map.', description: 'Get policy tag block map.' + ONLY_SR, }) - @ApiExtraModels(InternalServerErrorDTO) @ApiParam({ - description: 'Policy identifier.', name: 'policyId', - required: true + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID }) - @ApiSecurity('bearerAuth') @ApiOkResponse({ description: 'Policy tag block map.', schema: { @@ -892,41 +1042,41 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/tag-block-map') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getTagBlockMap(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async getTagBlockMap( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ): Promise { try { - return await engineService.getTagBlockMap( - req.params.policyId, - req.user.did - ); + const engineService = new PolicyEngine(); + return await engineService.getTagBlockMap(policyId, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Get policy virtual keys + */ + @Get('/:policyId/virtual-keys') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Get policy virtual keys.', description: 'Get policy virtual keys.' + ONLY_SR, }) - @ApiExtraModels(InternalServerErrorDTO) @ApiParam({ - description: 'Policy identifier.', name: 'policyId', - required: true + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID }) - @ApiSecurity('bearerAuth') @ApiOkResponse({ description: 'Policy virtual keys.', schema: { @@ -936,54 +1086,50 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/virtual-keys') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async downloadVirtualKeys(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async downloadVirtualKeys( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Response() res: any + ): Promise { const engineService = new PolicyEngine(); try { - const policy = await engineService.getPolicy({ - userDid: req.user.did, - filters: req.params.policyId, - }); - if (!policy) { - throw new Error(`Policy doesn't exist`); - } - const downloadResult = await engineService.downloadVirtualKeys( - req.params.policyId, - req.user.did - ); - res.setHeader( + const owner = new EntityOwner(user); + const policy = await engineService.accessPolicy(policyId, owner, 'read'); + const downloadResult = await engineService.downloadVirtualKeys(policyId, owner); + res.header( 'Content-Disposition', `attachment; filename=${policy.name}.vk` ); - res.setHeader('Content-Type', 'application/virtual-keys'); + res.header('Content-Type', 'application/virtual-keys'); return res.send(downloadResult); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Upload policy virtual keys. + */ + @Post('/:policyId/virtual-keys') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Upload policy virtual keys.', description: 'Upload policy virtual keys.' + ONLY_SR, }) - @ApiExtraModels(InternalServerErrorDTO) @ApiParam({ - description: 'Policy identifier.', name: 'policyId', - required: true + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID }) - @ApiSecurity('bearerAuth') @ApiBody({ description: 'Virtual keys file', schema: { @@ -996,264 +1142,420 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/:policyId/virtual-keys') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async uploadVirtualKeys(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async uploadVirtualKeys( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: any + ): Promise { try { - return await engineService.uploadVirtualKeys( - req.user.did, - req.body, - req.params.policyId - ); + const engineService = new PolicyEngine(); + return await engineService.uploadVirtualKeys(new EntityOwner(user), body, policyId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Makes the selected group active. + */ + @Post('/:policyId/groups') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ summary: 'Makes the selected group active.', description: 'Makes the selected group active. if UUID is not set then returns the user to the default state.', }) - @ApiSecurity('bearerAuth') - @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Group', + type: Object + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: Object + }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/:policyId/groups') + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setPolicyGroups(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); + async setPolicyGroups( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: any + ): Promise { const engineService = new PolicyEngine(); try { - return res.send(await engineService.selectGroup(req.user, req.params.policyId, req.body.uuid)); + return await engineService.selectGroup(user, policyId, body?.uuid); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** - * @param req - * @param res + * Retrieves data for the policy root block. */ + @Get('/:policyId/blocks') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ summary: 'Retrieves data for the policy root block.', description: 'Returns data from the root policy block. Only users with the Standard Registry and Installer role are allowed to make the request.', }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: BlockDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/blocks') + @ApiExtraModels(BlockDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getPolicyBlocks(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async getPolicyBlocks( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string + ): Promise { try { - return res.send(await engineService.getPolicyBlocks(req.user, req.params.policyId)); + const engineService = new PolicyEngine(); + return await engineService.getPolicyBlocks(user, policyId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Requests block data. + */ + @Get('/:policyId/blocks/:uuid') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ summary: 'Requests block data.', description: 'Requests block data. Only users with a role that described in block are allowed to make the request.', }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Block Identifier', + example: Examples.UUID + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: BlockDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/blocks/:uuid') + @ApiExtraModels(BlockDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getBlockData(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async getBlockData( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Param('uuid') uuid: string + ): Promise { try { - return res.send(await engineService.getBlockData(req.user, req.params.policyId, req.params.uuid)); + const engineService = new PolicyEngine(); + return await engineService.getBlockData(user, policyId, uuid); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Sends data to the specified block + */ + @Post('/:policyId/blocks/:uuid') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ summary: 'Sends data to the specified block.', description: 'Sends data to the specified block.', }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Block Identifier', + example: Examples.UUID + }) + @ApiBody({ + description: 'Data', + type: Object + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: BlockDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/:policyId/blocks/:uuid') + @ApiExtraModels(BlockDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setBlockData(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async setBlockData( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Param('uuid') uuid: string, + @Body() body: any + ): Promise { try { - return res.send( - await engineService.setBlockData(req.user, req.params.policyId, req.params.uuid, req.body) - ); + const engineService = new PolicyEngine(); + return await engineService.setBlockData(user, policyId, uuid, body); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Sends data to the specified block + */ + @Post('/:policyId/tag/:tagName/blocks') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ summary: 'Sends data to the specified block.', description: 'Sends data to the specified block.', }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'tagName', + type: 'string', + required: true, + description: 'Block name (Tag)', + example: 'block-tag', + }) + @ApiBody({ + description: 'Data', + type: Object + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: BlockDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/:policyId/tag/:tagName/blocks') + @ApiExtraModels(BlockDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setBlocksByTagName(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async setBlocksByTagName( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Param('tagName') tagName: string, + @Body() body: any + ): Promise { try { - return res.send(await engineService.setBlockDataByTag(req.user, req.params.policyId, req.params.tagName, req.body)); + const engineService = new PolicyEngine(); + return await engineService.setBlockDataByTag(user, policyId, tagName, body); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Requests block + */ + @Get('/:policyId/tag/:tagName') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ - summary: 'Requests block data.', + summary: 'Requests block config.', description: 'Requests block data by tag. Only users with a role that described in block are allowed to make the request.', }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'tagName', + type: 'string', + required: true, + description: 'Block name (Tag)', + example: 'block-tag', + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: BlockDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/tag/:tagName') + @ApiExtraModels(BlockDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getBlockByTagName(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async getBlockByTagName( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Param('tagName') tagName: string + ): Promise { try { - return res.send(await engineService.getBlockByTagName(req.user, req.params.policyId, req.params.tagName)); + const engineService = new PolicyEngine(); + return await engineService.getBlockByTagName(user, policyId, tagName); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Requests block data + */ + @Get('/:policyId/tag/:tagName/blocks') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) @ApiOperation({ summary: 'Requests block data.', description: 'Requests block data by tag. Only users with a role that described in block are allowed to make the request.', }) - @ApiSecurity('bearerAuth') + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'tagName', + type: 'string', + required: true, + description: 'Block name (Tag)', + example: 'block-tag', + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: BlockDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Get('/:policyId/tag/:tagName/blocks') + @ApiExtraModels(BlockDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getBlocksByTagName(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async getBlocksByTagName( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Param('tagName') tagName: string, + ): Promise { try { - return res.send(await engineService.getBlockDataByTag(req.user, req.params.policyId, req.params.tagName)); + const engineService = new PolicyEngine(); + return await engineService.getBlockDataByTag(user, policyId, tagName); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Sends data to the specified block + */ @Get('/:policyId/blocks/:uuid/parents') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Requests block\'s parents.', + description: 'Requests block\'s parents. Only users with a role that described in block are allowed to make the request.', + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'uuid', + type: 'string', + required: true, + description: 'Block Identifier', + example: Examples.UUID + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: BlockDTO, + isArray: true + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(BlockDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getBlockParents(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async getBlockParents( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Param('uuid') uuid: string, + ): Promise { try { - return res.send(await engineService.getBlockParents(req.user, req.params.policyId, req.params.uuid)); + const engineService = new PolicyEngine(); + return await engineService.getBlockParents(user, policyId, uuid); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -1262,19 +1564,19 @@ export class PolicyApi { */ @Get('/:policyId/export/file') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_READ, + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Return policy and its artifacts in a zip file format for the specified policy.', description: 'Returns a zip file containing the published policy and all associated artifacts, i.e. schemas and VCs.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', @@ -1283,16 +1585,11 @@ export class PolicyApi { format: 'binary' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getPolicyExportFile( @AuthUser() user: IAuthUser, @@ -1301,14 +1598,14 @@ export class PolicyApi { ): Promise { try { const engineService = new PolicyEngine(); - const policyFile: any = await engineService.exportFile(user, policyId); - const policy: any = await engineService.getPolicy({ filters: policyId }); - res.setHeader('Content-disposition', `attachment; filename=${policy.name}`); - res.setHeader('Content-type', 'application/zip'); + const owner = new EntityOwner(user); + const policy = await engineService.accessPolicy(policyId, owner, 'read'); + const policyFile: any = await engineService.exportFile(policyId, owner); + res.header('Content-disposition', `attachment; filename=${policy.name}`); + res.header('Content-type', 'application/zip'); return res.send(policyFile); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } @@ -1317,48 +1614,39 @@ export class PolicyApi { */ @Get('/:policyId/export/message') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_READ, + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Return Heder message ID for the specified published policy.', description: 'Returns the Hedera message ID for the specified policy published onto IPFS.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) - @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + description: 'Message.', + type: ExportMessageDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(ExportMessageDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getPolicyExportMessage( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, - ): Promise { + ): Promise { try { const engineService = new PolicyEngine(); - return await engineService.exportMessage(user, policyId); + return await engineService.exportMessage(policyId, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } @@ -1367,19 +1655,19 @@ export class PolicyApi { */ @Get('/:policyId/export/xlsx') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_READ, + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Return policy and its artifacts in a xlsx file format for the specified policy.', description: 'Returns a xlsx file containing the published policy and all associated artifacts, i.e. schemas and VCs.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', @@ -1388,16 +1676,11 @@ export class PolicyApi { format: 'binary' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getPolicyExportXlsx( @AuthUser() user: IAuthUser, @@ -1406,97 +1689,127 @@ export class PolicyApi { ): Promise { try { const engineService = new PolicyEngine(); - const policyFile: any = await engineService.exportXlsx(user, policyId); - const policy: any = await engineService.getPolicy({ filters: policyId }); - res.setHeader('Content-disposition', `attachment; filename=${policy.name}`); - res.setHeader('Content-type', 'application/zip'); + const owner = new EntityOwner(user); + const policy = await engineService.accessPolicy(policyId, owner, 'read'); + const policyFile: any = await engineService.exportXlsx(policyId, owner); + res.header('Content-disposition', `attachment; filename=${policy.name}`); + res.header('Content-type', 'application/zip'); return res.send(policyFile); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } + /** + * Imports policy + */ + @Post('/import/message') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new policy from IPFS.', description: 'Imports new policy and all associated artifacts from IPFS into the local DB.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiQuery({ + name: 'versionOfTopicId', + type: String, + description: 'The topic ID of policy version.', + required: false, + example: '0.0.00000001' + }) + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, + }) @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, + description: 'Created policy.', + type: PolicyDTO, + isArray: true }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/import/message') + @ApiExtraModels(ImportMessageDTO, PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async importPolicyFromMessage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async importPolicyFromMessage( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO, + @Query('versionOfTopicId') versionOfTopicId?: string + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } const engineService = new PolicyEngine(); - const versionOfTopicId = req.query ? req.query.versionOfTopicId : null; try { - const policies = await engineService.importMessage( - req.user, - req.body.messageId, + await engineService.importMessage( + messageId, + new EntityOwner(user), versionOfTopicId, - req.body.metadata + body.metadata ); - return res.status(201).send(policies); + return await getOldResult(user); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } + /** + * Imports policy + */ + @Post('/push/import/message') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new policy from IPFS.', description: 'Imports new policy and all associated artifacts from IPFS into the local DB.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiQuery({ + name: 'versionOfTopicId', + type: String, + description: 'The topic ID of policy version.', + required: false, + example: '0.0.00000001' + }) + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/push/import/message') + @ApiExtraModels(ImportMessageDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async importPolicyFromMessageAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const messageId = req.body.messageId; - const versionOfTopicId = req.query ? req.query.versionOfTopicId : null; + async importPolicyFromMessageAsync( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO, + @Query('versionOfTopicId') versionOfTopicId?: string + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } const taskManager = new TaskManager(); - const task = taskManager.start( - TaskAction.IMPORT_POLICY_MESSAGE, - user.id - ); + const task = taskManager.start(TaskAction.IMPORT_POLICY_MESSAGE, user.id); RunFunctionAsync( async () => { const engineService = new PolicyEngine(); await engineService.importMessageAsync( - user, messageId, + new EntityOwner(user), versionOfTopicId, task, - req.body.metadata + body.metadata ); }, async (error) => { @@ -1507,75 +1820,95 @@ export class PolicyApi { }); } ); - return res.status(202).send(task); + return task; } + /** + * Import preview + */ + @Post('/import/message/preview') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Policy preview from IPFS.', description: 'Previews the policy from IPFS without loading it into the local DB.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, + }) @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, + description: 'Policy preview.', + type: PolicyPreviewDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/import/message/preview') + @ApiExtraModels(ImportMessageDTO, PolicyPreviewDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async importMessage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + async importMessage( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } try { - return res.send(await engineService.importMessagePreview(req.user, req.body.messageId)); + const engineService = new PolicyEngine(); + return await engineService.importMessagePreview(messageId, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Import preview + */ + @Post('/push/import/message/preview') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Policy preview from IPFS.', description: 'Previews the policy from IPFS without loading it into the local DB.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @ApiSecurity('bearerAuth') - @Post('/push/import/message/preview') + @ApiExtraModels(ImportMessageDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async importFromMessagePreview(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const messageId = req.body.messageId; + async importFromMessagePreview( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO + ) { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.PREVIEW_POLICY_MESSAGE, user.id); RunFunctionAsync(async () => { const engineService = new PolicyEngine(); - await engineService.importMessagePreviewAsync(user, messageId, task); + await engineService.importMessagePreviewAsync(messageId, new EntityOwner(user), task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: 'Unknown error: ' + error.message }); }); - - return res.status(202).send(task); + return task; } /** @@ -1583,18 +1916,19 @@ export class PolicyApi { */ @Post('/import/file') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Imports new policy from a zip file.', description: 'Imports new policy and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'versionOfTopicId', type: String, - description: 'Topic Id', - required: false + description: 'The topic ID of policy version.', + required: false, + example: '0.0.00000001' }) @ApiBody({ description: 'A zip file containing policy config.', @@ -1602,35 +1936,27 @@ export class PolicyApi { type: String }) @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + description: 'Created policy.', + type: PolicyDTO, + isArray: true }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(PolicyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) async importPolicyFromFile( @AuthUser() user: IAuthUser, @Body() file: any, - @Query('versionOfTopicId') versionOfTopicId, - @Response() res: any - ): Promise { - const engineService = new PolicyEngine(); + @Query('versionOfTopicId') versionOfTopicId?: string + ): Promise { try { - const policies = await engineService.importFile(user, file, versionOfTopicId); - return res.status(201).send(policies); + const engineService = new PolicyEngine(); + await engineService.importFile(file, new EntityOwner(user), versionOfTopicId); + return await getOldResult(user); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -1639,18 +1965,19 @@ export class PolicyApi { */ @Post('/import/file-metadata') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_CREATE, + //UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Imports new policy from a zip file with metadata.', description: 'Imports new policy and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'versionOfTopicId', type: String, - description: 'Topic Id', - required: false + description: 'The topic ID of policy version.', + required: false, + example: '0.0.00000001' }) @ApiConsumes('multipart/form-data') @ApiBody({ @@ -1672,27 +1999,21 @@ export class PolicyApi { }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: PolicyDTO, + isArray: true }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - @HttpCode(HttpStatus.CREATED) + @ApiExtraModels(InternalServerErrorDTO) @UseInterceptors(AnyFilesInterceptor()) + @HttpCode(HttpStatus.CREATED) async importPolicyFromFileWithMetadata( @AuthUser() user: IAuthUser, @UploadedFiles() files: any, - @Query('versionOfTopicId') versionOfTopicId, - ): Promise { + @Query('versionOfTopicId') versionOfTopicId?: string + ): Promise { try { const policyFile = files.find( (item) => item.fieldname === 'policyFile' @@ -1704,18 +2025,15 @@ export class PolicyApi { (item) => item.fieldname === 'metadata' ); const engineService = new PolicyEngine(); - return await engineService.importFile( - user, + await engineService.importFile( policyFile.buffer, + new EntityOwner(user), versionOfTopicId, metadata?.buffer && JSON.parse(metadata.buffer.toString()) ); + return await getOldResult(user) } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } @@ -1724,18 +2042,19 @@ export class PolicyApi { */ @Post('/push/import/file') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Imports new policy from a zip file.', description: 'Imports new policy and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'versionOfTopicId', type: String, - description: 'Topic Id', - required: false + description: 'The topic ID of policy version.', + required: false, + example: '0.0.00000001' }) @ApiBody({ description: 'A zip file containing policy config.', @@ -1744,37 +2063,29 @@ export class PolicyApi { }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) async importPolicyFromFileAsync( @AuthUser() user: IAuthUser, @Body() file: any, - @Query('versionOfTopicId') versionOfTopicId, - @Response() res: any + @Query('versionOfTopicId') versionOfTopicId?: string ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.IMPORT_POLICY_FILE, user.id); RunFunctionAsync(async () => { const engineService = new PolicyEngine(); - await engineService.importFileAsync(user, file, versionOfTopicId, task); + await engineService.importFileAsync(file, new EntityOwner(user), versionOfTopicId, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: 'Unknown error: ' + error.message }); }); - return res.status(202).send(task); + return task; } /** @@ -1782,18 +2093,19 @@ export class PolicyApi { */ @Post('/push/import/file-metadata') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Imports new policy from a zip file with metadata.', description: 'Imports new policy and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'versionOfTopicId', type: String, - description: 'Topic Id', - required: false + description: 'The topic ID of policy version.', + required: false, + example: '0.0.00000001' }) @ApiConsumes('multipart/form-data') @ApiBody({ @@ -1815,27 +2127,20 @@ export class PolicyApi { }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - @HttpCode(HttpStatus.ACCEPTED) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @UseInterceptors(AnyFilesInterceptor()) + @HttpCode(HttpStatus.ACCEPTED) async importPolicyFromFileWithMetadataAsync( @AuthUser() user: IAuthUser, @UploadedFiles() files: any, - @Query('versionOfTopicId') versionOfTopicId, - ): Promise { + @Query('versionOfTopicId') versionOfTopicId?: string + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.IMPORT_POLICY_FILE, user.id); RunFunctionAsync( @@ -1851,8 +2156,8 @@ export class PolicyApi { ); const engineService = new PolicyEngine(); await engineService.importFileAsync( - user, policyFile.buffer, + new EntityOwner(user), versionOfTopicId, task, metadata?.buffer && JSON.parse(metadata.buffer.toString()) @@ -1874,9 +2179,9 @@ export class PolicyApi { */ @Post('/import/file/preview') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Policy preview from a zip file.', description: 'Previews the policy from a zip file without loading it into the local DB.' + ONLY_SR, @@ -1887,21 +2192,14 @@ export class PolicyApi { type: String }) @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + description: 'Policy preview.', + type: PolicyPreviewDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(PolicyPreviewDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async importPolicyFromFilePreview( @AuthUser() user: IAuthUser, @@ -1912,10 +2210,9 @@ export class PolicyApi { } try { const engineService = new PolicyEngine(); - return await engineService.importFilePreview(user, file); + return await engineService.importFilePreview(file, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -1924,19 +2221,19 @@ export class PolicyApi { */ @Post('/import/xlsx') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Imports new policy from a xlsx file.', description: 'Imports new policy and all associated artifacts, such as schemas and VCs, from the provided xlsx file into the local DB.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'A xlsx file containing policy config.', @@ -1949,16 +2246,11 @@ export class PolicyApi { 'type': 'object' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) async importPolicyFromXlsx( @AuthUser() user: IAuthUser, @@ -1970,10 +2262,9 @@ export class PolicyApi { } try { const engineService = new PolicyEngine(); - return await engineService.importXlsx(user, file, policyId); + return await engineService.importXlsx(file, new EntityOwner(user), policyId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -1982,19 +2273,19 @@ export class PolicyApi { */ @Post('/push/import/xlsx') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Imports new policy from a xlsx file.', description: 'Imports new policy and all associated artifacts, such as schemas and VCs, from the provided xlsx file into the local DB.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'A xlsx file containing policy config.', @@ -2003,26 +2294,19 @@ export class PolicyApi { }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) async importPolicyFromXlsxAsync( @AuthUser() user: IAuthUser, @Query('policyId') policyId: string, @Body() file: ArrayBuffer - ): Promise { + ): Promise { if (!file) { throw new HttpException('File in body is empty', HttpStatus.UNPROCESSABLE_ENTITY) } @@ -2030,7 +2314,7 @@ export class PolicyApi { const task = taskManager.start(TaskAction.IMPORT_POLICY_FILE, user.id); RunFunctionAsync(async () => { const engineService = new PolicyEngine(); - await engineService.importXlsxAsync(user, file, policyId, task); + await engineService.importXlsxAsync(file, new EntityOwner(user), policyId, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: 'Unknown error: ' + error.message }); @@ -2043,9 +2327,9 @@ export class PolicyApi { */ @Post('/import/xlsx/preview') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Policy preview from a xlsx file.', description: 'Previews the policy from a xlsx file without loading it into the local DB.' + ONLY_SR, @@ -2061,16 +2345,11 @@ export class PolicyApi { 'type': 'object' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async importPolicyFromXlsxPreview( @AuthUser() user: IAuthUser, @@ -2081,273 +2360,505 @@ export class PolicyApi { } try { const engineService = new PolicyEngine(); - return await engineService.importXlsxPreview(user, file); + return await engineService.importXlsxPreview(file, new EntityOwner(user)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** - * @param req + * About */ @Get('/blocks/about') - @HttpCode(HttpStatus.OK) + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + Permissions.MODULES_MODULE_UPDATE, + Permissions.TOOLS_TOOL_UPDATE + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Returns block descriptions.', + description: 'Returns block descriptions.' + ONLY_SR, + }) + @ApiOkResponse({ + description: 'Block descriptions.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @UseCache({ ttl: CACHE.LONG_TTL }) - async getBlockAbout(@Req() req) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const engineService = new PolicyEngine(); + @HttpCode(HttpStatus.OK) + async getBlockAbout() { try { + const engineService = new PolicyEngine(); return await engineService.blockAbout(); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get virtual users + */ @Get('/:policyId/dry-run/users') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Returns virtual users.', + description: 'Returns virtual users.' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Virtual users.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getDryRunUsers(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getDryRunUsers( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ) { const engineService = new PolicyEngine(); - let policy; - try { - policy = await engineService.getPolicy({ filters: req.params.policyId }) as any; - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!policy) { - throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) - } - if (policy.owner !== req.user.did) { - throw new HttpException('Invalid owner.', HttpStatus.FORBIDDEN) - } - if (policy.status !== PolicyType.DRY_RUN) { - throw new HttpException('Invalid status.', HttpStatus.FORBIDDEN) - } + const owner = new EntityOwner(user); + await engineService.accessPolicy(policyId, owner, 'read'); try { - return res.send(await engineService.getVirtualUsers(req.params.policyId)); + return await engineService.getVirtualUsers(policyId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Create virtual user + */ @Post('/:policyId/dry-run/user') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Creates virtual users.', + description: 'Creates virtual users.' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Virtual users.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async setDryRunUser(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async setDryRunUser( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ) { const engineService = new PolicyEngine(); - let policy; - try { - policy = await engineService.getPolicy({ filters: req.params.policyId }) as any; - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!policy) { - throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) - } - if (policy.owner !== req.user.did) { - throw new HttpException('Invalid owner.', HttpStatus.FORBIDDEN) - } - if (policy.status !== PolicyType.DRY_RUN) { - throw new HttpException('Invalid status.', HttpStatus.FORBIDDEN) - } + const owner = new EntityOwner(user); + await engineService.accessPolicy(policyId, owner, 'read'); try { - return res.status(201).send(await engineService.createVirtualUser(req.params.policyId, req.user.did)); + return await engineService.createVirtualUser(policyId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Change virtual user + */ @Post('/:policyId/dry-run/login') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Change active virtual user.', + description: 'Change active virtual user.' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Credentials.', + type: Object + }) + @ApiOkResponse({ + description: 'Virtual users.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async loginDryRunUser(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async loginDryRunUser( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: any + ) { const engineService = new PolicyEngine(); - let policy; - try { - policy = await engineService.getPolicy({ filters: req.params.policyId }) as any; - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!policy) { - throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) - } - if (policy.owner !== req.user.did) { - throw new HttpException('Invalid owner.', HttpStatus.FORBIDDEN) - } - if (policy.status !== PolicyType.DRY_RUN) { - throw new HttpException('Invalid status.', HttpStatus.FORBIDDEN) - } + const owner = new EntityOwner(user); + await engineService.accessPolicy(policyId, owner, 'read'); try { - return res.send(await engineService.loginVirtualUser(req.params.policyId, req.body.did)); + return await engineService.loginVirtualUser(policyId, body.did, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Clear dry-run state. + */ @Post('/:policyId/dry-run/restart') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Clear dry-run state.', + description: 'Clear dry-run state.' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiBody({ + description: '.', + }) + @ApiOkResponse({ + description: '.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async restartDryRun(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async restartDryRun( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: any + ) { const engineService = new PolicyEngine(); - let policy; - try { - policy = await engineService.getPolicy({ filters: req.params.policyId }) as any; - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!policy) { - throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) - } - if (policy.owner !== req.user.did) { - throw new HttpException('Invalid owner.', HttpStatus.FORBIDDEN) - } + const owner = new EntityOwner(user); + const policy = await engineService.accessPolicy(policyId, owner, 'read'); if (policy.status !== PolicyType.DRY_RUN) { throw new HttpException('Invalid status.', HttpStatus.FORBIDDEN) } try { - return res.json(await engineService.restartDryRun(req.body, req.user, req.params.policyId)); + return await engineService.restartDryRun(body, owner, policyId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get dry-run details + */ @Get('/:policyId/dry-run/transactions') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Get dry-run details (Transactions).', + description: 'Get dry-run details (Transactions).' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiOkResponse({ + description: 'Transactions.', + isArray: true, + headers: pageHeader, + type: Object, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getDryRunTransactions(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getDryRunTransactions( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Param('policyId') policyId: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ) { const engineService = new PolicyEngine(); - let policy; - try { - policy = await engineService.getPolicy({ filters: req.params.policyId }) as any; - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!policy) { - throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) - } - if (policy.owner !== req.user.did) { - throw new HttpException('Invalid owner.', HttpStatus.FORBIDDEN) - } + const owner = new EntityOwner(user); + await engineService.accessPolicy(policyId, owner, 'read'); try { - let pageIndex: any; - let pageSize: any; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } - const [data, count] = await engineService.getVirtualDocuments(req.params.policyId, 'transactions', pageIndex, pageSize) - return res.setHeader('X-Total-Count', count).json(data); + const [data, count] = await engineService.getVirtualDocuments(policyId, 'transactions', owner, pageIndex, pageSize) + return res.header('X-Total-Count', count).send(data); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get dry-run details + */ @Get('/:policyId/dry-run/artifacts') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Get dry-run details (Artifacts).', + description: 'Get dry-run details (Artifacts).' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiOkResponse({ + description: 'Artifacts.', + isArray: true, + headers: pageHeader, + type: Object, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getDryRunArtifacts(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getDryRunArtifacts( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Param('policyId') policyId: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ) { const engineService = new PolicyEngine(); - let policy; - try { - policy = await engineService.getPolicy({ filters: req.params.policyId }) as any; - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!policy) { - throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) - } - if (policy.owner !== req.user.did) { - throw new HttpException('Invalid owner.', HttpStatus.FORBIDDEN) - } - + const owner = new EntityOwner(user); + await engineService.accessPolicy(policyId, owner, 'read'); try { - let pageIndex: any; - let pageSize: any; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } - const [data, count] = await engineService.getVirtualDocuments(req.params.policyId, 'artifacts', pageIndex, pageSize); - return res.setHeader('X-Total-Count', count).json(data); + const [data, count] = await engineService.getVirtualDocuments(policyId, 'artifacts', owner, pageIndex, pageSize); + return res.header('X-Total-Count', count).send(data); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get dry-run details + */ @Get('/:policyId/dry-run/ipfs') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Get dry-run details (Files).', + description: 'Get dry-run details (Files).' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 20 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiOkResponse({ + description: 'Files.', + isArray: true, + headers: pageHeader, + type: Object, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getDryRunIpfs(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getDryRunIpfs( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Param('policyId') policyId: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ) { const engineService = new PolicyEngine(); - let policy; - try { - policy = await engineService.getPolicy({ filters: req.params.policyId }) as any; - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!policy) { - throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) - } - if (policy.owner !== req.user.did) { - throw new HttpException('Invalid owner.', HttpStatus.FORBIDDEN) - } + const owner = new EntityOwner(user); + await engineService.accessPolicy(policyId, owner, 'read'); try { - let pageIndex: any; - let pageSize: any; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } - const [data, count] = await engineService.getVirtualDocuments(req.params.policyId, 'ipfs', pageIndex, pageSize) - return res.setHeader('X-Total-Count', count).json(data); + const [data, count] = await engineService.getVirtualDocuments(policyId, 'ipfs', owner, pageIndex, pageSize) + return res.header('X-Total-Count', count).send(data); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get policy links + */ @Get('/:policyId/multiple') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Requests policy links.', + description: 'Requests policy links. Only users with a role that described in block are allowed to make the request.', + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getMultiplePolicies(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async getMultiplePolicies( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + ) { try { - return res.send(await engineService.getMultiPolicy(req.user, req.params.policyId)); + const engineService = new PolicyEngine(); + return await engineService.getMultiPolicy(new EntityOwner(user), policyId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Set policy links + */ @Post('/:policyId/multiple/') + @Auth( + Permissions.POLICIES_POLICY_EXECUTE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Creates policy link.', + description: 'Creates policy link. Only users with a role that described in block are allowed to make the request.', + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID + }) + @ApiBody({ + description: '', + type: Object + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setMultiplePolicies(@Req() req, @Response() res) { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - const engineService = new PolicyEngine(); + async setMultiplePolicies( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() body: any + ) { try { - return res.send(await engineService.setMultiPolicy(req.user, req.params.policyId, req.body)); + const engineService = new PolicyEngine(); + return await engineService.setMultiPolicy(new EntityOwner(user), policyId, body); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** + * Get all categories */ @Get('/methodologies/categories') @ApiOperation({ @@ -2361,22 +2872,23 @@ export class PolicyApi { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @HttpCode(HttpStatus.ACCEPTED) + @ApiExtraModels(InternalServerErrorDTO) @UseCache() + @HttpCode(HttpStatus.ACCEPTED) async getPolicyCategoriesAsync(): Promise { try { const projectService = new ProjectService(); return await projectService.getPolicyCategories(); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get filtered policies + */ @Post('/methodologies/search') @ApiOperation({ summary: 'Get filtered policies', @@ -2388,7 +2900,7 @@ export class PolicyApi { examples: { Filter1: { value: { - categoryIds: ['000000000000000000000001', '000000000000000000000002'], + categoryIds: [Examples.DB_ID, Examples.DB_ID], text: 'abc' } } @@ -2396,29 +2908,23 @@ export class PolicyApi { }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, + type: PolicyDTO, + isArray: true }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async getPoliciesByCategory(@Req() req, @Response() res): Promise { - const engineService = new PolicyEngine(); - - const categoryIds = req.body.categoryIds; - const text = req.body.text; - + async getPoliciesByCategory( + @Body() body: any + ): Promise { try { - const policies = await engineService.getPoliciesByCategoriesAndText(categoryIds, text); - return res.send(policies); + const engineService = new PolicyEngine(); + return engineService.getPoliciesByCategoriesAndText(body.categoryIds, body.text); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/profile.ts b/api-gateway/src/api/service/profile.ts index 0157dd3c7d..687218f937 100644 --- a/api-gateway/src/api/service/profile.ts +++ b/api-gateway/src/api/service/profile.ts @@ -1,35 +1,30 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { DidDocumentStatus, SchemaEntity, TaskAction, TopicType, UserRole } from '@guardian/interfaces'; +import { DidDocumentStatus, Permissions, SchemaEntity, TaskAction, TopicType } from '@guardian/interfaces'; import { IAuthUser, Logger, RunFunctionAsync } from '@guardian/common'; -import { TaskManager } from '../../helpers/task-manager.js'; -import { ServiceError } from '../../helpers/service-requests-base.js'; import { Controller, Get, HttpCode, HttpException, HttpStatus, Put, Param, Post, Body } from '@nestjs/common'; -import { AuthUser } from '../../auth/authorization-helper.js'; -import { Auth } from '../../auth/auth.decorator.js'; -import { ApiBody, ApiForbiddenResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiSecurity, ApiTags, ApiUnauthorizedResponse } from '@nestjs/swagger'; -import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator.js'; -import { ProfileDTO, InternalServerErrorDTO, TaskDTO, CredentialsDTO, DidDocumentDTO, DidDocumentStatusDTO, DidDocumentWithKeyDTO, DidKeyStatusDTO } from '../../middlewares/validation/schemas/index.js'; +import { ApiBody, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'; +import { ProfileDTO, InternalServerErrorDTO, TaskDTO, CredentialsDTO, DidDocumentDTO, DidDocumentStatusDTO, DidDocumentWithKeyDTO, DidKeyStatusDTO } from '#middlewares'; +import { AuthUser, Auth } from '#auth'; import { CACHE } from '../../constants/index.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { UseCache, InternalException, Guardians, TaskManager, ServiceError } from '#helpers'; @Controller('profiles') @ApiTags('profiles') export class ProfileApi { /** - * Get user.profile + * Get user profile. */ @Get('/:username/') @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR + Permissions.PROFILES_USER_READ + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Returns user account info.', description: 'Returns user account information. For users with the Standard Registry role it also returns address book and VC document information.', }) - @ApiImplicitParam({ + @ApiParam({ name: 'username', type: String, description: 'The name of the user for whom to fetch the information', @@ -40,20 +35,15 @@ export class ProfileApi { description: 'Successful operation.', type: ProfileDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(ProfileDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getProfile( @AuthUser() user: IAuthUser - ): Promise { + ): Promise { const guardians = new Guardians(); try { let didDocument: any = null; @@ -100,20 +90,20 @@ export class ProfileApi { return { username: user.username, role: user.role, + permissionsGroup: user.permissionsGroup, + permissions: user.permissions, did: user.did, parent: user.parent, hederaAccountId: user.hederaAccountId, confirmed: !!(didDocument && didDocument.status === DidDocumentStatus.CREATE), failed: !!(didDocument && didDocument.status === DidDocumentStatus.FAILED), - hederaAccountKey: null, topicId: topic?.topicId, parentTopicId: topic?.parent, didDocument, vcDocument }; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.UNPROCESSABLE_ENTITY); + await InternalException(error); } } @@ -122,16 +112,16 @@ export class ProfileApi { */ @Put('/:username') @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR + Permissions.PROFILES_USER_UPDATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Sets Hedera credentials for the user.', description: 'Sets Hedera credentials for the user. For users with the Standard Registry role it also creates an address book.' }) - @ApiImplicitParam({ + @ApiParam({ name: 'username', type: String, description: 'The name of the user for whom to update the information.', @@ -146,25 +136,19 @@ export class ProfileApi { @ApiOkResponse({ description: 'Created.', }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(CredentialsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.NO_CONTENT) async setUserProfile( @AuthUser() user: IAuthUser, @Body() profile: any - ): Promise { + ): Promise { const username: string = user.username; const guardians = new Guardians(); await guardians.createUserProfileCommon(username, profile); - return; } /** @@ -172,16 +156,16 @@ export class ProfileApi { */ @Put('/push/:username') @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR + Permissions.PROFILES_USER_UPDATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Sets Hedera credentials for the user.', description: 'Sets Hedera credentials for the user. For users with the Standard Registry role it also creates an address book.' }) - @ApiImplicitParam({ + @ApiParam({ name: 'username', type: String, description: 'The name of the user for whom to update the information.', @@ -197,21 +181,16 @@ export class ProfileApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(CredentialsDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) async setUserProfileAsync( @AuthUser() user: IAuthUser, @Body() profile: any - ): Promise { + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.CONNECT_USER, user.id); const username: string = user.username; @@ -230,16 +209,16 @@ export class ProfileApi { */ @Get('/:username/balance') @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER, - UserRole.AUDITOR + Permissions.PROFILES_BALANCE_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + // UserRole.AUDITOR ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Returns user\'s Hedera account balance.', description: 'Requests Hedera account balance. Only users with the Installer role are allowed to make the request.' }) - @ApiImplicitParam({ + @ApiParam({ name: 'username', type: String, description: 'The name of the user for whom to fetch the balance.', @@ -250,22 +229,17 @@ export class ProfileApi { description: 'Successful operation.', type: String }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(InternalServerErrorDTO) @UseCache({ ttl: CACHE.SHORT_TTL }) + @HttpCode(HttpStatus.OK) async getUserBalance( @AuthUser() user: IAuthUser, @Param('username') username: string - ): Promise { + ): Promise { if (!user.did) { return null; } @@ -283,14 +257,14 @@ export class ProfileApi { */ @Put('/restore/:username') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.PROFILES_RESTORE_ALL, + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Restore user data (policy, DID documents, VC documents).', description: 'Restore user data (policy, DID documents, VC documents).' }) - @ApiImplicitParam({ + @ApiParam({ name: 'username', type: String, description: 'The name of the user for whom to restore the information.', @@ -306,21 +280,16 @@ export class ProfileApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(CredentialsDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) async restoreUserProfile( @AuthUser() user: IAuthUser, @Body() profile: any - ): Promise { + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.RESTORE_USER_PROFILE, user.id); const username: string = user.username; @@ -339,14 +308,14 @@ export class ProfileApi { */ @Put('/restore/topics/:username') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.PROFILES_RESTORE_ALL, + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'List of available recovery topics.', description: 'List of available recovery topics.' }) - @ApiImplicitParam({ + @ApiParam({ name: 'username', type: String, description: 'The name of the user for whom to restore the information.', @@ -362,21 +331,16 @@ export class ProfileApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(CredentialsDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) async restoreTopic( @AuthUser() user: IAuthUser, @Body() profile: any - ): Promise { + ): Promise { const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.GET_USER_TOPICS, user.id); const username: string = user.username; @@ -395,10 +359,10 @@ export class ProfileApi { */ @Post('/did-document/validate') @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER + Permissions.PROFILES_USER_UPDATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Validate DID document format.', description: 'Validate DID document format.', @@ -412,21 +376,16 @@ export class ProfileApi { description: 'Successful operation.', type: DidDocumentStatusDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(DidDocumentDTO, DidDocumentStatusDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async validateDidDocument( @AuthUser() user: IAuthUser, @Body() document: any - ) { + ): Promise { if (!document) { throw new HttpException('Body is empty', HttpStatus.UNPROCESSABLE_ENTITY) } @@ -434,8 +393,7 @@ export class ProfileApi { const guardians = new Guardians(); return await guardians.validateDidDocument(document); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -444,10 +402,10 @@ export class ProfileApi { */ @Post('/did-keys/validate') @Auth( - UserRole.STANDARD_REGISTRY, - UserRole.USER + Permissions.PROFILES_USER_UPDATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Validate DID document keys.', description: 'Validate DID document keys.', @@ -461,21 +419,16 @@ export class ProfileApi { description: 'Successful operation.', type: DidKeyStatusDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(DidKeyStatusDTO, DidDocumentWithKeyDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async validateDidKeys( @AuthUser() user: IAuthUser, @Body() body: any - ) { + ): Promise { if (!body) { throw new HttpException('Body is empty', HttpStatus.UNPROCESSABLE_ENTITY) } @@ -490,8 +443,7 @@ export class ProfileApi { const guardians = new Guardians(); return await guardians.validateDidKeys(document, keys); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/project.ts b/api-gateway/src/api/service/project.ts index d499af73e9..e0585ee0b0 100644 --- a/api-gateway/src/api/service/project.ts +++ b/api-gateway/src/api/service/project.ts @@ -1,13 +1,9 @@ -import { Logger } from '@guardian/common'; import { ClientProxy } from '@nestjs/microservices'; -import { Body, Controller, Get, HttpCode, HttpException, HttpStatus, Inject, Post, Req, Response } from '@nestjs/common'; -import { ApiBody, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, getSchemaPath } from '@nestjs/swagger'; -import { ProjectService } from '../../helpers/projects.js'; -import { ProjectDTO, PropertiesDTO } from '../../middlewares/validation/schemas/projects.js'; -import { CompareDocumentsDTO, FilterDocumentsDTO, InternalServerErrorDTO } from '../../middlewares/validation/schemas/index.js'; -import { Guardians } from '../../helpers/guardians.js'; +import { Body, Controller, Get, HttpCode, HttpException, HttpStatus, Inject, Post, Version } from '@nestjs/common'; +import { ApiBody, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { ProjectDTO, PropertiesDTO, CompareDocumentsDTO, CompareDocumentsV2DTO, FilterDocumentsDTO, InternalServerErrorDTO, Examples } from '#middlewares'; import { CACHE } from '../../constants/index.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { UseCache, Guardians, InternalException, ProjectService } from '#helpers'; /** * Projects route @@ -26,11 +22,6 @@ export class ProjectsAPI { summary: 'Search projects', description: 'Search projects by filters', }) - @ApiOkResponse({ - description: 'Successful operation.', - isArray: true, - type: ProjectDTO, - }) @ApiBody({ description: 'The question of choosing a methodology', required: true, @@ -41,25 +32,27 @@ export class ProjectsAPI { } } }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + type: ProjectDTO, + }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ProjectDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async projectSearch(@Req() req, @Response() res): Promise { - const projectService = new ProjectService(); - - const categoryIds = req.body.categoryIds; - const policyIds = req.body.policyIds; - + async projectSearch( + @Body() body: any + ): Promise { + const categoryIds = body?.categoryIds; + const policyIds = body?.policyIds; try { - const projects = await projectService.search(categoryIds, policyIds); - return res.send(projects); + const projectService = new ProjectService(); + return await projectService.search(categoryIds, policyIds); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -78,13 +71,13 @@ export class ProjectsAPI { examples: { Filter1: { value: { - documentId1: '000000000000000000000001', - documentId2: '000000000000000000000002' + documentId1: Examples.DB_ID, + documentId2: Examples.DB_ID } }, Filter2: { value: { - documentIds: ['000000000000000000000001', '000000000000000000000002'], + documentIds: [Examples.DB_ID, Examples.DB_ID], } } } @@ -97,8 +90,11 @@ export class ProjectsAPI { description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(FilterDocumentsDTO, CompareDocumentsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async compareDocuments(@Body() body, @Req() req): Promise { + async compareDocumentsV1( + @Body() body: FilterDocumentsDTO + ): Promise { const guardians = new Guardians(); const documentId1 = body ? body.documentId1 : null; const documentId2 = body ? body.documentId2 : null; @@ -143,7 +139,113 @@ export class ProjectsAPI { refLvl ); } catch (error) { - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); + } + } + + /** + * Compare documents + */ + @Post('/compare/documents') + @ApiOperation({ + summary: 'Compare documents.', + description: 'Compare documents.', + }) + @ApiBody({ + description: 'Filters.', + required: true, + type: FilterDocumentsDTO, + examples: { + Filter1: { + value: { + documentId1: Examples.DB_ID, + documentId2: Examples.DB_ID + } + }, + Filter2: { + value: { + documentIds: [Examples.DB_ID, Examples.DB_ID], + } + } + } + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: CompareDocumentsV2DTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @Version('2') + @ApiExtraModels(FilterDocumentsDTO, CompareDocumentsV2DTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async compareDocumentsV2( + @Body() body: FilterDocumentsDTO + ): Promise { + const guardians = new Guardians(); + const documentId1 = body ? body.documentId1 : null; + const documentId2 = body ? body.documentId2 : null; + const documentIds = body ? body.documentIds : null; + let ids: string[]; + if (documentId1 && documentId2) { + ids = [documentId1, documentId2]; + } else if (Array.isArray(documentIds) && documentIds.length > 1) { + ids = documentIds; + } + if (!ids) { + throw new HttpException('Invalid parameters', HttpStatus.UNPROCESSABLE_ENTITY); + } + + const idLvl = 0; + const eventsLvl = 0; + const propLvl = 2; + const childrenLvl = 0; + const user = null; + + let samePolicy: boolean = true; + const _data = await guardians.getVcDocuments({ id: ids }); + for (let index = 1; index < _data.length; index++) { + if (_data[index - 1].policyId !== _data[index].policyId) { + samePolicy = false; + break; + } + } + + const policyIds = _data.map((p: any) => p.policyId); + + const refLvl = samePolicy ? 'Revert' : 'Merge'; + const keyLvl = samePolicy ? 'Default' : 'Property'; + + try { + const comparationVpArray = await guardians.compareVPDocuments( + user, + null, + policyIds, + '1', + '2', + '2', + '0', + 0, + 'Direct' + ); + const comparationVc = await guardians.compareDocuments( + user, + null, + ids, + eventsLvl, + propLvl, + childrenLvl, + idLvl, + keyLvl, + refLvl + ); + return { + projects: comparationVc, + presentations: comparationVpArray + } + } catch (error) { + await InternalException(error); } } @@ -161,19 +263,17 @@ export class ProjectsAPI { }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO }) - @HttpCode(HttpStatus.ACCEPTED) + @ApiExtraModels(PropertiesDTO, InternalServerErrorDTO) @UseCache({ ttl: CACHE.LONG_TTL }) + @HttpCode(HttpStatus.ACCEPTED) async getPolicyProperties(): Promise { try { const projectService = new ProjectService(); return await projectService.getPolicyProperties(); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/record.ts b/api-gateway/src/api/service/record.ts index c0d186a390..79540af66e 100644 --- a/api-gateway/src/api/service/record.ts +++ b/api-gateway/src/api/service/record.ts @@ -1,42 +1,10 @@ -import { PolicyType, UserRole } from '@guardian/interfaces'; -import { PolicyEngine } from '../../helpers/policy-engine.js'; -import { IAuthUser, Logger } from '@guardian/common'; -import { Controller, Get, HttpCode, HttpException, HttpStatus, Post, Response, Param, Body } from '@nestjs/common'; -import { ApiBody, ApiForbiddenResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiSecurity, ApiTags, ApiUnauthorizedResponse } from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; -import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator.js'; -import { Guardians } from '../../helpers/guardians.js'; -import { Auth } from '../../auth/auth.decorator.js'; -import { AuthUser } from '../../auth/authorization-helper.js'; -import { RecordActionDTO, RecordStatusDTO, RunningDetailsDTO, RunningResultDTO } from '../../middlewares/validation/schemas/record.js'; - -/** - * Check policy - * @param policyId - * @param owner - */ -export async function checkPolicy(policyId: string, owner: string): Promise { - let policy: any; - try { - const engineService = new PolicyEngine(); - policy = await engineService.getPolicy({ filters: policyId }); - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!policy) { - throw new HttpException('Policy does not exist.', HttpStatus.NOT_FOUND) - } - if (policy.owner !== owner) { - throw new HttpException('Invalid owner.', HttpStatus.FORBIDDEN) - } - if (policy.status !== PolicyType.DRY_RUN) { - throw new HttpException('Invalid status.', HttpStatus.FORBIDDEN) - } - return policy; -} - -const ONLY_SR = ' Only users with the Standard Registry role are allowed to make the request.' +import { Permissions } from '@guardian/interfaces'; +import { EntityOwner, Guardians, InternalException, ONLY_SR, checkPolicy } from '#helpers'; +import { IAuthUser } from '@guardian/common'; +import { Controller, Get, HttpCode, HttpStatus, Post, Response, Param, Body } from '@nestjs/common'; +import { ApiBody, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'; +import { AuthUser, Auth } from '#auth'; +import { InternalServerErrorDTO, RecordActionDTO, RecordStatusDTO, RunningDetailsDTO, RunningResultDTO, Examples } from '#middlewares'; @Controller('record') @ApiTags('record') @@ -46,46 +14,41 @@ export class RecordApi { */ @Get('/:policyId/status') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Get recording or running status.', description: 'Get recording or running status.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', type: RecordStatusDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(RecordStatusDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getRecordStatus( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.getRecordStatus(policyId, user.did); + return await guardians.getRecordStatus(policyId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -94,19 +57,19 @@ export class RecordApi { */ @Post('/:policyId/recording/start') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Start recording.', description: 'Start recording.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'Object that contains options', @@ -117,29 +80,24 @@ export class RecordApi { description: 'Successful operation.', type: Boolean }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async startRecord( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, @Body() options: any ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.startRecording(policyId, user.did, options); + return await guardians.startRecording(policyId, owner, options); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -148,19 +106,19 @@ export class RecordApi { */ @Post('/:policyId/recording/stop') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Stop recording.', description: 'Stop recording.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'Object that contains options', @@ -172,18 +130,13 @@ export class RecordApi { schema: { type: 'string', format: 'binary' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + } }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async stopRecord( @AuthUser() user: IAuthUser, @@ -191,16 +144,16 @@ export class RecordApi { @Body() options: any, @Response() res: any ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - const result = await guardians.stopRecording(policyId, user.did, options); - res.setHeader('Content-disposition', `attachment; filename=${Date.now()}`); - res.setHeader('Content-type', 'application/zip'); + const result = await guardians.stopRecording(policyId, owner, options); + res.header('Content-disposition', `attachment; filename=${Date.now()}`); + res.header('Content-type', 'application/zip'); return res.send(result); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -209,47 +162,42 @@ export class RecordApi { */ @Get('/:policyId/recording/actions') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Get recorded actions.', description: 'Get recorded actions.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', isArray: true, type: RecordActionDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(RecordActionDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getRecordActions( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.getRecordedActions(policyId, user.did); + return await guardians.getRecordedActions(policyId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -258,19 +206,19 @@ export class RecordApi { */ @Post('/:policyId/running/start') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Run record from a zip file.', description: 'Run record from a zip file.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'A zip file containing record to be run.', @@ -281,30 +229,25 @@ export class RecordApi { description: 'Successful operation.', type: Boolean }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async runRecord( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, @Body() file: any ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const options = { file }; const guardians = new Guardians(); - return await guardians.runRecord(policyId, user.did, options); + return await guardians.runRecord(policyId, owner, options); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -313,19 +256,19 @@ export class RecordApi { */ @Post('/:policyId/running/stop') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Stop running.', description: 'Stop running.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'Object that contains options', @@ -336,29 +279,24 @@ export class RecordApi { description: 'Successful operation.', type: Boolean }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(RecordActionDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async stopRunning( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, @Body() options: any ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.stopRunning(policyId, user.did, options); + return await guardians.stopRunning(policyId, owner, options); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -367,46 +305,41 @@ export class RecordApi { */ @Get('/:policyId/running/results') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Get running results.', description: 'Get running results.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', type: RunningResultDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(RunningResultDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getRecordResults( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.getRecordResults(policyId, user.did); + return await guardians.getRecordResults(policyId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -415,46 +348,41 @@ export class RecordApi { */ @Get('/:policyId/running/details') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Get running details.', description: 'Get running details.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', type: RunningDetailsDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(RunningDetailsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getRecordDetails( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.getRecordDetails(policyId, user.did); + return await guardians.getRecordDetails(policyId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -463,19 +391,19 @@ export class RecordApi { */ @Post('/:policyId/running/fast-forward') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Fast Forward.', description: 'Fast Forward.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'Object that contains options', @@ -486,29 +414,24 @@ export class RecordApi { description: 'Successful operation.', type: Boolean }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async fastForward( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, @Body() options: any ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.fastForward(policyId, user.did, options); + return await guardians.fastForward(policyId, owner, options); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -517,19 +440,19 @@ export class RecordApi { */ @Post('/:policyId/running/retry') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Retry step.', description: 'Retry step.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'Object that contains options', @@ -540,29 +463,24 @@ export class RecordApi { description: 'Successful operation.', type: Boolean }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async retryStep( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, @Body() options: any ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.retryStep(policyId, user.did, options); + return await guardians.retryStep(policyId, owner, options); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -571,19 +489,19 @@ export class RecordApi { */ @Post('/:policyId/running/skip') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.POLICIES_RECORD_ALL + // UserRole.STANDARD_REGISTRY ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Skip step.', description: 'Skip step.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'policyId', type: String, description: 'Policy Id', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'Object that contains options', @@ -594,29 +512,24 @@ export class RecordApi { description: 'Successful operation.', type: Boolean }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async skipStep( @AuthUser() user: IAuthUser, @Param('policyId') policyId: string, @Body() options: any ) { - await checkPolicy(policyId, user.did); + const owner = new EntityOwner(user); + await checkPolicy(policyId, owner); try { const guardians = new Guardians(); - return await guardians.skipStep(policyId, user.did, options); + return await guardians.skipStep(policyId, owner, options); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/schema.ts b/api-gateway/src/api/service/schema.ts index 6ac7934b06..0892aba99a 100644 --- a/api-gateway/src/api/service/schema.ts +++ b/api-gateway/src/api/service/schema.ts @@ -1,178 +1,84 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { ISchema, SchemaCategory, SchemaEntity, SchemaHelper, SchemaStatus, StatusType, TaskAction, UserRole } from '@guardian/interfaces'; + +import { ISchema, Permissions, SchemaCategory, SchemaEntity, SchemaHelper, SchemaStatus, StatusType, TaskAction } from '@guardian/interfaces'; import { IAuthUser, Logger, RunFunctionAsync, SchemaImportExport } from '@guardian/common'; -import { ApiBody, ApiExtraModels, ApiForbiddenResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiSecurity, ApiTags, ApiUnauthorizedResponse } from '@nestjs/swagger'; -import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Req, Response } from '@nestjs/common'; -import process from 'process'; -import { AuthUser, checkPermission } from '../../auth/authorization-helper.js'; +import { ApiParam, ApiQuery, ApiBody, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Query, Response } from '@nestjs/common'; +import { AuthUser, Auth } from '#auth'; import { Client, ClientProxy, Transport } from '@nestjs/microservices'; -import { TaskManager } from '../../helpers/task-manager.js'; -import { ServiceError } from '../../helpers/service-requests-base.js'; -import { SchemaUtils } from '../../helpers/schema-utils.js'; -import { ApiImplicitQuery } from '@nestjs/swagger/dist/decorators/api-implicit-query.decorator.js'; -import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator.js'; -import { ExportSchemaDTO, InternalServerErrorDTO, MessageSchemaDTO, SchemaDTO, SystemSchemaDTO, TaskDTO, VersionSchemaDTO } from '../../middlewares/validation/schemas/index.js'; -import { Auth } from '../../auth/auth.decorator.js'; +import { ExportSchemaDTO, InternalServerErrorDTO, MessageSchemaDTO, SchemaDTO, SystemSchemaDTO, TaskDTO, VersionSchemaDTO, Examples, pageHeader } from '#middlewares'; import { CACHE } from '../../constants/index.js'; -import { UseCache } from '../../helpers/decorators/cache.js'; - -const ONLY_SR = ' Only users with the Standard Registry role are allowed to make the request.' - -/** - * Prepare the schema pagination - * - * @param req - * @param user - */ -function prepareSchemaPagination(req: any, user: any, topicId?: string): any { - const options: any = {}; - options.pageIndex = undefined; - options.pageSize = undefined; - if (req.query && req.query.pageIndex && req.query.pageSize) { - options.pageIndex = req.query.pageIndex; - options.pageSize = req.query.pageSize; - } - if (req.query) { - options.category = req.query.category; - if (topicId) { - options.topicId = topicId; - } else { - options.policyId = req.query.policyId; - options.moduleId = req.query.moduleId; - options.toolId = req.query.toolId; - options.topicId = req.query.topicId; - } - } - options.owner = user.parent; - if (user.role === UserRole.STANDARD_REGISTRY) { - options.owner = user.did; - } - return options; -} - -/** - * Create new schema - * @param {ISchema} newSchema - * @param {string} owner - * @param {string} topicId - * @returns {Promise} - */ -export async function createSchema(newSchema: ISchema, owner: string, topicId?: string): Promise { - const guardians = new Guardians(); - newSchema.topicId = topicId; - newSchema.category = newSchema.category || SchemaCategory.POLICY; - SchemaHelper.checkSchemaKey(newSchema); - SchemaHelper.updateOwner(newSchema, owner); - const schemas = await guardians.createSchema(newSchema); - SchemaHelper.updatePermission(schemas, owner); - return schemas; -} - -/** - * Async create new schema - * @param {ISchema} newSchema - * @param {string} owner - * @param {string} topicId - * @param {any} task - */ -export async function createSchemaAsync(newSchema: ISchema, owner: string, topicId: string | undefined, task: any): Promise { - const taskManager = new TaskManager(); - const guardians = new Guardians(); - taskManager.addStatus(task.taskId, 'Check schema version', StatusType.PROCESSING); - newSchema.topicId = topicId; - newSchema.category = newSchema.category || SchemaCategory.POLICY; - SchemaHelper.checkSchemaKey(newSchema); - SchemaHelper.updateOwner(newSchema, owner); - await guardians.createSchemaAsync(newSchema, task); -} - -/** - * Copy schema - * @param iri - * @param topicId - * @param name - * @param owner - * @param task - */ -export async function copySchemaAsync(iri: string, topicId: string, name: string, owner: string, task: any): Promise { - const taskManager = new TaskManager(); - const guardians = new Guardians(); - taskManager.addStatus(task.taskId, 'Check schema version', StatusType.PROCESSING); - await guardians.copySchemaAsync(iri, topicId, name, owner, task); -} - -/** - * Update schema - * @param {ISchema} newSchema - * @param {string} owner - * @returns {Promise} - */ -export async function updateSchema(newSchema: ISchema, owner: string): Promise { - const guardians = new Guardians(); - const schema = await guardians.getSchemaById(newSchema.id); - if (!schema) { - throw new Error('Schema does not exist.'); - } - if (schema.creator !== owner) { - throw new Error('Invalid creator.'); - } - - SchemaHelper.checkSchemaKey(newSchema); - SchemaHelper.updateOwner(newSchema, owner); - const schemas = (await guardians.updateSchema(newSchema)); - SchemaHelper.updatePermission(schemas, owner); - return schemas; -} +import { Guardians, TaskManager, ServiceError, SchemaUtils, UseCache, ONLY_SR, InternalException, EntityOwner } from '#helpers'; +import process from 'process'; @Controller('schema') @ApiTags('schema') export class SingleSchemaApi { /** - * use cache 30s test - * @param req + * Returns schema by schema ID. */ @Get('/:schemaId') - @HttpCode(HttpStatus.OK) + @Auth() + @ApiOperation({ + summary: 'Returns schema by schema ID.', + description: 'Returns schema by schema ID.' + ONLY_SR, + }) + @ApiParam({ + name: 'schemaId', + type: String, + description: 'Schema ID', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: SchemaDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @UseCache({ ttl: CACHE.SHORT_TTL }) - async getSchema(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.AUDITOR, UserRole.USER)(req.user); + @HttpCode(HttpStatus.OK) + async getSchema( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + ): Promise { try { - const user = req.user; - const schemaId = req.params.schemaId; const guardians = new Guardians(); + const owner = new EntityOwner(user); const schema = await guardians.getSchemaById(schemaId); if (!schema) { - throw new HttpException('Schema not found', HttpStatus.NOT_FOUND) + throw new HttpException(`Schema not found.`, HttpStatus.NOT_FOUND); } - let owner = user.parent; - if (user.role === UserRole.STANDARD_REGISTRY) { - owner = user.did; + if (schema.system && !schema.active && schema.owner !== user.username && schema.owner !== owner.creator) { + throw new HttpException(`Schema not found.`, HttpStatus.NOT_FOUND); } - if (!schema.system && schema.owner && schema.owner !== owner) { - throw new HttpException('Invalid creator.', HttpStatus.FORBIDDEN) - - } - if (schema.system) { - schema.readonly = schema.readonly || schema.owner !== owner; - } else { - SchemaHelper.updatePermission([schema], owner); + if (!schema.system && schema.status !== SchemaStatus.PUBLISHED && schema.owner !== owner.owner) { + throw new HttpException(`Schema not found.`, HttpStatus.NOT_FOUND); } + SchemaHelper.updatePermission([schema], owner); return SchemaUtils.toOld(schema); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } + /** + * Returns all parent schemas. + */ @Get('/:schemaId/parents') - @HttpCode(HttpStatus.OK) - @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.AUDITOR ?, + // UserRole.USER ? + ) @ApiOperation({ summary: 'Returns all parent schemas.', description: 'Returns all parent schemas.', }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema identifier', @@ -183,39 +89,41 @@ export class SingleSchemaApi { isArray: true, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - async getSchemaParents(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.AUDITOR, UserRole.USER)(req.user); + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getSchemaParents( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + ): Promise { try { - const user = req.user; - const schemaId = req.params.schemaId; const guardians = new Guardians(); - const schemas = await guardians.getSchemaParents(schemaId, user?.did); + const owner = new EntityOwner(user); + const schemas = await guardians.getSchemaParents(schemaId, owner); return SchemaUtils.toOld(schemas); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } + /** + * Returns all parent schemas. + */ @Get('/:schemaId/tree') - @HttpCode(HttpStatus.OK) - @ApiExtraModels(InternalServerErrorDTO) - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.AUDITOR ?, + // UserRole.USER ? + ) @ApiOperation({ summary: 'Returns schema tree.', description: 'Returns schema tree.', }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema identifier', @@ -241,27 +149,22 @@ export class SingleSchemaApi { } } }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - async getSchemaTree(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.AUDITOR, UserRole.USER)(req.user); + @ApiExtraModels(InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getSchemaTree( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + ): Promise { try { - const user = req.user; - const schemaId = req.params.schemaId; const guardians = new Guardians(); - const tree = await guardians.getSchemaTree(schemaId, user?.did); - return tree; + const owner = new EntityOwner(user); + return await guardians.getSchemaTree(schemaId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } } @@ -269,7 +172,6 @@ export class SingleSchemaApi { @Controller('schemas') @ApiTags('schemas') export class SchemaApi { - @Client({ transport: Transport.NATS, options: { @@ -282,99 +184,119 @@ export class SchemaApi { client: ClientProxy; /** - * Get page + * 'Return a list of all schemas. */ @Get('/') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.AUDITOR ?, + // UserRole.USER ? + ) @ApiOperation({ summary: 'Return a list of all schemas.', description: 'Returns all schemas.', }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageIndex', type: Number, description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageSize', type: Number, description: 'The numbers of items to return', required: false, example: 20 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'category', type: String, description: 'Schema category', required: false, example: SchemaCategory.POLICY }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'policyId', type: String, description: 'Policy id', required: false, - example: '000000000000000000000001' + example: Examples.DB_ID }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'moduleId', type: String, description: 'Module id', required: false, - example: '000000000000000000000001' + example: Examples.DB_ID }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'toolId', type: String, description: 'Tool id', required: false, - example: '000000000000000000000001' + example: Examples.DB_ID }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'topicId', type: String, description: 'Topic id', required: false, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - 'type': 'integer' - }, - description: 'Total items in the collection.' - } - }, + headers: pageHeader, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getSchemasPage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.AUDITOR, UserRole.USER)(req.user); + async getSchemasPage( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + @Query('category') category?: string, + @Query('policyId') policyId?: string, + @Query('moduleId') moduleId?: string, + @Query('toolId') toolId?: string, + @Query('topicId') topicId?: string + ): Promise { try { const guardians = new Guardians(); - const user = req.user; - const options: any = prepareSchemaPagination(req, user); - const { items, count } = await guardians.getSchemasByOwner(options); - SchemaHelper.updatePermission(items, user.did); - return res.setHeader('X-Total-Count', count).json(SchemaUtils.toOld(items)); + const owner = new EntityOwner(user); + const options: any = {}; + if (pageSize) { + options.pageIndex = pageIndex; + options.pageSize = pageSize; + } + if (category) { + options.category = category; + } + if (topicId) { + options.topicId = topicId; + } + if (policyId) { + options.policyId = policyId; + } + if (moduleId) { + options.moduleId = moduleId; + } + if (toolId) { + options.toolId = toolId; + } + const { items, count } = await guardians.getSchemasByOwner(options, owner); + SchemaHelper.updatePermission(items, owner); + return res.header('X-Total-Count', count).send(SchemaUtils.toOld(items)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -382,33 +304,38 @@ export class SchemaApi { * Get page */ @Get('/:topicId') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.AUDITOR ?, + // UserRole.USER ? + ) @ApiOperation({ summary: 'Return a list of all schemas.', description: 'Returns all schemas.', }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', required: true, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageIndex', type: Number, description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageSize', type: Number, description: 'The numbers of items to return', required: false, example: 20 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'category', type: String, description: 'Schema category', @@ -418,40 +345,42 @@ export class SchemaApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - 'type': 'integer' - }, - description: 'Total items in the collection.' - } - }, + headers: pageHeader, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getSchemasPageByTopicId(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER, UserRole.AUDITOR)(req.user); + async getSchemasPageByTopicId( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Param('topicId') topicId: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + @Query('category') category?: string, + ): Promise { try { const guardians = new Guardians(); - const user = req.user; - const { topicId } = req.params; - const options = prepareSchemaPagination(req, user, topicId); - const { items, count } = await guardians.getSchemasByOwner(options); - SchemaHelper.updatePermission(items, user.did); - return res.setHeader('X-Total-Count', count).json(SchemaUtils.toOld(items)); + const owner = new EntityOwner(user); + const options: any = {}; + if (pageSize) { + options.pageIndex = pageIndex; + options.pageSize = pageSize; + } + if (category) { + options.category = category; + } + if (topicId) { + options.topicId = topicId; + } + const { items, count } = await guardians.getSchemasByOwner(options, owner); + SchemaHelper.updatePermission(items, owner); + return res.header('X-Total-Count', count).send(SchemaUtils.toOld(items)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -459,12 +388,12 @@ export class SchemaApi { * Get schema by type */ @Get('/type/:schemaType') - @ApiSecurity('bearerAuth') + @Auth() @ApiOperation({ summary: 'Finds the schema using the json document type.', description: 'Finds the schema using the json document type.', }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaType', type: String, description: 'Type', @@ -474,32 +403,31 @@ export class SchemaApi { description: 'Successful operation.', type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getSchemaByType(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER, UserRole.AUDITOR)(req.user) - let schema: any; + async getSchemaByType( + @AuthUser() user: IAuthUser, + @Param('schemaType') schemaType: string + ): Promise { + let schema: ISchema; try { const guardians = new Guardians(); - schema = await guardians.getSchemaByType(req.params.schemaType); - } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - if (!schema) { - throw new HttpException(`Schema not found: ${req.params.schemaType}`, HttpStatus.NOT_FOUND); - } - try { - return res.send({ + const owner = new EntityOwner(user); + schema = await guardians.getSchemaByType(schemaType); + if (!schema) { + throw new HttpException(`Schema not found: ${schemaType}`, HttpStatus.NOT_FOUND); + } + if (schema.system && !schema.active && schema.owner !== owner.username && schema.owner !== owner.creator) { + throw new HttpException(`Schema not found: ${schemaType}`, HttpStatus.NOT_FOUND); + } + if (!schema.system && schema.status !== SchemaStatus.PUBLISHED && schema.owner !== owner.owner) { + throw new HttpException(`Schema not found: ${schemaType}`, HttpStatus.NOT_FOUND); + } + return { uuid: schema.uuid, iri: schema.iri, name: schema.name, @@ -508,10 +436,9 @@ export class SchemaApi { documentURL: schema.documentURL, context: schema.context, contextURL: schema.contextURL, - }); + }; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -519,7 +446,13 @@ export class SchemaApi { * Get all schemas */ @Get('/list/all') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_READ, + Permissions.POLICIES_POLICY_READ, + Permissions.MODULES_MODULE_READ, + Permissions.TOOLS_TOOL_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Returns a list of schemas.', description: 'Returns a list of schemas.' + ONLY_SR, @@ -529,30 +462,26 @@ export class SchemaApi { isArray: true, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @UseCache() - async getAll(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @HttpCode(HttpStatus.OK) + async getAll( + @AuthUser() user: IAuthUser + ): Promise { try { - const user = req.user; const guardians = new Guardians(); if (user.did) { - return await guardians.getListSchemas(user.did); + const owner = new EntityOwner(user); + return await guardians.getListSchemas(owner); + } else { + return []; } - return []; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -560,19 +489,25 @@ export class SchemaApi { * Get sub schemas */ @Get('/list/sub') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_UPDATE, + Permissions.POLICIES_POLICY_UPDATE, + Permissions.MODULES_MODULE_UPDATE, + Permissions.TOOLS_TOOL_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Returns a list of schemas.', description: 'Returns a list of schemas.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'topicId', type: String, description: 'Topic Id', required: false, example: '0.0.1' }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'category', type: String, description: 'Schema category', @@ -584,33 +519,27 @@ export class SchemaApi { isArray: true, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @UseCache() - async getSub(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @HttpCode(HttpStatus.OK) + async getSub( + @AuthUser() user: IAuthUser, + @Query('category') category?: string, + @Query('topicId') topicId?: string + ): Promise { try { const guardians = new Guardians(); - if (!req.user.did) { + if (!user.did) { return []; } - return await guardians.getSubSchemas( - req.query.category, - req.query.topicId, - req.user.did - ); + const owner = new EntityOwner(user); + return await guardians.getSubSchemas(category, topicId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -618,17 +547,20 @@ export class SchemaApi { * Create Schema */ @Post('/:topicId') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new schema.', description: 'Creates a new schema.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', required: true, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) @ApiBody({ description: 'Object that contains a valid schema.', @@ -640,33 +572,30 @@ export class SchemaApi { isArray: true, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async createNewSchema(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async createNewSchema( + @AuthUser() user: IAuthUser, + @Param('topicId') topicId: string, + @Body() newSchema: SchemaDTO + ): Promise { try { - const user = req.user; - const newSchema = req.body; SchemaUtils.fromOld(newSchema); - const topicId = req.params.topicId; - const schemas = await createSchema( - newSchema, - user.did, - topicId, - ); - return res.status(201).json(SchemaUtils.toOld(schemas)); + const guardians = new Guardians(); + const owner = new EntityOwner(user); + newSchema.topicId = topicId; + newSchema.category = newSchema.category || SchemaCategory.POLICY; + SchemaHelper.checkSchemaKey(newSchema); + SchemaHelper.updateOwner(newSchema, owner); + const schemas = await guardians.createSchema(newSchema, owner); + SchemaHelper.updatePermission(schemas, owner); + return SchemaUtils.toOld(schemas); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -674,7 +603,10 @@ export class SchemaApi { * Create Schema (Async) */ @Post('/push/copy') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Copy schema.', description: 'Copy schema.' + ONLY_SR, @@ -686,48 +618,49 @@ export class SchemaApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - @Auth( - UserRole.STANDARD_REGISTRY, - ) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async copySchemaAsync(@Body() body: any, @AuthUser() user: any): Promise { + async copySchemaAsync( + @AuthUser() user: IAuthUser, + @Body() body: any + ): Promise { const taskManager = new TaskManager(); + const guardians = new Guardians(); + const owner = new EntityOwner(user); const task = taskManager.start(TaskAction.CREATE_SCHEMA, user.id); RunFunctionAsync(async () => { const { iri, topicId, name } = body; - await copySchemaAsync(iri, topicId, name, user.did, task); + taskManager.addStatus(task.taskId, 'Check schema version', StatusType.PROCESSING); + await guardians.copySchemaAsync(iri, topicId, name, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return task; } + /** * Create Schema (Async) */ @Post('/push/:topicId') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new schema.', description: 'Creates a new schema.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', required: true, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) @ApiBody({ description: 'Object that contains a valid schema.', @@ -738,45 +671,44 @@ export class SchemaApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(TaskDTO, SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async createNewSchemaAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const newSchema = req.body; - const topicId = (req.params.topicId === null || req.params.topicId === undefined) ? undefined : req.params.topicId; + async createNewSchemaAsync( + @AuthUser() user: IAuthUser, + @Param('topicId') topicId: string, + @Body() newSchema: SchemaDTO + ): Promise { + const owner = new EntityOwner(user); + const guardians = new Guardians(); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.CREATE_SCHEMA, user.id); RunFunctionAsync(async () => { SchemaUtils.fromOld(newSchema); - await createSchemaAsync( - newSchema, - user.did, - topicId, - task - ); + taskManager.addStatus(task.taskId, 'Check schema version', StatusType.PROCESSING); + newSchema.topicId = topicId; + newSchema.category = newSchema.category || SchemaCategory.POLICY; + SchemaHelper.checkSchemaKey(newSchema); + SchemaHelper.updateOwner(newSchema, owner); + await guardians.createSchemaAsync(newSchema, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } /** * Update Schema */ @Put('/') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Updates the schema.', description: 'Updates the schema.' + ONLY_SR, @@ -791,28 +723,24 @@ export class SchemaApi { isArray: true, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setSchema(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async setSchema( + @AuthUser() user: IAuthUser, + @Body() newSchema: SchemaDTO + ): Promise { try { - const user = req.user; - const newSchema = req.body; const guardians = new Guardians(); + const owner = new EntityOwner(user); const schema = await guardians.getSchemaById(newSchema.id); if (!schema) { throw new HttpException('Schema not found.', HttpStatus.NOT_FOUND) } - const error = SchemaUtils.checkPermission(schema, user, SchemaCategory.POLICY); + const error = SchemaUtils.checkPermission(schema, owner, SchemaCategory.POLICY); if (error) { throw new HttpException(error, HttpStatus.FORBIDDEN) } @@ -820,11 +748,13 @@ export class SchemaApi { throw new HttpException('Schema is published.', HttpStatus.UNPROCESSABLE_ENTITY) } SchemaUtils.fromOld(newSchema); - const schemas = await updateSchema(newSchema, user.did); - return res.json(SchemaUtils.toOld(schemas)); + SchemaHelper.checkSchemaKey(newSchema); + SchemaHelper.updateOwner(newSchema, owner); + const schemas = await guardians.updateSchema(newSchema, owner); + SchemaHelper.updatePermission(schemas, owner); + return SchemaUtils.toOld(schemas); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -832,50 +762,48 @@ export class SchemaApi { * Delete Schema */ @Delete('/:schemaId') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Deletes the schema with the provided schema ID.', description: 'Deletes the schema with the provided schema ID.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', isArray: true, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async deleteSchema(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; + async deleteSchema( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string + ): Promise { const guardians = new Guardians(); - const schemaId = req.params.schemaId; - let schema; + let schema: ISchema; + const owner = new EntityOwner(user); try { schema = await guardians.getSchemaById(schemaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } if (!schema) { throw new HttpException('Schema not found.', HttpStatus.NOT_FOUND) } - const error = SchemaUtils.checkPermission(schema, user, SchemaCategory.POLICY); + const error = SchemaUtils.checkPermission(schema, owner, SchemaCategory.POLICY); if (error) { throw new HttpException(error, HttpStatus.FORBIDDEN) } @@ -883,12 +811,11 @@ export class SchemaApi { throw new HttpException('Schema is published.', HttpStatus.UNPROCESSABLE_ENTITY) } try { - const schemas = (await guardians.deleteSchema(schemaId, user?.did, true) as ISchema[]); - SchemaHelper.updatePermission(schemas, user.did); - return res.json(SchemaUtils.toOld(schemas)); + const schemas = (await guardians.deleteSchema(schemaId, owner, true) as ISchema[]); + SchemaHelper.updatePermission(schemas, owner); + return SchemaUtils.toOld(schemas); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -896,17 +823,20 @@ export class SchemaApi { * Publish Schema */ @Put('/:schemaId/publish') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Publishes the schema with the provided schema ID.', description: 'Publishes the schema with the provided (internal) schema ID onto IPFS, sends a message featuring IPFS CID into the corresponding Hedera topic.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'Object that contains version.', @@ -923,40 +853,30 @@ export class SchemaApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - 'type': 'integer' - }, - description: 'Total items in the collection.' - } - }, + headers: pageHeader, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(VersionSchemaDTO, SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async publishSchema(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; + async publishSchema( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + @Body() option: VersionSchemaDTO, + @Response() res: any + ): Promise { const guardians = new Guardians(); - const schemaId = req.params.schemaId; - const { version } = req.body; + const { version } = option; let schema: ISchema; let allVersion: ISchema[]; + const owner = new EntityOwner(user); try { schema = await guardians.getSchemaById(schemaId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } if (!schema) { throw new HttpException('Schema not found.', HttpStatus.NOT_FOUND) @@ -964,10 +884,9 @@ export class SchemaApi { try { allVersion = await guardians.getSchemasByUUID(schema.uuid); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } - const error = SchemaUtils.checkPermission(schema, user, SchemaCategory.POLICY); + const error = SchemaUtils.checkPermission(schema, owner, SchemaCategory.POLICY); if (error) { throw new HttpException(error, HttpStatus.FORBIDDEN) } @@ -978,16 +897,14 @@ export class SchemaApi { throw new HttpException('Version already exists.', HttpStatus.UNPROCESSABLE_ENTITY) } try { - await guardians.publishSchema(schemaId, version, user.did); + await guardians.publishSchema(schemaId, version, owner); const { items, count } = await guardians.getSchemasByOwner({ - category: SchemaCategory.POLICY, - owner: user.did - }); - SchemaHelper.updatePermission(items, user.did); - return res.setHeader('X-Total-Count', count).json(SchemaUtils.toOld(items)); + category: SchemaCategory.POLICY + }, owner); + SchemaHelper.updatePermission(items, owner); + return res.header('X-Total-Count', count).send(SchemaUtils.toOld(items)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -995,17 +912,20 @@ export class SchemaApi { * Publish Schema (Async) */ @Put('/push/:schemaId/publish') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Publishes the schema with the provided schema ID.', description: 'Publishes the schema with the provided (internal) schema ID onto IPFS, sends a message featuring IPFS CID into the corresponding Hedera topic.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiBody({ description: 'Object that contains version.', @@ -1023,33 +943,30 @@ export class SchemaApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(TaskDTO, VersionSchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async publishSchemaAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const schemaId = req.params.schemaId; + async publishSchemaAsync( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + @Body() option: VersionSchemaDTO, + ): Promise { const guardians = new Guardians(); + const owner = new EntityOwner(user); const schema = await guardians.getSchemaById(schemaId); if (!schema) { throw new HttpException('Schema not found', HttpStatus.NOT_FOUND) } - const notAllowed = SchemaUtils.checkPermission(schema, user, SchemaCategory.POLICY); + const notAllowed = SchemaUtils.checkPermission(schema, owner, SchemaCategory.POLICY); if (notAllowed) { throw new HttpException(notAllowed, HttpStatus.FORBIDDEN) } const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.PUBLISH_SCHEMA, user.id); - const version = req.body.version; + const version = option.version; RunFunctionAsync(async () => { if (schema.status === SchemaStatus.PUBLISHED) { taskManager.addError(task.taskId, { code: 500, message: 'Schema is published.' }); @@ -1060,20 +977,23 @@ export class SchemaApi { taskManager.addError(task.taskId, { code: 500, message: 'Version already exists.' }); return; } - await guardians.publishSchemaAsync(schemaId, version, user.did, task); + await guardians.publishSchemaAsync(schemaId, version, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return res.status(202).send(task); + return task; } /** * Preview Schema from IPFS */ @Post('/import/message/preview') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Previews the schema from IPFS without loading it into the local DB.', description: 'Previews the schema from IPFS without loading it into the local DB.' + ONLY_SR, @@ -1085,38 +1005,34 @@ export class SchemaApi { examples: { Message: { value: { - messageId: '0000000000.000000000' + messageId: Examples.MESSAGE_ID } } } }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: SchemaDTO, + isArray: true }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(MessageSchemaDTO, SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async importFromMessagePreview(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async importFromMessagePreview( + @Body() body: MessageSchemaDTO + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } try { - const messageId = req.body.messageId; const guardians = new Guardians(); - const schemaToPreview = await guardians.previewSchemasByMessages([messageId]); - return res.json(schemaToPreview); + return await guardians.previewSchemasByMessages([messageId]); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -1124,7 +1040,10 @@ export class SchemaApi { * Preview Schema from IPFS (Async) */ @Post('/push/import/message/preview') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Previews the schema from IPFS without loading it into the local DB.', description: 'Previews the schema from IPFS without loading it into the local DB.' + ONLY_SR, @@ -1136,7 +1055,7 @@ export class SchemaApi { examples: { Message: { value: { - messageId: '0000000000.000000000' + messageId: Examples.MESSAGE_ID } } } @@ -1145,23 +1064,19 @@ export class SchemaApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(MessageSchemaDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async importFromMessagePreviewAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const messageId = req.body.messageId; + async importFromMessagePreviewAsync( + @AuthUser() user: IAuthUser, + @Body() body: MessageSchemaDTO + ): Promise { + const messageId = body?.messageId; if (!messageId) { - throw new HttpException('Schema ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); } const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.PREVIEW_SCHEMA_MESSAGE, user.id); @@ -1172,15 +1087,17 @@ export class SchemaApi { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } /** * Preview Schema from a zip file */ @Post('/import/file/preview') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Previews the schema from a zip file.', description: 'Previews the schema from a zip file.' + ONLY_SR, @@ -1191,35 +1108,27 @@ export class SchemaApi { }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - 'type': 'object' - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: SchemaDTO, + isArray: true }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async importFromFilePreview(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const zip = req.body; + async importFromFilePreview( + @Body() zip: any + ): Promise { if (!zip) { throw new HttpException('File in body is empty', HttpStatus.UNPROCESSABLE_ENTITY) } try { const guardians = new Guardians(); const { schemas } = await SchemaImportExport.parseZipFile(zip); - const schemaToPreview = await guardians.previewSchemasByFile(schemas); - return res.json(schemaToPreview); + return await guardians.previewSchemasByFile(schemas); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -1227,17 +1136,20 @@ export class SchemaApi { * Import Schema from IPFS */ @Post('/:topicId/import/message') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new schema from IPFS into the local DB.', description: 'Imports new schema from IPFS into the local DB.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', required: true, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) @ApiBody({ description: 'Object that contains version.', @@ -1246,7 +1158,7 @@ export class SchemaApi { examples: { Message: { value: { - messageId: '0000000000.000000000' + messageId: Examples.MESSAGE_ID } } } @@ -1254,47 +1166,36 @@ export class SchemaApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - 'type': 'integer' - }, - description: 'Total items in the collection.' - } - }, + headers: pageHeader, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(MessageSchemaDTO, SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async importFromMessage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const topicId = req.params.topicId; + async importFromMessage( + @AuthUser() user: IAuthUser, + @Param('topicId') topicId: string, + @Body() body: MessageSchemaDTO, + @Response() res: any + ): Promise { const guardians = new Guardians(); - const messageId = req.body.messageId; + const messageId = body?.messageId; if (!messageId) { - throw new HttpException('message ID in body is required', HttpStatus.UNPROCESSABLE_ENTITY) + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); } try { - await guardians.importSchemasByMessages([messageId], req.user.did, topicId); + const owner = new EntityOwner(user); + await guardians.importSchemasByMessages([messageId], owner, topicId); const { items, count } = await guardians.getSchemasByOwner({ - category: SchemaCategory.POLICY, - owner: user.did - }); - SchemaHelper.updatePermission(items, user.did); - return res.status(201).setHeader('X-Total-Count', count).json(SchemaUtils.toOld(items)); + category: SchemaCategory.POLICY + }, owner); + SchemaHelper.updatePermission(items, owner); + return res.status(201).header('X-Total-Count', count).send(SchemaUtils.toOld(items)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -1302,17 +1203,20 @@ export class SchemaApi { * Import Schema from IPFS (Async) */ @Post('/push/:topicId/import/message') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new schema from IPFS into the local DB.', description: 'Imports new schema from IPFS into the local DB.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', required: true, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) @ApiBody({ description: 'Object that contains version.', @@ -1321,7 +1225,7 @@ export class SchemaApi { examples: { Message: { value: { - messageId: '0000000000.000000000' + messageId: Examples.MESSAGE_ID } } } @@ -1330,53 +1234,52 @@ export class SchemaApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(TaskDTO, MessageSchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async importFromMessageAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const topicId = req.params.topicId; - const messageId = req.body.messageId; + async importFromMessageAsync( + @AuthUser() user: IAuthUser, + @Param('topicId') topicId: string, + @Body() body: MessageSchemaDTO, + ): Promise { + const messageId = body?.messageId; if (!messageId) { - throw new HttpException('Schema ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.IMPORT_SCHEMA_MESSAGE, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.importSchemasByMessagesAsync([messageId], user.did, topicId, task); + await guardians.importSchemasByMessagesAsync([messageId], owner, topicId, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } /** * Import Schema from a zip file */ @Post('/:topicId/import/file') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new schema from a zip file into the local DB.', description: 'Imports new schema from a zip file into the local DB.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', required: true, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) @ApiBody({ description: 'A zip file containing schema to be imported.', @@ -1385,48 +1288,36 @@ export class SchemaApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - 'type': 'integer' - }, - description: 'Total items in the collection.' - } - }, + headers: pageHeader, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async importToTopicFromFile(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; + async importToTopicFromFile( + @AuthUser() user: IAuthUser, + @Param('topicId') topicId: string, + @Body() zip: any, + @Response() res: any + ): Promise { const guardians = new Guardians(); - const zip = req.body; - const topicId = req.params.topicId; if (!zip) { throw new HttpException('File in body is empty', HttpStatus.UNPROCESSABLE_ENTITY) } try { + const owner = new EntityOwner(user); const files = await SchemaImportExport.parseZipFile(zip); - await guardians.importSchemasByFile(files, req.user.did, topicId); + await guardians.importSchemasByFile(files, owner, topicId); const { items, count } = await guardians.getSchemasByOwner({ - category: SchemaCategory.POLICY, - owner: user.did - }); - SchemaHelper.updatePermission(items, user.did); - return res.status(201).setHeader('X-Total-Count', count).json(SchemaUtils.toOld(items)); + category: SchemaCategory.POLICY + }, owner); + SchemaHelper.updatePermission(items, owner); + return res.status(201).header('X-Total-Count', count).send(SchemaUtils.toOld(items)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -1434,17 +1325,20 @@ export class SchemaApi { * Import Schema from a zip file (Async) */ @Post('/push/:topicId/import/file') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new schema from a zip file into the local DB.', description: 'Imports new schema from a zip file into the local DB.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', required: true, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) @ApiBody({ description: 'A zip file containing schema to be imported.', @@ -1454,126 +1348,127 @@ export class SchemaApi { description: 'Successful operation.', type: TaskDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async importToTopicFromFileAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const zip = req.body; + async importToTopicFromFileAsync( + @AuthUser() user: IAuthUser, + @Param('topicId') topicId: string, + @Body() zip: any, + ): Promise { if (!zip) { throw new HttpException('File in body is empty', HttpStatus.UNPROCESSABLE_ENTITY) } - const topicId = req.params.topicId; + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.IMPORT_SCHEMA_FILE, user.id); RunFunctionAsync(async () => { const files = await SchemaImportExport.parseZipFile(zip); const guardians = new Guardians(); - await guardians.importSchemasByFileAsync(files, user.did, topicId, task); + await guardians.importSchemasByFileAsync(files, owner, topicId, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } + /** + * Export schemas + */ @Get('/:schemaId/export/message') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Returns Hedera message IDs of the published schemas.', description: 'Returns Hedera message IDs of the published schemas, these messages contain IPFS CIDs of these schema files.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', type: ExportSchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(ExportSchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async exportMessage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async exportMessage( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + ): Promise { try { const guardians = new Guardians(); - const id = req.params.schemaId; - const schemas = await guardians.exportSchemas([id]); + const owner = new EntityOwner(user); + const schemas = await guardians.exportSchemas([schemaId], owner); const scheme = schemas[0]; if (!scheme) { - throw new HttpException(`Cannot export schema ${req.params.schemaId}`, HttpStatus.UNPROCESSABLE_ENTITY); + throw new HttpException(`Cannot export schema ${schemaId}`, HttpStatus.UNPROCESSABLE_ENTITY); } - return res.send({ + return { id: scheme.id, name: scheme.name, description: scheme.description, version: scheme.version, messageId: scheme.messageId, owner: scheme.owner - }); + }; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } + /** + * Export schemas + */ @Get('/:schemaId/export/file') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Returns schema files for the schema.', description: 'Returns schema files for the schema.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation. Response zip file.' }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async exportToFile(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async exportToFile( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + @Response() res: any + ): Promise { try { const guardians = new Guardians(); - const id = req.params.schemaId; - const schemas = await guardians.exportSchemas([id]); + const owner = new EntityOwner(user); + const schemas = await guardians.exportSchemas([schemaId], owner); if (!schemas || !schemas.length) { - throw new HttpException(`Cannot export schema ${req.params.schemaId}`, HttpStatus.UNPROCESSABLE_ENTITY) + throw new HttpException(`Cannot export schema ${schemaId}`, HttpStatus.UNPROCESSABLE_ENTITY) } const ids = schemas.map(s => s.id); const tags = await guardians.exportTags('Schema', ids); @@ -1586,13 +1481,11 @@ export class SchemaApi { level: 3 } }); - res.setHeader('Content-disposition', `attachment; filename=${name}`); - res.setHeader('Content-type', 'application/zip'); - arcStream.pipe(res); - return res; + res.header('Content-disposition', `attachment; filename=${name}`); + res.header('Content-type', 'application/zip'); + return res.send(arcStream); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -1600,12 +1493,15 @@ export class SchemaApi { * Create system schema */ @Post('/system/:username') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SYSTEM_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new system schema.', description: 'Creates a new system schema.' + ONLY_SR }) - @ApiImplicitParam({ + @ApiParam({ name: 'username', type: String, description: 'username', @@ -1616,30 +1512,29 @@ export class SchemaApi { description: 'Successful operation.', type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async postSystemSchema(@Body() body: SystemSchemaDTO, @Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async postSystemSchema( + @AuthUser() user: IAuthUser, + @Param('username') username: string, + @Body() body: SystemSchemaDTO + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const newSchema = body as any; - if (newSchema.entity !== SchemaEntity.STANDARD_REGISTRY - && newSchema.entity !== SchemaEntity.USER) { + if ( + newSchema.entity !== SchemaEntity.STANDARD_REGISTRY && + newSchema.entity !== SchemaEntity.USER + ) { throw new HttpException(`Invalid schema types. Entity must be ${SchemaEntity.STANDARD_REGISTRY} or ${SchemaEntity.USER}`, HttpStatus.UNPROCESSABLE_ENTITY) } const guardians = new Guardians(); - const owner = user.username; SchemaUtils.fromOld(newSchema); delete newSchema.version; @@ -1651,10 +1546,9 @@ export class SchemaApi { SchemaHelper.updateOwner(newSchema, owner); const schema = await guardians.createSystemSchema(newSchema); - return res.status(201).json(SchemaUtils.toOld(schema)); + return SchemaUtils.toOld(schema); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -1662,26 +1556,29 @@ export class SchemaApi { * Get system schemas page */ @Get('/system/:username') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SYSTEM_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return a list of all system schemas.', description: 'Returns all system schemas.' + ONLY_SR }) - @ApiImplicitParam({ + @ApiParam({ name: 'username', type: String, description: 'username', required: true, example: 'username' }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageIndex', type: Number, description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageSize', type: Number, description: 'The numbers of items to return', @@ -1691,45 +1588,30 @@ export class SchemaApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - headers: { - 'x-total-count': { - schema: { - 'type': 'integer' - }, - description: 'Total items in the collection.' - } - }, + headers: pageHeader, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getSystemSchema(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getSystemSchema( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Param('username') username: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { try { - const user = req.user; const guardians = new Guardians(); - const owner = user.username; - let pageIndex: any; - let pageSize: any; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } - const { items, count } = await guardians.getSystemSchemas(owner, pageIndex, pageSize); - items.forEach((s) => { s.readonly = s.readonly || s.owner !== owner }); - return res.setHeader('X-Total-Count', count).json(SchemaUtils.toOld(items)); + const owner = new EntityOwner(user); + const { items, count } = await guardians.getSystemSchemas(pageIndex, pageSize); + items.forEach((s) => { s.readonly = s.readonly || s.owner !== owner.owner }); + return res.header('X-Total-Count', count).send(SchemaUtils.toOld(items)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -1737,54 +1619,51 @@ export class SchemaApi { * Delete system schema */ @Delete('/system/:schemaId') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SYSTEM_SCHEMA_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Deletes the system schema with the provided schema ID.', description: 'Deletes the system schema with the provided schema ID.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.NO_CONTENT) - async deleteSystemSchema(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async deleteSystemSchema( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + ): Promise { try { - const user = req.user; const guardians = new Guardians(); - const schemaId = req.params.schemaId; + const owner = new EntityOwner(user); const schema = await guardians.getSchemaById(schemaId); if (!schema) { throw new HttpException('Schema not found.', HttpStatus.NOT_FOUND) } - const error = SchemaUtils.checkPermission(schema, user, SchemaCategory.SYSTEM); + const error = SchemaUtils.checkPermission(schema, owner, SchemaCategory.SYSTEM); if (error) { throw new HttpException(error, HttpStatus.FORBIDDEN); } if (schema.active) { throw new HttpException('Schema is active.', HttpStatus.UNPROCESSABLE_ENTITY); } - await guardians.deleteSchema(schemaId, user.username); - return res.status(204).send(); + await guardians.deleteSchema(schemaId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -1792,17 +1671,20 @@ export class SchemaApi { * Update system schema */ @Put('/system/:schemaId') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SYSTEM_SCHEMA_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Updates the system schema.', description: 'Updates the system schema.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.ACCOUNT_ID }) @ApiBody({ description: 'Object that contains a valid schema.', @@ -1814,28 +1696,25 @@ export class SchemaApi { isArray: true, type: SchemaDTO }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setSystemSchema(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async setSystemSchema( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + @Body() newSchema: SchemaDTO, + ): Promise { try { - const user = req.user; - const newSchema = req.body; const guardians = new Guardians(); + const owner = new EntityOwner(user); const schema = await guardians.getSchemaById(newSchema.id); if (!schema) { throw new HttpException('Schema not found.', HttpStatus.NOT_FOUND); } - const error = SchemaUtils.checkPermission(schema, user, SchemaCategory.SYSTEM); + const error = SchemaUtils.checkPermission(schema, owner, SchemaCategory.SYSTEM); if (error) { throw new HttpException(error, HttpStatus.FORBIDDEN); } @@ -1843,11 +1722,13 @@ export class SchemaApi { throw new HttpException('Schema is active.', HttpStatus.UNPROCESSABLE_ENTITY); } SchemaUtils.fromOld(newSchema); - const schemas = await updateSchema(newSchema, user.username); - return res.json(SchemaUtils.toOld(schemas)); + SchemaHelper.checkSchemaKey(newSchema); + SchemaHelper.updateOwner(newSchema, owner); + const schemas = await guardians.updateSchema(newSchema, owner); + SchemaHelper.updatePermission(schemas, owner); + return SchemaUtils.toOld(schemas); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -1855,37 +1736,35 @@ export class SchemaApi { * Makes the selected scheme active. */ @Put('/system/:schemaId/active') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.SCHEMAS_SYSTEM_SCHEMA_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Makes the selected scheme active. Other schemes of the same type become inactive', description: 'Makes the selected scheme active. Other schemes of the same type become inactive' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async activeSystemSchema(@Req() req: any): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async activeSystemSchema( + @Param('schemaId') schemaId: string + ): Promise { try { const guardians = new Guardians(); - const schemaId = req.params.schemaId; const schema = await guardians.getSchemaById(schemaId); if (!schema) { throw new HttpException('Schema not found.', HttpStatus.NOT_FOUND); @@ -1899,8 +1778,7 @@ export class SchemaApi { await guardians.activeSchema(schemaId); return null; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } @@ -1908,12 +1786,12 @@ export class SchemaApi { * Finds the schema by entity. */ @Get('/system/entity/:schemaEntity') - @ApiSecurity('bearerAuth') + @Auth() @ApiOperation({ summary: 'Finds the schema using the schema type.', description: 'Finds the schema using the schema type.', }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaEntity', enum: ['STANDARD_REGISTRY', 'USER', 'POLICY', 'MINT_TOKEN', 'WIPE_TOKEN', 'MINT_NFTOKEN'], description: 'Entity name', @@ -1922,28 +1800,24 @@ export class SchemaApi { }) @ApiOkResponse({ description: 'Successful operation.', - type: TaskDTO - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: SchemaDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getSchemaEntity(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER, UserRole.AUDITOR)(req.user) + async getSchemaEntity( + @Param('schemaEntity') schemaEntity: string + ): Promise { try { const guardians = new Guardians(); - const schema = await guardians.getSchemaByEntity(req.params.schemaEntity); + const schema = await guardians.getSchemaByEntity(schemaEntity); if (!schema) { - return res.send(null); + return null; } - return res.send({ + return { uuid: schema.uuid, iri: schema.iri, name: schema.name, @@ -1952,10 +1826,9 @@ export class SchemaApi { documentURL: schema.documentURL, context: schema.context, contextURL: schema.contextURL, - }); + }; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } @@ -1964,19 +1837,19 @@ export class SchemaApi { */ @Get('/:schemaId/export/xlsx') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Return schemas in a xlsx file format for the specified policy.', description: 'Returns a xlsx file containing schemas.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'schemaId', type: String, description: 'Schema ID', required: true, - example: '000000000000000000000001' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', @@ -1985,16 +1858,11 @@ export class SchemaApi { format: 'binary' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getPolicyExportXlsx( @AuthUser() user: IAuthUser, @@ -2003,14 +1871,14 @@ export class SchemaApi { ): Promise { try { const guardians = new Guardians(); - const file: any = await guardians.exportSchemasXlsx(user, [schemaId]); + const owner = new EntityOwner(user); + const file: any = await guardians.exportSchemasXlsx(owner, [schemaId]); const schema: any = await guardians.getSchemaById(schemaId); - res.setHeader('Content-disposition', `attachment; filename=${schema.name}`); - res.setHeader('Content-type', 'application/zip'); + res.header('Content-disposition', `attachment; filename=${schema.name}`); + res.header('Content-type', 'application/zip'); return res.send(file); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } @@ -2019,19 +1887,19 @@ export class SchemaApi { */ @Post('/:topicId/import/xlsx') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Imports new schema from a xlsx file into the local DB.', description: 'Imports new schema from a xlsx file into the local DB.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', required: true, - example: '0.0.1' + example: Examples.ACCOUNT_ID }) @ApiBody({ description: 'A xlsx file containing schema config.', @@ -2044,16 +1912,11 @@ export class SchemaApi { 'type': 'object' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) async importPolicyFromXlsx( @AuthUser() user: IAuthUser, @@ -2066,16 +1929,15 @@ export class SchemaApi { } try { const guardians = new Guardians(); - await guardians.importSchemasByXlsx(user, topicId, file); + const owner = new EntityOwner(user); + await guardians.importSchemasByXlsx(owner, topicId, file); const { items, count } = await guardians.getSchemasByOwner({ - category: SchemaCategory.POLICY, - owner: user.did - }); - SchemaHelper.updatePermission(items, user.did); - return res.status(201).setHeader('X-Total-Count', count).json(SchemaUtils.toOld(items)); + category: SchemaCategory.POLICY + }, owner); + SchemaHelper.updatePermission(items, owner); + return res.status(201).header('X-Total-Count', count).send(SchemaUtils.toOld(items)); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -2084,14 +1946,14 @@ export class SchemaApi { */ @Post('/push/:topicId/import/xlsx') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Imports new schema from a xlsx file into the local DB.', description: 'Imports new schema from a xlsx file into the local DB.' + ONLY_SR, }) - @ApiImplicitParam({ + @ApiParam({ name: 'topicId', type: String, description: 'Topic Id', @@ -2109,16 +1971,11 @@ export class SchemaApi { 'type': 'object' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) async importPolicyFromXlsxAsync( @AuthUser() user: IAuthUser, @@ -2133,7 +1990,8 @@ export class SchemaApi { const task = taskManager.start(TaskAction.IMPORT_SCHEMA_FILE, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.importSchemasByXlsxAsync(user, topicId, file, task); + const owner = new EntityOwner(user); + await guardians.importSchemasByXlsxAsync(owner, topicId, file, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: 'Unknown error: ' + error.message }); @@ -2146,9 +2004,9 @@ export class SchemaApi { */ @Post('/import/xlsx/preview') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Previews the schema from a xlsx file.', description: 'Previews the schema from a xlsx file.' + ONLY_SR, @@ -2164,16 +2022,11 @@ export class SchemaApi { 'type': 'object' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async importPolicyFromXlsxPreview( @AuthUser() user: IAuthUser, @@ -2184,10 +2037,10 @@ export class SchemaApi { } try { const guardians = new Guardians(); - return await guardians.previewSchemasByFileXlsx(user, file); + const owner = new EntityOwner(user); + return await guardians.previewSchemasByFileXlsx(owner, file); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -2196,9 +2049,9 @@ export class SchemaApi { */ @Get('/export/template') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Returns a list of schemas.', description: 'Returns a list of schemas.' + ONLY_SR, @@ -2210,18 +2063,13 @@ export class SchemaApi { format: 'binary' }, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(InternalServerErrorDTO) @UseCache({ isExpress: true }) + @HttpCode(HttpStatus.OK) async exportTemplate( @AuthUser() user: IAuthUser, @Response() res: any @@ -2231,13 +2079,12 @@ export class SchemaApi { const guardians = new Guardians(); const file = await guardians.getFileTemplate(filename); const fileBuffer = Buffer.from(file, 'base64'); - res.setHeader('Content-disposition', `attachment; filename=` + filename); - res.setHeader('Content-type', 'application/zip'); + res.header('Content-disposition', `attachment; filename=` + filename); + res.header('Content-type', 'application/zip'); res.locals.data = fileBuffer return res.send(fileBuffer); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/settings.ts b/api-gateway/src/api/service/settings.ts index 6da3bc5546..70695fcf9d 100644 --- a/api-gateway/src/api/service/settings.ts +++ b/api-gateway/src/api/service/settings.ts @@ -1,98 +1,135 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { AboutInterface, CommonSettings, UserRole } from '@guardian/interfaces'; -import { Logger } from '@guardian/common'; -import { Body, Controller, Get, HttpCode, HttpException, HttpStatus, Post, Req, Response } from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, getSchemaPath } from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; -import { SettingsDTO } from '../../middlewares/validation/schemas/settings.js'; +import { AboutInterface, CommonSettings, Permissions } from '@guardian/interfaces'; +import { Body, Controller, Get, HttpCode, HttpStatus, Post } from '@nestjs/common'; +import { ApiBody, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { SettingsDTO, InternalServerErrorDTO } from '#middlewares'; +import { Auth } from '#auth'; +import { Guardians, InternalException } from '#helpers'; import process from 'process'; @Controller('settings') @ApiTags('settings') export class SettingsApi { + /** + * Set settings + */ + @Post('/') + @Auth( + Permissions.SETTINGS_SETTINGS_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Set settings.', description: 'Set settings. For users with the Standard Registry role only.', }) + @ApiBody({ + description: 'Settings.', + required: true, + type: SettingsDTO, + }) @ApiOkResponse({ description: 'Successful operation.', }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO }) - @Post('/') + @ApiExtraModels(SettingsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async updateSettings(@Body() body: SettingsDTO, @Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async updateSettings( + @Body() body: SettingsDTO + ): Promise { try { const settings = body as CommonSettings; const guardians = new Guardians(); - await Promise.all([ - guardians.updateSettings(settings) - ]); - return res.status(201).json(null); + await Promise.all([guardians.updateSettings(settings)]); + return null; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get settings + */ + @Get('/') + @Auth( + Permissions.SETTINGS_SETTINGS_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Returns current settings.', description: 'Returns current settings. For users with the Standard Registry role only.', }) @ApiOkResponse({ description: 'Successful operation.', + type: SettingsDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO }) - @Get('/') + @ApiExtraModels(SettingsDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getSettings(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getSettings(): Promise { try { const guardians = new Guardians(); - const [guardiansSettings] = await Promise.all([ - guardians.getSettings() - ]); - res.json({ - ...guardiansSettings - }); + const [guardiansSettings] = await Promise.all([guardians.getSettings()]); + return { ...guardiansSettings } as any; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Get settings + */ @Get('/environment') + @Auth() + @ApiOperation({ + summary: 'Returns current environment name.', + description: 'Returns current environment name.', + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: String + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getEnvironment(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER, UserRole.AUDITOR)(req.user); + async getEnvironment(): Promise { try { const guardians = new Guardians(); - const environment = await guardians.getEnvironment(); - return res.send(environment); + return await guardians.getEnvironment(); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Get about + */ @Get('/about') + @Auth( + Permissions.SETTINGS_SETTINGS_READ, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Returns package version.', + description: 'Returns package version. For users with the Standard Registry role only.', + }) + @ApiOkResponse({ + description: 'Successful operation.', + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getAbout(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - - return { - version: process.env.npm_package_version - } + async getAbout(): Promise { + return { version: process.env.npm_package_version }; } } diff --git a/api-gateway/src/api/service/suggestions.ts b/api-gateway/src/api/service/suggestions.ts index eec6c3b9bf..4079169a6a 100644 --- a/api-gateway/src/api/service/suggestions.ts +++ b/api-gateway/src/api/service/suggestions.ts @@ -1,137 +1,107 @@ -import { UserRole } from '@guardian/interfaces'; -import { Body, Controller, Get, HttpCode, HttpStatus, Post, Req, UseGuards, } from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { Guardians } from '../../helpers/guardians.js'; -import { ApiBearerAuth, ApiCreatedResponse, ApiExtraModels, ApiForbiddenResponse, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiSecurity, ApiTags, ApiUnauthorizedResponse, getSchemaPath, } from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; -import { SuggestionsConfigDTO, SuggestionsConfigItemDTO, SuggestionsInputDTO, SuggestionsOutputDTO, } from '../../middlewares/validation/schemas/suggestions.js'; -import { AuthGuard } from '../../auth/auth-guard.js'; +import { Permissions } from '@guardian/interfaces'; +import { Body, Controller, Get, HttpCode, HttpStatus, Post } from '@nestjs/common'; +import { ApiBody, ApiCreatedResponse, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; +import { SuggestionsConfigDTO, SuggestionsConfigItemDTO, SuggestionsInputDTO, SuggestionsOutputDTO, InternalServerErrorDTO } from '#middlewares'; +import { IAuthUser } from '@guardian/common'; +import { AuthUser, Auth } from '#auth'; +import { Guardians, ONLY_SR } from '#helpers'; @Controller('suggestions') @ApiTags('suggestions') export class SuggestionsApi { + /** + * Get next and nested suggested block types + */ + @Post('/') + @Auth( + Permissions.SUGGESTIONS_SUGGESTIONS_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Get next and nested suggested block types', - description: - 'Get next and nested suggested block types. Only users with the Standard Registry role are allowed to make the request.', - }) - @ApiSecurity('bearerAuth') - @ApiExtraModels( - SuggestionsInputDTO, - SuggestionsOutputDTO, - InternalServerErrorDTO - ) - @ApiOkResponse({ - description: - 'Successful operation. Suggested next and nested block types respectively.', - schema: { - $ref: getSchemaPath(SuggestionsOutputDTO), - }, + description: 'Get next and nested suggested block types.' + ONLY_SR, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'Data.', + type: SuggestionsInputDTO, }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Successful operation. Suggested next and nested block types respectively.', + type: SuggestionsOutputDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO, }) - @ApiBearerAuth() - @UseGuards(AuthGuard) - @Post('/') + @ApiExtraModels(SuggestionsInputDTO, SuggestionsOutputDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async policySuggestions( - @Req() req, + @AuthUser() user: IAuthUser, @Body() body: SuggestionsInputDTO ): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; const guardians = new Guardians(); return await guardians.policySuggestions(body, user); } + /** + * Set suggestions config + */ + @Post('/config') + @Auth( + Permissions.SUGGESTIONS_SUGGESTIONS_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Set suggestions config', - description: - 'Set suggestions config. Only users with the Standard Registry role are allowed to make the request.', + description: 'Set suggestions config.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') - @ApiExtraModels( - SuggestionsConfigItemDTO, - SuggestionsConfigDTO, - InternalServerErrorDTO - ) - @ApiCreatedResponse({ - description: - 'Successful operation. Response setted suggestions config.', - schema: { - $ref: getSchemaPath(SuggestionsConfigDTO), - }, + @ApiBody({ + description: 'Suggestions config.', + type: SuggestionsConfigDTO, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiCreatedResponse({ + description: 'Successful operation. Response setted suggestions config.', + type: SuggestionsConfigDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO, }) - @ApiBearerAuth() - @UseGuards(AuthGuard) - @Post('/config') + @ApiExtraModels(SuggestionsConfigItemDTO, SuggestionsConfigDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) async setPolicySuggestionsConfig( - @Req() req, + @AuthUser() user: IAuthUser, @Body() body: SuggestionsConfigDTO ): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); const guardians = new Guardians(); - const user = req.user; - return { - items: await guardians.setPolicySuggestionsConfig(body.items, user), - }; + return { items: await guardians.setPolicySuggestionsConfig(body.items, user) }; } + /** + * Get suggestions config + */ + @Get('/config') + @Auth( + Permissions.SUGGESTIONS_SUGGESTIONS_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Get suggestions config', - description: - 'Get suggestions config. Only users with the Standard Registry role are allowed to make the request.', + description: 'Get suggestions config.' + ONLY_SR, }) - @ApiSecurity('bearerAuth') - @ApiExtraModels( - SuggestionsConfigItemDTO, - SuggestionsConfigDTO, - InternalServerErrorDTO - ) @ApiOkResponse({ description: 'Successful operation. Response suggestions config.', - schema: { - $ref: getSchemaPath(SuggestionsConfigDTO), - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + type: SuggestionsConfigDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO, }) - @ApiBearerAuth() - @UseGuards(AuthGuard) - @Get('/config') + @ApiExtraModels(SuggestionsConfigItemDTO, SuggestionsConfigDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) async getPolicySuggestionsConfig( - @Req() req + @AuthUser() user: IAuthUser ): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; const guardians = new Guardians(); return { items: await guardians.getPolicySuggestionsConfig(user) }; } diff --git a/api-gateway/src/api/service/tags.ts b/api-gateway/src/api/service/tags.ts index 8c33665032..ad1f974037 100644 --- a/api-gateway/src/api/service/tags.ts +++ b/api-gateway/src/api/service/tags.ts @@ -1,40 +1,106 @@ -import { Logger } from '@guardian/common'; -import { Guardians } from '../../helpers/guardians.js'; -import { SchemaCategory, SchemaHelper, UserRole } from '@guardian/interfaces'; -import { SchemaUtils } from '../../helpers/schema-utils.js'; -import { Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Post, Put, Req, Response } from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { ApiTags } from '@nestjs/swagger'; +import { IAuthUser } from '@guardian/common'; +import { Permissions, SchemaCategory, SchemaHelper } from '@guardian/interfaces'; +import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Query, Response } from '@nestjs/common'; +import { ApiTags, ApiInternalServerErrorResponse, ApiExtraModels, ApiOperation, ApiBody, ApiOkResponse, ApiParam, ApiCreatedResponse, ApiQuery } from '@nestjs/swagger'; +import { Examples, InternalServerErrorDTO, SchemaDTO, TagDTO, TagFilterDTO, TagMapDTO, pageHeader } from '#middlewares'; +import { AuthUser, Auth } from '#auth'; +import { ONLY_SR, SchemaUtils, Guardians, InternalException, EntityOwner } from '#helpers'; @Controller('tags') @ApiTags('tags') export class TagsApi { + /** + * Create tag + */ @Post('/') + @Auth( + Permissions.TAGS_TAG_CREATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Creates new tag.', + description: 'Creates new tag.', + }) + @ApiBody({ + description: 'Object that contains tag information.', + required: true, + type: TagDTO, + }) + @ApiOkResponse({ + description: 'Created tag.', + type: TagDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(TagDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async setTags(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); + async setTags( + @AuthUser() user: IAuthUser, + @Body() body: TagDTO + ): Promise { try { - if (!req.headers.authorization || !req.user || !req.user.did) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED) - } + const owner = new EntityOwner(user); const guardian = new Guardians(); - const item = await guardian.createTag(req.body, req.user.did); - return res.status(201).json(item); + return await guardian.createTag(body, owner); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get tags + */ @Post('/search') + @Auth( + Permissions.TAGS_TAG_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Search tags.', + description: 'Search tags.', + }) + @ApiBody({ + description: 'Object that contains filters', + required: true, + type: TagFilterDTO, + examples: { + Single: { + value: { + entity: 'PolicyDocument', + target: Examples.MESSAGE_ID + } + }, + Multiple: { + value: { + entity: 'PolicyDocument', + targets: [ + Examples.MESSAGE_ID, + Examples.MESSAGE_ID + ] + } + } + } + }) + @ApiOkResponse({ + description: 'Created tag.', + type: TagMapDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(TagFilterDTO, TagMapDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async searchTags(@Req() req, @Response() res): Promise { + async searchTags( + @Body() body: TagFilterDTO + ): Promise<{ [localTarget: string]: TagMapDTO }> { try { - const guardians = new Guardians(); - if (!req.headers.authorization || !req.user || !req.user.did) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED) - } - const { entity, target, targets } = req.body; + const { entity, target, targets } = body; + let _targets: string[]; if (!entity) { throw new HttpException('Invalid entity', HttpStatus.UNPROCESSABLE_ENTITY) @@ -55,6 +121,7 @@ export class TagsApi { throw new HttpException('Invalid target', HttpStatus.UNPROCESSABLE_ENTITY) } + const guardians = new Guardians(); const items = await guardians.getTags(entity, _targets); const dates = await guardians.getTagCache(entity, _targets); @@ -76,215 +143,405 @@ export class TagsApi { } } } - return res.json(tagMap); + return tagMap; } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } + /** + * Delete tag + */ @Delete('/:uuid') + @Auth( + Permissions.TAGS_TAG_CREATE, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Delete tag.', + description: 'Delete tag.', + }) + @ApiParam({ + name: 'uuid', + type: String, + description: 'Tag identifier', + required: true, + example: Examples.UUID, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: Boolean + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async deleteTag(@Req() req, @Response() res): Promise { - if (!req.user) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED) - } + async deleteTag( + @AuthUser() user: IAuthUser, + @Param('uuid') uuid: string, + ): Promise { try { - const guardian = new Guardians(); - if (!req.params.uuid) { + if (!uuid) { throw new HttpException('Invalid uuid', HttpStatus.UNPROCESSABLE_ENTITY) } - const result = await guardian.deleteTag(req.params.uuid, req.user.did); - return res.json(result); + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.deleteTag(uuid, owner); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - // return next(error); + await InternalException(error); } } + /** + * Synchronization + */ @Post('/synchronization') - @HttpCode(HttpStatus.OK) - async synchronizationTags(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); - if (!req.headers.authorization || !req.user || !req.user.did) { - throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED) + @Auth( + Permissions.TAGS_TAG_READ, + // UserRole.STANDARD_REGISTRY, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Synchronization of tags with an external network.', + description: 'Synchronization of tags with an external network.', + }) + @ApiBody({ + description: 'Object that contains filters', + required: true, + type: TagFilterDTO, + examples: { + Single: { + value: { + entity: 'PolicyDocument', + target: Examples.MESSAGE_ID + } + } } + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TagMapDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(TagMapDTO, TagFilterDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async synchronizationTags( + @Body() body: TagFilterDTO + ): Promise { try { - const guardians = new Guardians(); - const { entity, target } = req.body; - + const { entity, target } = body; if (!entity) { throw new HttpException('Invalid entity', HttpStatus.UNPROCESSABLE_ENTITY) } - if (typeof target !== 'string') { throw new HttpException('Invalid target', HttpStatus.UNPROCESSABLE_ENTITY) } + const guardians = new Guardians(); const tags = await guardians.synchronizationTags(entity, target); - - const result = { + return { entity, target, tags, refreshDate: (new Date()).toISOString(), } - return res.json(result); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } /** - * @param req - * @param res + * Get list of all schemas */ @Get('/schemas') - @HttpCode(HttpStatus.OK) + @Auth( + Permissions.SCHEMAS_SCHEMA_READ, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Return a list of all tag schemas.', + description: 'Returns all tag schemas.' + ONLY_SR, + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + headers: pageHeader, + type: SchemaDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) // @UseCache({ isExpress: true }) - async getSchemas(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @HttpCode(HttpStatus.OK) + async getSchemas( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { try { - const user = req.user; const guardians = new Guardians(); - const owner = user.did; - let pageIndex: any; - let pageSize: any; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } + const owner = new EntityOwner(user); const { items, count } = await guardians.getTagSchemas(owner, pageIndex, pageSize); - items.forEach((s) => { s.readonly = s.readonly || s.owner !== owner }); - res.locals.data = SchemaUtils.toOld(items) + items.forEach((s) => { s.readonly = s.readonly || s.owner !== owner.creator }); + // res.locals.data = SchemaUtils.toOld(items) return res - .setHeader('X-Total-Count', count) - .json(SchemaUtils.toOld(items)); + .header('X-Total-Count', count) + .send(SchemaUtils.toOld(items)); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Create schema + */ @Post('/schemas') + @Auth( + Permissions.SCHEMAS_SCHEMA_CREATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Creates a new tag schema.', + description: 'Creates a new tag schema.' + ONLY_SR, + }) + @ApiBody({ + description: 'Schema config.', + type: SchemaDTO, + }) + @ApiCreatedResponse({ + description: 'Created schema.', + type: SchemaDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async postSchemas(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async postSchemas( + @AuthUser() user: IAuthUser, + @Body() newSchema: SchemaDTO + ): Promise { try { - const user = req.user; - const newSchema = req.body; - if (!newSchema) { throw new HttpException('Schema does not exist.', HttpStatus.UNPROCESSABLE_ENTITY) } const guardians = new Guardians(); - const owner = user.did; - + const owner = new EntityOwner(user); + newSchema.category = SchemaCategory.TAG; SchemaUtils.fromOld(newSchema); - delete newSchema.version; - delete newSchema.id; - delete newSchema._id; - delete newSchema.status; - delete newSchema.topicId; - + SchemaUtils.clearIds(newSchema); SchemaHelper.updateOwner(newSchema, owner); - const schema = await guardians.createTagSchema(newSchema); - return res.status(201).json(SchemaUtils.toOld(schema)); + const schemas = await guardians.createTagSchema(newSchema, owner); + return SchemaUtils.toOld(schemas); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Delete schema + */ @Delete('/schemas/:schemaId') + @Auth( + Permissions.SCHEMAS_SCHEMA_DELETE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Deletes the schema.', + description: 'Deletes the schema with the provided schema ID.' + ONLY_SR + }) + @ApiParam({ + name: 'schemaId', + type: 'string', + required: true, + description: 'Schema Identifier', + example: Examples.DB_ID, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: Boolean, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async deleteSchema(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async deleteSchema( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + ): Promise { try { - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - const schemaId = req.params.schemaId; const schema = await guardians.getSchemaById(schemaId); - const error = SchemaUtils.checkPermission(schema, user, SchemaCategory.TAG); + const error = SchemaUtils.checkPermission(schema, owner, SchemaCategory.TAG); if (error) { throw new HttpException(error, HttpStatus.FORBIDDEN) } - await guardians.deleteSchema(schemaId, user?.did); - return res.json(true); + await guardians.deleteSchema(schemaId, owner); + return true; } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Update schema + */ @Put('/schemas/:schemaId') + @Auth( + Permissions.SCHEMAS_SCHEMA_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Updates schema configuration.', + description: 'Updates schema configuration for the specified schema ID.' + ONLY_SR, + }) + @ApiParam({ + name: 'schemaId', + type: 'string', + required: true, + description: 'Schema Identifier', + example: Examples.DB_ID, + }) + @ApiBody({ + description: 'Schema config.', + type: SchemaDTO, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: SchemaDTO, + isArray: true + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setTag(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async updateSchema( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + @Body() newSchema: SchemaDTO + ): Promise { try { - const user = req.user; - const newSchema = req.body; - const owner = user.did; + const owner = new EntityOwner(user); const guardians = new Guardians(); const schema = await guardians.getSchemaById(newSchema.id); - const error = SchemaUtils.checkPermission(schema, user, SchemaCategory.TAG); + const error = SchemaUtils.checkPermission(schema, owner, SchemaCategory.TAG); if (error) { throw new HttpException(error, HttpStatus.FORBIDDEN) } SchemaUtils.fromOld(newSchema); SchemaHelper.checkSchemaKey(newSchema); SchemaHelper.updateOwner(newSchema, owner); - await guardians.updateSchema(newSchema); - return res.json(newSchema); + return await guardians.updateSchema(newSchema, owner); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Publish schema + */ @Put('/schemas/:schemaId/publish') + @Auth( + Permissions.SCHEMAS_SCHEMA_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Publishes the schema.', + description: 'Publishes the schema with the provided (internal) schema ID onto IPFS, sends a message featuring IPFS CID into the corresponding Hedera topic.' + ONLY_SR, + }) + @ApiParam({ + name: 'schemaId', + type: 'string', + required: true, + description: 'Schema Identifier', + example: Examples.DB_ID, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: SchemaDTO, + isArray: true + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async publishTag(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const guardians = new Guardians(); - const schemaId = req.params.schemaId; - let schema; + async publishTag( + @AuthUser() user: IAuthUser, + @Param('schemaId') schemaId: string, + ): Promise { try { - schema = await guardians.getSchemaById(schemaId); - } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); - } - const version = '1.0.0'; - const error = SchemaUtils.checkPermission(schema, user, SchemaCategory.TAG); - if (error) { - throw new HttpException(error, HttpStatus.FORBIDDEN) - } - try { - const result = await guardians.publishTagSchema(schemaId, version, user.did); - return res.json(result); + const owner = new EntityOwner(user); + const guardians = new Guardians(); + const schema = await guardians.getSchemaById(schemaId); + const error = SchemaUtils.checkPermission(schema, owner, SchemaCategory.TAG); + if (error) { + throw new HttpException(error, HttpStatus.FORBIDDEN) + } + const version = '1.0.0'; + return await guardians.publishTagSchema(schemaId, version, owner); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Get published schema + */ @Get('/schemas/published') - @HttpCode(HttpStatus.OK) - async getPublished(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); + @Auth() + @ApiOperation({ + summary: 'Return a list of all published schemas.', + description: 'Return a list of all published schemas.' + ONLY_SR, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: SchemaDTO, + isArray: true + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(SchemaDTO, InternalServerErrorDTO) + async getPublished(): Promise { try { const guardians = new Guardians(); - const schemas = await guardians.getPublishedTagSchemas(); - return res.send(schemas); + return await guardians.getPublishedTagSchemas(); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/task.ts b/api-gateway/src/api/service/task.ts index 72ffdc57d8..c8a71f98e4 100644 --- a/api-gateway/src/api/service/task.ts +++ b/api-gateway/src/api/service/task.ts @@ -1,22 +1,48 @@ -import { Logger } from '@guardian/common'; -import { TaskManager } from '../../helpers/task-manager.js'; -import { Controller, Get, HttpCode, HttpStatus, Req, Response } from '@nestjs/common'; -import { ApiTags } from '@nestjs/swagger'; +import { IAuthUser } from '@guardian/common'; +import { Controller, Get, HttpCode, HttpStatus, Param } from '@nestjs/common'; +import { ApiTags, ApiParam, ApiOperation, ApiExtraModels, ApiOkResponse, ApiInternalServerErrorResponse } from '@nestjs/swagger'; +import { AuthUser, Auth } from '#auth'; +import { Examples, InternalServerErrorDTO, TaskStatusDTO } from '#middlewares'; +import { InternalException, TaskManager } from '#helpers'; @Controller('tasks') @ApiTags('tasks') export class TaskApi { + /** + * Get status + */ @Get('/:taskId') + @Auth() + @ApiOperation({ + summary: 'Returns task statuses by Id.', + description: 'Returns task statuses by Id.', + }) + @ApiParam({ + name: 'taskId', + type: String, + description: 'Task Id', + required: true, + example: Examples.UUID, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskStatusDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(TaskStatusDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getTask(@Req() req, @Response() res): Promise { - const taskManager = new TaskManager(); + async getTask( + @AuthUser() user: IAuthUser, + @Param('taskId') taskId: string, + ): Promise { try { - const taskId = req.params.taskId; - const taskState = taskManager.getState(req.user.id, taskId); - return res.json(taskState); + const taskManager = new TaskManager(); + return taskManager.getState(user.id, taskId); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/themes.ts b/api-gateway/src/api/service/themes.ts index e48051ea78..ad1618fc22 100644 --- a/api-gateway/src/api/service/themes.ts +++ b/api-gateway/src/api/service/themes.ts @@ -1,104 +1,274 @@ -import { Logger } from '@guardian/common'; -import { Guardians } from '../../helpers/guardians.js'; -import { Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Post, Put, Req, Response } from '@nestjs/common'; -import { ApiTags } from '@nestjs/swagger'; +import { IAuthUser } from '@guardian/common'; +import { EntityOwner, Guardians, InternalException, ONLY_SR } from '#helpers'; +import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Response } from '@nestjs/common'; +import { ApiTags, ApiOperation, ApiBody, ApiOkResponse, ApiInternalServerErrorResponse, ApiExtraModels, ApiParam } from '@nestjs/swagger'; +import { Permissions } from '@guardian/interfaces'; +import { AuthUser, Auth } from '#auth'; +import { Examples, InternalServerErrorDTO, ThemeDTO } from '#middlewares'; @Controller('themes') @ApiTags('themes') export class ThemesApi { + /** + * Create theme + */ @Post('/') + @Auth( + Permissions.SETTINGS_THEME_CREATE, + // UserRole.STANDARD_REGISTRY + ) + @ApiOperation({ + summary: 'Creates a new theme.', + description: 'Creates a new theme.' + ONLY_SR, + }) + @ApiBody({ + description: 'Object that contains a theme.', + required: true, + type: ThemeDTO + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: ThemeDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(ThemeDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async setThemes(@Req() req, @Response() res): Promise { + async setThemes( + @AuthUser() user: IAuthUser, + @Body() theme: ThemeDTO + ): Promise { try { const guardians = new Guardians(); - const item = await guardians.createTheme(req.body, req.user.did); - return res.status(201).json(item); + const owner = new EntityOwner(user); + return await guardians.createTheme(theme, owner); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Update theme + */ @Put('/:themeId') + @Auth( + Permissions.SETTINGS_THEME_UPDATE, + // UserRole.STANDARD_REGISTRY + ) + @ApiOperation({ + summary: 'Updates theme configuration.', + description: 'Updates theme configuration for the specified theme ID.' + ONLY_SR, + }) + @ApiParam({ + name: 'themeId', + type: 'string', + required: true, + description: 'Theme Identifier', + example: Examples.DB_ID, + }) + @ApiBody({ + description: 'Object that contains a theme.', + required: true, + type: ThemeDTO + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: ThemeDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(ThemeDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async updateTheme(@Req() req, @Response() res): Promise { + async updateTheme( + @AuthUser() user: IAuthUser, + @Param('themeId') themeId: string, + @Body() theme: ThemeDTO + ): Promise { try { - const user = req.user; - const newTheme = req.body; - const guardians = new Guardians(); - if (!req.params.themeId) { - throw new HttpException('Invalid theme id', HttpStatus.UNPROCESSABLE_ENTITY) + if (!themeId) { + throw new HttpException('Invalid theme id', HttpStatus.UNPROCESSABLE_ENTITY); } - const oldTheme = await guardians.getThemeById(req.params.themeId); + const owner = new EntityOwner(user); + const guardians = new Guardians(); + const oldTheme = await guardians.getThemeById(themeId, owner); if (!oldTheme) { - throw new HttpException('Theme not found.', HttpStatus.NOT_FOUND) + throw new HttpException('Theme not found.', HttpStatus.NOT_FOUND); } - const theme = await guardians.updateTheme(req.params.themeId, newTheme, user.did); - return res.json(theme); + return await guardians.updateTheme(themeId, theme, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Delete theme + */ @Delete('/:themeId') + @Auth( + Permissions.SETTINGS_THEME_UPDATE, + // UserRole.STANDARD_REGISTRY + ) + @ApiOperation({ + summary: 'Deletes the theme.', + description: 'Deletes the theme with the provided theme ID.' + ONLY_SR, + }) + @ApiParam({ + name: 'themeId', + type: 'string', + required: true, + description: 'Theme Identifier', + example: Examples.DB_ID, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: Boolean + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async deleteTheme(@Req() req, @Response() res): Promise { + async deleteTheme( + @AuthUser() user: IAuthUser, + @Param('themeId') themeId: string + ): Promise { try { - const guardians = new Guardians(); - if (!req.params.themeId) { + if (!themeId) { throw new HttpException('Invalid theme id', HttpStatus.UNPROCESSABLE_ENTITY) } - const result = await guardians.deleteTheme(req.params.themeId, req.user.did); - return res.json(result); + const owner = new EntityOwner(user); + const guardians = new Guardians(); + return await guardians.deleteTheme(themeId, owner); } catch (error) { - await (new Logger()).error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Get all themes + */ @Get('/') + @Auth( + Permissions.SETTINGS_THEME_READ, + // UserRole.STANDARD_REGISTRY + ) + @ApiOperation({ + summary: 'Returns a list of all themes.', + description: 'Returns a list of all themes.' + ONLY_SR, + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: ThemeDTO, + isArray: true + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(ThemeDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getThemes(@Req() req, @Response() res): Promise { + async getThemes( + @AuthUser() user: IAuthUser + ): Promise { try { - const user = req.user; const guardians = new Guardians(); if (user.did) { - const themes = await guardians.getThemes(user.did); - return res.send(themes); + const owner = new EntityOwner(user); + return await guardians.getThemes(owner); + } else { + return []; } - return res.send([]); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } + /** + * Import theme + */ @Post('/import/file') + @Auth( + Permissions.SETTINGS_THEME_CREATE, + // UserRole.STANDARD_REGISTRY + ) + @ApiOperation({ + summary: 'Imports new theme from a zip file.', + description: 'Imports new theme from the provided zip file into the local DB.' + ONLY_SR, + }) + @ApiBody({ + description: 'A zip file containing theme to be imported.', + required: true + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: ThemeDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(ThemeDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async importTheme(@Req() req, @Response() res): Promise { + async importTheme( + @AuthUser() user: IAuthUser, + @Body() zip: any + ): Promise { const guardian = new Guardians(); try { - const theme = await guardian.importThemeFile(req.body, req.user.did); - return res.status(201).send(theme); + const owner = new EntityOwner(user); + return await guardian.importThemeFile(zip, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Export theme + */ @Get('/:themeId/export/file') + @Auth( + Permissions.SETTINGS_THEME_CREATE, + // UserRole.STANDARD_REGISTRY + ) + @ApiOperation({ + summary: 'Returns a zip file containing the theme.', + description: 'Returns a zip file containing the theme.' + ONLY_SR, + }) + @ApiParam({ + name: 'themeId', + type: 'string', + required: true, + description: 'Theme Identifier', + example: Examples.DB_ID, + }) + @ApiOkResponse({ + description: 'Successful operation. Response zip file.' + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async exportTheme(@Req() req, @Response() res): Promise { + async exportTheme( + @AuthUser() user: IAuthUser, + @Param('themeId') themeId: string, + @Response() res: any + ): Promise { const guardian = new Guardians(); try { - const file: any = await guardian.exportThemeFile(req.params.themeId, req.user.did); - res.setHeader('Content-disposition', `attachment; filename=theme_${Date.now()}`); - res.setHeader('Content-type', 'application/zip'); + const owner = new EntityOwner(user); + const file: any = await guardian.exportThemeFile(themeId, owner); + res.header('Content-disposition', `attachment; filename=theme_${Date.now()}`); + res.header('Content-type', 'application/zip'); return res.send(file); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/tokens.ts b/api-gateway/src/api/service/tokens.ts index 38d66b39aa..47c8755080 100644 --- a/api-gateway/src/api/service/tokens.ts +++ b/api-gateway/src/api/service/tokens.ts @@ -1,44 +1,10 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { ITokenInfo, TaskAction, UserRole } from '@guardian/interfaces'; -import { Logger, RunFunctionAsync } from '@guardian/common'; -import { PolicyEngine } from '../../helpers/policy-engine.js'; -import { TaskManager } from '../../helpers/task-manager.js'; -import { ServiceError } from '../../helpers/service-requests-base.js'; -import { prepareValidationResponse } from '../../middlewares/validation/index.js'; -import { - Controller, - Delete, - Get, - HttpCode, - HttpException, - HttpStatus, - Post, - Put, - Req, - Response, -} from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { - ApiInternalServerErrorResponse, - ApiOkResponse, - ApiOperation, - ApiUnauthorizedResponse, - ApiExtraModels, - ApiForbiddenResponse, - ApiTags, - ApiBearerAuth, - ApiParam, - ApiBody, - ApiSecurity, - ApiUnprocessableEntityResponse, -} from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/index.js'; -import { Auth } from '../../auth/auth.decorator.js'; - -/** - * Token route - */ -// export const tokenAPI = Router(); +import { Guardians, PolicyEngine, TaskManager, ServiceError, InternalException, ONLY_SR, parseInteger, EntityOwner } from '#helpers'; +import { IOwner, Permissions, TaskAction, UserPermissions } from '@guardian/interfaces'; +import { IAuthUser, Logger, RunFunctionAsync } from '@guardian/common'; +import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Query, Response } from '@nestjs/common'; +import { AuthUser, Auth } from '#auth'; +import { ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiExtraModels, ApiTags, ApiParam, ApiBody, ApiQuery } from '@nestjs/swagger'; +import { Examples, InternalServerErrorDTO, TaskDTO, TokenDTO, TokenInfoDTO, pageHeader } from '#middlewares'; /** * Connect policies to tokens @@ -47,7 +13,7 @@ import { Auth } from '../../auth/auth.decorator.js'; * @param policyId * @param notEmpty */ -function setTokensPolicies(tokens: any[], map: any[], policyId?: any, notEmpty?: boolean): T[] { +function setTokensPolicies(tokens: any[], map: any[], policyId?: string, notEmpty?: boolean): T[] { if (!tokens) { return []; } @@ -78,19 +44,23 @@ function setTokensPolicies(tokens: any[], map: any[], policyId?: any, notEmpt * @param tokens * @param engineService */ -async function setDynamicTokenPolicy(tokens: any[], engineService?: PolicyEngine): Promise { - if (!tokens || !engineService) { +async function setDynamicTokenPolicy( + tokens: any[], + owner: IOwner +): Promise { + if (!tokens || !owner) { return tokens; } for (const token of tokens) { if (!token.policyId) { continue; } + const engineService = new PolicyEngine(); const policy = await engineService.getPolicy({ filters: { id: token.policyId, } - }); + }, owner); token.policies = [`${policy.name} (${policy.version || 'DRAFT'})`]; token.policyIds = [policy.id]; } @@ -100,267 +70,432 @@ async function setDynamicTokenPolicy(tokens: any[], engineService?: PolicyEngine @Controller('tokens') @ApiTags('tokens') export class TokensApi { + /** + * Return a list of tokens + */ @Get('/') + @Auth( + Permissions.TOKENS_TOKEN_READ + // UserRole.STANDARD_REGISTRY + // UserRole.USER + ) + @ApiOperation({ + summary: 'Return a list of tokens.', + description: 'Returns all tokens. For the Standard Registry role it returns only the list of tokens, for other users it also returns token balances as well as the KYC, Freeze, and Association statuses. Not allowed for the Auditor role.', + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiQuery({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: false, + example: Examples.DB_ID + }) + @ApiQuery({ + name: 'status', + type: String, + enum: [ + 'Associated', + 'All' + ], + description: 'Token status', + required: false, + example: 'All' + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + headers: pageHeader, + type: TokenDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getTokens(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); + async getTokens( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('policyId') policyId?: string, + @Query('status') status?: string, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + ): Promise { try { const guardians = new Guardians(); const engineService = new PolicyEngine(); - const user = req.user; - const policyId = req.query?.policy; - - let pageIndex: number; - let pageSize: number; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = Number.parseInt(req.query.pageIndex, 10); - pageSize = Number.parseInt(req.query.pageSize, 10); - } - - let tokensAndCount = { - items: [], - count: 0 - } - - if (user.role === UserRole.STANDARD_REGISTRY) { - tokensAndCount = await guardians.getTokensPage(user.did, pageIndex, pageSize); - const map = await engineService.getTokensMap(user.did); - tokensAndCount.items = await setDynamicTokenPolicy(tokensAndCount.items, engineService); - tokensAndCount.items = setTokensPolicies(tokensAndCount.items, map, policyId, false); - } else if (user.did) { - tokensAndCount = await guardians.getAssociatedTokens(user.did, pageIndex, pageSize); - const map = await engineService.getTokensMap(user.parent, 'PUBLISH'); - tokensAndCount.items = await setDynamicTokenPolicy(tokensAndCount.items, engineService); - tokensAndCount.items = setTokensPolicies(tokensAndCount.items, map, policyId, true); + let tokensAndCount = { items: [], count: 0 }; + const owner = new EntityOwner(user); + if (owner) { + if (UserPermissions.has(user, Permissions.TOKENS_TOKEN_EXECUTE) && status !== 'All') { + tokensAndCount = await guardians.getAssociatedTokens(user.did, parseInteger(pageIndex), parseInteger(pageSize)); + const map = await engineService.getTokensMap(owner, 'PUBLISH'); + tokensAndCount.items = await setDynamicTokenPolicy(tokensAndCount.items, owner); + tokensAndCount.items = setTokensPolicies(tokensAndCount.items, map, policyId, true); + } else { + tokensAndCount = await guardians.getTokensPage(owner, parseInteger(pageIndex), parseInteger(pageSize)); + const map = await engineService.getTokensMap(owner); + tokensAndCount.items = await setDynamicTokenPolicy(tokensAndCount.items, owner); + tokensAndCount.items = setTokensPolicies(tokensAndCount.items, map, policyId, false); + } } return res - .setHeader('X-Total-Count', tokensAndCount.count) - .json(tokensAndCount.items); + .header('X-Total-Count', tokensAndCount.count) + .send(tokensAndCount.items); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Creates a new token + */ @Post('/') + @Auth( + Permissions.TOKENS_TOKEN_CREATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Creates a new token.', + description: 'Creates a new token.' + ONLY_SR, + }) + @ApiBody({ + description: 'Object that contains token information.', + required: true, + type: TokenDTO + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TokenDTO, + isArray: true + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async newToken(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async newToken( + @AuthUser() user: IAuthUser, + @Body() token: TokenDTO + ): Promise { try { const guardians = new Guardians(); const engineService = new PolicyEngine(); - const user = req.user; + const owner = new EntityOwner(user); - if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); - } - - let tokens = await guardians.setToken({ - token: req.body, - owner: user.did - }); - - tokens = await guardians.getTokens({ did: user.did }); - const map = await engineService.getTokensMap(user.did); + let tokens = await guardians.setToken(token, owner); + tokens = await guardians.getTokens({}, owner); + const map = await engineService.getTokensMap(owner); tokens = setTokensPolicies(tokens, map); - return res.status(201).json(tokens); + return tokens; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } + /** + * Creates a new token + */ @Post('/push') + @Auth( + Permissions.TOKENS_TOKEN_CREATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Creates a new token.', + description: 'Creates a new token.' + ONLY_SR, + }) + @ApiBody({ + description: 'Object that contains token information.', + required: true, + type: TokenDTO + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, TokenDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async pushTokenAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; + async pushTokenAsync( + @AuthUser() user: IAuthUser, + @Body() token: TokenDTO + ): Promise { if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } - const token = req.body; + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.CREATE_TOKEN, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.setTokenAsync(token, user.did, task); + await guardians.setTokenAsync(token, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - return res.status(202).send(task); + return task; } + /** + * Update token + */ @Put('/') @Auth( - UserRole.STANDARD_REGISTRY + Permissions.TOKENS_TOKEN_UPDATE, + // UserRole.STANDARD_REGISTRY, ) - @ApiSecurity('bearerAuth') @ApiOperation({ summary: 'Update token.', - description: 'Update token. Only users with the Standard Registry role are allowed to make the request.', + description: 'Update token.' + ONLY_SR, }) @ApiBody({ - description: 'Token', + description: 'Object that contains token information.', required: true, - schema: { - type: 'object' - } + type: TokenDTO }) @ApiOkResponse({ description: 'Updated token.', - schema: { - 'type': 'object' - }, - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) - @ApiUnprocessableEntityResponse({ - description: 'Unprocessable entity.' + type: TokenDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO }) + @ApiExtraModels(TokenDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async updateToken(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; - const token = req.body; + async updateToken( + @AuthUser() user: IAuthUser, + @Body() token: TokenDTO + ): Promise { + try { + if (!user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); + } - if (!user.did) { - throw new HttpException('User is not registered', HttpStatus.UNPROCESSABLE_ENTITY); - } + if (!token.tokenId) { + throw new HttpException('The field tokenId is required.', HttpStatus.UNPROCESSABLE_ENTITY); + } - if (!token.tokenId) { - throw new HttpException('The field tokenId is required', HttpStatus.UNPROCESSABLE_ENTITY); - } + const owner = new EntityOwner(user); + const guardians = new Guardians(); + const tokenObject = await guardians.getTokenById(token.tokenId, owner); - const guardians = new Guardians(); - const tokenObject = await guardians.getTokenById(token.tokenId); + if (!tokenObject) { + throw new HttpException('Token not found.', HttpStatus.NOT_FOUND) + } - if (!tokenObject) { - throw new HttpException('Token not found', HttpStatus.NOT_FOUND) - } + if (tokenObject.owner !== owner.owner) { + throw new HttpException('Invalid creator.', HttpStatus.FORBIDDEN) + } - if (tokenObject.owner !== user.did) { - throw new HttpException('Invalid creator.', HttpStatus.FORBIDDEN) + return await guardians.updateToken(token, owner); + } catch (error) { + await InternalException(error); } - - return await guardians.updateToken(token); } + /** + * Update token + */ @Put('/push') + @Auth( + Permissions.TOKENS_TOKEN_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Update token.', + description: 'Update token.' + ONLY_SR, + }) + @ApiBody({ + description: 'Object that contains token information.', + required: true, + type: TokenDTO + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, TokenDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async updateTokenAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async updateTokenAsync( + @AuthUser() user: IAuthUser, + @Body() token: TokenDTO + ): Promise { try { - const user = req.user; - const token = req.body; - if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } if (!token.tokenId) { - return res.status(422).json(prepareValidationResponse('The field tokenId is required')); + throw new HttpException('Invalid token id.', HttpStatus.UNPROCESSABLE_ENTITY); } const guardians = new Guardians(); - const tokenObject = await guardians.getTokenById(token.tokenId); + const owner = new EntityOwner(user); + const tokenObject = await guardians.getTokenById(token.tokenId, owner); if (!tokenObject) { - throw new HttpException('Token not found', HttpStatus.NOT_FOUND) + throw new HttpException('Token not found.', HttpStatus.NOT_FOUND) } - if (tokenObject.owner !== user.did) { + if (tokenObject.owner !== owner.owner) { throw new HttpException('Invalid creator.', HttpStatus.FORBIDDEN) } const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.UPDATE_TOKEN, user.id); RunFunctionAsync(async () => { - await guardians.updateTokenAsync(token, task); + await guardians.updateTokenAsync(token, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - return res.status(202).send(task); + return task; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Delete token + */ @Delete('/push/:tokenId') + @Auth( + Permissions.TOKENS_TOKEN_DELETE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Deletes the token with the provided schema ID.', + description: 'Deletes the token with the provided schema ID.' + ONLY_SR, + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async deleteTokenAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async deleteTokenAsync( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string + ): Promise { try { - const user = req.user; - const tokenId = req.params.tokenId; - - if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); - } - + const owner = new EntityOwner(user); const guardians = new Guardians(); - const tokenObject = await guardians.getTokenById(tokenId); + const tokenObject = await guardians.getTokenById(tokenId, owner); if (!tokenObject) { throw new HttpException('Token does not exist.', HttpStatus.NOT_FOUND) } - if (tokenObject.owner !== user.did) { + if (tokenObject.owner !== owner.owner) { throw new HttpException('Invalid creator.', HttpStatus.FORBIDDEN); } const engineService = new PolicyEngine(); - const map = await engineService.getTokensMap(user.did); + const map = await engineService.getTokensMap(owner); setTokensPolicies([tokenObject], map, undefined, false); if (!tokenObject.canDelete) { - throw new HttpException('Token cannot be deleted', HttpStatus.FORBIDDEN); + throw new HttpException('Token cannot be deleted.', HttpStatus.FORBIDDEN); } const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.DELETE_TOKEN, user.id); RunFunctionAsync(async () => { - await guardians.deleteTokenAsync(tokenId, task); + await guardians.deleteTokenAsync(tokenId, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - return res.status(202).send(task); + return task; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Associate + */ @Put('/:tokenId/associate') + @Auth( + Permissions.TOKENS_TOKEN_EXECUTE, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Associates the user with the provided Hedera token.', + description: 'Associates the user with the provided Hedera token. Only users with the Installer role are allowed to make the request.', + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TokenInfoDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenInfoDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async associateToken(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.USER)(req.user); + async associateToken( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string + ): Promise { try { - const guardians = new Guardians(); - const tokenId = req.params.tokenId; - const userDid = req.user.did; - if (!userDid) { - return res.status(422).json(prepareValidationResponse('User not registered')); + if (!user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } - const status = await guardians.associateToken(tokenId, userDid); - return res.json(status); + const owner = new EntityOwner(user); + const guardians = new Guardians(); + return await guardians.associateToken(tokenId, owner); } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error?.message?.toLowerCase().includes('user not found')) { - throw new HttpException('User not found', HttpStatus.NOT_FOUND) + throw new HttpException('User not found.', HttpStatus.NOT_FOUND) } if (error?.message?.toLowerCase().includes('token not found')) { throw new HttpException('Token does not exist.', HttpStatus.NOT_FOUND) @@ -369,46 +504,101 @@ export class TokensApi { } } + /** + * Associate + */ @Put('/push/:tokenId/associate') + @Auth( + Permissions.TOKENS_TOKEN_EXECUTE, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Associates the user with the provided Hedera token.', + description: 'Associates the user with the provided Hedera token. Only users with the Installer role are allowed to make the request.', + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async associateTokenAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.USER)(req.user); - const tokenId = req.params.tokenId; - const user = req.user; + async associateTokenAsync( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string + ): Promise { if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.ASSOCIATE_TOKEN, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.associateTokenAsync(tokenId, user.did, task); + await guardians.associateTokenAsync(tokenId, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - return res.status(202).send(task); + return task; } + /** + * Dissociate + */ @Put('/:tokenId/dissociate') + @Auth( + Permissions.TOKENS_TOKEN_EXECUTE, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Associate the user with the provided Hedera token.', + description: 'Disassociates the user with the provided Hedera token. Only users with the Installer role are allowed to make the request.', + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TokenInfoDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenInfoDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async dissociateToken(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.USER)(req.user); + async dissociateToken( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string + ): Promise { try { - const guardians = new Guardians(); - const tokenId = req.params.tokenId; - const userDid = req.user.did; - if (!userDid) { - return res.status(422).json(prepareValidationResponse('User not registered')); + if (!user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } - const status = await guardians.dissociateToken(tokenId, userDid); - return res.json(status); + const owner = new EntityOwner(user); + const guardians = new Guardians(); + return await guardians.dissociateToken(tokenId, owner); } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error?.message?.toLowerCase().includes('user not found')) { - throw new HttpException('User not found', HttpStatus.NOT_FOUND) + throw new HttpException('User not found.', HttpStatus.NOT_FOUND) } if (error?.message?.toLowerCase().includes('token not found')) { throw new HttpException('Token does not exist.', HttpStatus.NOT_FOUND) @@ -417,304 +607,671 @@ export class TokensApi { } } + /** + * Dissociate + */ @Put('/push/:tokenId/dissociate') + @Auth( + Permissions.TOKENS_TOKEN_EXECUTE, + // UserRole.USER, + ) + @ApiOperation({ + summary: 'Associate the user with the provided Hedera token.', + description: 'Disassociates the user with the provided Hedera token. Only users with the Installer role are allowed to make the request.', + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async dissociateTokenAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.USER)(req.user); - const tokenId = req.params.tokenId; - const user = req.user; + async dissociateTokenAsync( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string + ): Promise { if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.DISSOCIATE_TOKEN, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.dissociateTokenAsync(tokenId, user.did, task); + await guardians.dissociateTokenAsync(tokenId, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } + /** + * KYC + */ @Put('/:tokenId/:username/grant-kyc') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Sets the KYC flag for the user.', + description: 'Sets the KYC flag for the user.' + ONLY_SR, + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TokenInfoDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenInfoDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async grantKyc(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async grantKyc( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { try { - const guardians = new Guardians(); - const tokenId = req.params.tokenId; - const username = req.params.username; - const userDid = req.user.did; - if (!userDid) { - return res.status(422).json(prepareValidationResponse('User not registered')); + if (!user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } - return res.json(await guardians.grantKycToken(tokenId, username, userDid)); + const owner = new EntityOwner(user); + const guardians = new Guardians(); + return await guardians.grantKycToken(tokenId, username, owner); } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error?.message?.toLowerCase().includes('user not found')) { - throw new HttpException('User not found', HttpStatus.NOT_FOUND) + throw new HttpException('User not found.', HttpStatus.NOT_FOUND) } if (error?.message?.toLowerCase().includes('token not found')) { - throw new HttpException('Token not found', HttpStatus.NOT_FOUND) + throw new HttpException('Token not found.', HttpStatus.NOT_FOUND) } throw error; } } + /** + * KYC + */ @Put('/push/:tokenId/:username/grant-kyc') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Sets the KYC flag for the user.', + description: 'Sets the KYC flag for the user.' + ONLY_SR, + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async grantKycAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const tokenId = req.params.tokenId; - const username = req.params.username; - const user = req.user; + async grantKycAsync( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.GRANT_KYC, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.grantKycTokenAsync(tokenId, username, user.did, task); + await guardians.grantKycTokenAsync(tokenId, username, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } + /** + * KYC + */ @Put('/:tokenId/:username/revoke-kyc') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Unsets the KYC flag for the user.', + description: 'Unsets the KYC flag for the user.' + ONLY_SR + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TokenInfoDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenInfoDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async revokeKyc(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async revokeKyc( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { try { const guardians = new Guardians(); - const tokenId = req.params.tokenId; - const username = req.params.username; - const userDid = req.user.did; - if (!userDid) { - return res.status(422).json(prepareValidationResponse('User not registered')); - } - const result = await guardians.revokeKycToken(tokenId, username, userDid); - return res.json(result); + if (!user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); + return await guardians.revokeKycToken(tokenId, username, owner); } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error?.message?.toLowerCase().includes('user not found')) { - throw new HttpException('User not found', HttpStatus.NOT_FOUND) + throw new HttpException('User not found.', HttpStatus.NOT_FOUND) } if (error?.message?.toLowerCase().includes('token not found')) { - throw new HttpException('Token not found', HttpStatus.NOT_FOUND) + throw new HttpException('Token not found.', HttpStatus.NOT_FOUND) } throw error; } } + /** + * KYC + */ @Put('/push/:tokenId/:username/revoke-kyc') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Unsets the KYC flag for the user.', + description: 'Unsets the KYC flag for the user.' + ONLY_SR + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async revokeKycAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const tokenId = req.params.tokenId; - const username = req.params.username; - const user = req.user; + async revokeKycAsync( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { if (!user.did) { - throw new HttpException('User not registered', HttpStatus.UNPROCESSABLE_ENTITY); + throw new HttpException('User not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.REVOKE_KYC, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.revokeKycTokenAsync(tokenId, username, user.did, task); + await guardians.revokeKycTokenAsync(tokenId, username, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } + /** + * Freeze + */ @Put('/:tokenId/:username/freeze') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Freeze transfers of the specified token for the user.', + description: 'Freezes transfers of the specified token for the user.' + ONLY_SR + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TokenInfoDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenInfoDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async freezeToken(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async freezeToken( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { try { + if (!user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); const guardians = new Guardians(); - const tokenId = req.params.tokenId; - const username = req.params.username; - const userDid = req.user.did; - if (!userDid) { - return res.status(422).json(prepareValidationResponse('User not registered')); - } - const result = await guardians.freezeToken(tokenId, username, userDid); - return res.json(result); + return await guardians.freezeToken(tokenId, username, owner); } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error?.message?.toLowerCase().includes('user not found')) { - throw new HttpException('User not registered', HttpStatus.NOT_FOUND); + throw new HttpException('User not registered.', HttpStatus.NOT_FOUND); } if (error?.message?.toLowerCase().includes('token not found')) { - throw new HttpException('Token not registered', HttpStatus.NOT_FOUND); + throw new HttpException('Token not registered.', HttpStatus.NOT_FOUND); } throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); } } + /** + * Unfreeze + */ @Put('/:tokenId/:username/unfreeze') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Unfreezes transfers of the specified token for the user.', + description: 'Unfreezes transfers of the specified token for the user.' + ONLY_SR + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TokenInfoDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenInfoDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async unfreezeToken(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async unfreezeToken( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { try { + if (!user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); + } const guardians = new Guardians(); - const tokenId = req.params.tokenId; - const username = req.params.username; - const userDid = req.user.did; - if (!userDid) { - return res.status(422).json(prepareValidationResponse('User not registered')); - } - const result = await guardians.unfreezeToken(tokenId, username, userDid); - return res.json(result); + return await guardians.unfreezeToken(tokenId, username, user.did); } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error?.message?.toLowerCase().includes('user not found')) { - throw new HttpException('User not registered', HttpStatus.NOT_FOUND); + throw new HttpException('User not registered.', HttpStatus.NOT_FOUND); } if (error?.message?.toLowerCase().includes('token not found')) { - throw new HttpException('Token not registered', HttpStatus.NOT_FOUND); + throw new HttpException('Token not registered.', HttpStatus.NOT_FOUND); } throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); } } + /** + * Freeze + */ @Put('/push/:tokenId/:username/freeze') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Freeze transfers of the specified token for the user.', + description: 'Freezes transfers of the specified token for the user.' + ONLY_SR + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async freezeTokenAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const tokenId = req.params.tokenId; - const username = req.params.username; - const user = req.user; + async freezeTokenAsync( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.FREEZE_TOKEN, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.freezeTokenAsync(tokenId, username, user.did, task); + await guardians.freezeTokenAsync(tokenId, username, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } + /** + * Unfreeze + */ @Put('/push/:tokenId/:username/unfreeze') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Unfreezes transfers of the specified token for the user.', + description: 'Unfreezes transfers of the specified token for the user.' + ONLY_SR + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TaskDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async unfreezeTokenAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const tokenId = req.params.tokenId; - const username = req.params.username; - const user = req.user; + async unfreezeTokenAsync( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { if (!user.did) { - return res.status(422).json(prepareValidationResponse('User not registered')); + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.UNFREEZE_TOKEN, user.id); RunFunctionAsync(async () => { const guardians = new Guardians(); - await guardians.unfreezeTokenAsync(tokenId, username, user.did, task); + await guardians.unfreezeTokenAsync(tokenId, username, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: error.code || 500, message: error.message }); }); - - return res.status(202).send(task); + return task; } /** - * @param req - * @param res + * User info */ @Get('/:tokenId/:username/info') + @Auth( + Permissions.TOKENS_TOKEN_MANAGE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Returns user information for the selected token.', + description: 'Returns user information for the selected token.' + ONLY_SR + }) + @ApiParam({ + name: 'tokenId', + type: String, + description: 'Token ID', + required: true, + example: Examples.DB_ID + }) + @ApiParam({ + name: 'username', + type: String, + description: 'Username', + required: true, + example: 'username' + }) + @ApiOkResponse({ + description: 'Successful operation.', + type: TokenInfoDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(TokenInfoDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getTokenInfo(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getTokenInfo( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string, + @Param('username') username: string + ): Promise { try { + if (!user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); const guardians = new Guardians(); - const tokenId = req.params.tokenId; - const username = req.params.username; - const userDid = req.user.did; - if (!userDid) { - return res.status(422).json(prepareValidationResponse('User not registered')); - } - const result = await guardians.getInfoToken(tokenId, username, userDid); - return res.json(result as ITokenInfo); + return await guardians.getInfoToken(tokenId, username, owner); } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error?.message?.toLowerCase().includes('user not found')) { - throw new HttpException('User not registered', HttpStatus.NOT_FOUND); + throw new HttpException('User not registered.', HttpStatus.NOT_FOUND); } if (error?.message?.toLowerCase().includes('token not found')) { - throw new HttpException('Token not registered', HttpStatus.NOT_FOUND); + throw new HttpException('Token not registered.', HttpStatus.NOT_FOUND); } throw error; } } /** - * @param req - * @param res + * Serials */ @Get('/:tokenId/serials') - @ApiBearerAuth() - @ApiExtraModels(InternalServerErrorDTO) + @Auth( + Permissions.TOKENS_TOKEN_READ + // UserRole.STANDARD_REGISTRY + // UserRole.USER + ) @ApiOperation({ summary: 'Return token serials.', description: 'Returns token serials of current user.', }) @ApiParam({ name: 'tokenId', - type: 'string', - description: 'Token identifier', + type: String, + description: 'Token ID', required: true, - example: '0.0.1', + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Token serials.', isArray: true, type: Number, }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getTokenSerials(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY, UserRole.USER)(req.user); + async getTokenSerials( + @AuthUser() user: IAuthUser, + @Param('tokenId') tokenId: string + ): Promise { try { const guardians = new Guardians(); - const tokenId = req.params.tokenId; - const userDid = req.user.did; - const result = await guardians.getTokenSerials(tokenId, userDid); - return res.json(result); + return await guardians.getTokenSerials(tokenId, user.did); } catch (error) { new Logger().error(error, ['API_GATEWAY']); if (error?.message?.toLowerCase().includes('user not found')) { - throw new HttpException('User not registered', HttpStatus.NOT_FOUND); + throw new HttpException('User not registered.', HttpStatus.NOT_FOUND); } if (error?.message?.toLowerCase().includes('token not found')) { - throw new HttpException('Token not registered', HttpStatus.NOT_FOUND); + throw new HttpException('Token not registered.', HttpStatus.NOT_FOUND); } throw error; } } + + /** + * Policy config menu + */ + @Get('/menu/all') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + Permissions.MODULES_MODULE_UPDATE, + Permissions.TOOLS_TOOL_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) + @ApiOperation({ + summary: 'Return a list of tokens.', + description: 'Returns tokens menu.' + ONLY_SR + }) + @ApiOkResponse({ + description: 'Modules.', + isArray: true, + type: TokenDTO, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO, + }) + @ApiExtraModels(TokenDTO, InternalServerErrorDTO) + @HttpCode(HttpStatus.OK) + async getMenu( + @AuthUser() user: IAuthUser + ): Promise { + try { + const owner = new EntityOwner(user); + const guardians = new Guardians(); + const engineService = new PolicyEngine(); + const map = await engineService.getTokensMap(owner, 'PUBLISH'); + let items = await guardians.getTokens({}, owner); + items = await setDynamicTokenPolicy(items, owner); + items = setTokensPolicies(items, map, null, false); + return items; + } catch (error) { + await InternalException(error); + } + } } diff --git a/api-gateway/src/api/service/tool.ts b/api-gateway/src/api/service/tool.ts index cc3ca567bc..d285aff74c 100644 --- a/api-gateway/src/api/service/tool.ts +++ b/api-gateway/src/api/service/tool.ts @@ -1,81 +1,54 @@ -import { Logger, RunFunctionAsync } from '@guardian/common'; -import { Guardians } from '../../helpers/guardians.js'; -import { - Controller, - Delete, - Get, - HttpCode, - HttpException, - HttpStatus, - Post, - Put, - Req, - Response, - UploadedFiles, - UseInterceptors, -} from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { TaskAction, UserRole } from '@guardian/interfaces'; -import { - ApiBody, - ApiConsumes, - ApiForbiddenResponse, - ApiInternalServerErrorResponse, - ApiOkResponse, - ApiOperation, - ApiSecurity, - ApiTags, - ApiUnauthorizedResponse, - getSchemaPath -} from '@nestjs/swagger'; -import { ApiImplicitQuery } from '@nestjs/swagger/dist/decorators/api-implicit-query.decorator.js'; -import { TaskManager } from '../../helpers/task-manager.js'; -import { ServiceError } from '../../helpers/service-requests-base.js'; -import { InternalServerErrorDTO, TaskDTO, ToolDTO } from '../../middlewares/validation/schemas/index.js'; -import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator.js'; -import { AnyFilesInterceptor } from '@nestjs/platform-express'; -import { UseCache } from '../../helpers/decorators/cache.js'; - -const ONLY_SR = ' Only users with the Standard Registry role are allowed to make the request.' +import { IAuthUser, Logger, RunFunctionAsync } from '@guardian/common'; +import { Body, Controller, Delete, Get, HttpCode, HttpException, HttpStatus, Param, Post, Put, Query, Response, UseInterceptors } from '@nestjs/common'; +import { Permissions, TaskAction } from '@guardian/interfaces'; +import { ApiBody, ApiConsumes, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, ApiQuery, ApiExtraModels, ApiParam } from '@nestjs/swagger'; +import { ExportMessageDTO, ImportMessageDTO, InternalServerErrorDTO, TaskDTO, ToolDTO, ToolPreviewDTO, ToolValidationDTO, Examples, pageHeader } from '#middlewares'; +import { UseCache, ServiceError, TaskManager, Guardians, InternalException, ONLY_SR, MultipartFile, UploadedFiles, AnyFilesInterceptor, EntityOwner } from '#helpers'; +import { AuthUser, Auth } from '#auth'; @Controller('tools') @ApiTags('tools') export class ToolsApi { /** - * Create new tool + * Creates a new tool */ @Post('/') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new tool.', description: 'Creates a new tool.' + ONLY_SR, }) + @ApiBody({ + description: 'Policy configuration.', + type: ToolDTO, + required: true + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(ToolDTO) - }, + type: ToolDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async createNewTool(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async createNewTool( + @AuthUser() user: IAuthUser, + @Body() tool: ToolDTO + ): Promise { try { - const tool = req.body; if (!tool.config || tool.config.blockType !== 'tool') { throw new HttpException('Invalid tool config', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const guardian = new Guardians(); - const item = await guardian.createTool(tool, req.user.did); - return res.status(201).json(item); + return await guardian.createTool(tool, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } @@ -83,45 +56,49 @@ export class ToolsApi { * Create new tool (Async) */ @Post('/push') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new tool.', description: 'Creates a new tool.' + ONLY_SR, }) + @ApiBody({ + description: 'Policy configuration.', + type: ToolDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(TaskDTO) - } + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(TaskDTO, ToolDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async createNewToolAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async createNewToolAsync( + @AuthUser() user: IAuthUser, + @Body() tool: ToolDTO + ): Promise { try { - const tool = req.body; - const user = req.user; if (!tool.config || tool.config.blockType !== 'tool') { throw new HttpException('Invalid tool config', HttpStatus.UNPROCESSABLE_ENTITY); } + const owner = new EntityOwner(user); const guardian = new Guardians(); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.CREATE_TOOL, user.id); RunFunctionAsync(async () => { - await guardian.createToolAsync(tool, user.did, task); + await guardian.createToolAsync(tool, owner, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return res.status(202).send(task); + return task; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } @@ -129,19 +106,22 @@ export class ToolsApi { * Get page */ @Get('/') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return a list of all tools.', description: 'Returns all tools.' + ONLY_SR, }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageIndex', type: Number, description: 'The number of pages to skip before starting to collect the result set', required: false, example: 0 }) - @ApiImplicitQuery({ + @ApiQuery({ name: 'pageSize', type: Number, description: 'The numbers of items to return', @@ -151,36 +131,31 @@ export class ToolsApi { @ApiOkResponse({ description: 'Successful operation.', isArray: true, - schema: { - $ref: getSchemaPath(ToolDTO) - }, + headers: pageHeader, + type: ToolDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getTools(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getTools( + @AuthUser() user: IAuthUser, + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number + ): Promise { try { + const owner = new EntityOwner(user); const guardians = new Guardians(); - let pageIndex: any; - let pageSize: any; - if (req.query && req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } const { items, count } = await guardians.getTools({ - owner: req.user.did, pageIndex, pageSize - }); - return res.setHeader('X-Total-Count', count).json(items); + }, owner); + return res.header('X-Total-Count', count).send(items); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -188,40 +163,44 @@ export class ToolsApi { * Delete tool */ @Delete('/:id') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_DELETE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Deletes the tool with the provided tool ID.' + ONLY_SR, description: 'Deletes the tool.' }) - @ApiImplicitParam({ + @ApiParam({ name: 'id', type: String, description: 'Tool ID', required: true, - example: '000000000000000000000000' + example: Examples.DB_ID }) @ApiOkResponse({ - description: 'Successful operation.' + description: 'Successful operation.', + type: Boolean }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async deleteTool(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async deleteTool( + @AuthUser() user: IAuthUser, + @Param('id') id: string + ): Promise { try { - const guardian = new Guardians(); - if (!req.params.id) { - throw new Error('Invalid id') + if (!id) { + throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY); } - const result = await guardian.deleteTool(req.params.id, req.user.did); - return res.status(200).json(result); + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.deleteTool(id, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -229,49 +208,44 @@ export class ToolsApi { * Get tool by id */ @Get('/:id') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_READ, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Retrieves tool configuration.', description: 'Retrieves tool configuration for the specified tool ID.' + ONLY_SR }) - @ApiImplicitParam({ + @ApiParam({ name: 'id', type: String, description: 'Tool ID', required: true, - example: '000000000000000000000000' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(ToolDTO) - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: ToolDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getToolById(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async getToolById( + @AuthUser() user: IAuthUser, + @Param('id') id: string + ): Promise { try { - const guardian = new Guardians(); - if (!req.params.id) { - throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY) + if (!id) { + throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY); } - const item = await guardian.getToolById(req.params.id, req.user.did); - return res.json(item); + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.getToolById(id, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -279,53 +253,53 @@ export class ToolsApi { * Update tool */ @Put('/:id') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Updates tool configuration.', description: 'Updates tool configuration for the specified tool ID.' + ONLY_SR }) - @ApiImplicitParam({ + @ApiParam({ name: 'id', type: String, description: 'Tool ID', required: true, - example: '000000000000000000000000' + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Tool configuration.', + type: ToolDTO, + required: true }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(ToolDTO) - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: ToolDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async updateTool(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - if (!req.params.id) { + async updateTool( + @AuthUser() user: IAuthUser, + @Param('id') id: string, + @Body() tool: ToolDTO + ): Promise { + if (!id) { throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY); } - const guardian = new Guardians(); - const tool = req.body; if (!tool.config || tool.config.blockType !== 'tool') { throw new HttpException('Invalid tool config', HttpStatus.UNPROCESSABLE_ENTITY) } try { - const result = await guardian.updateTool(req.params.id, tool, req.user.did); - return res.status(201).json(result); + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.updateTool(id, tool, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -333,46 +307,50 @@ export class ToolsApi { * Publish tool */ @Put('/:id/publish') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Publishes the tool onto IPFS.', description: 'Publishes the tool with the specified (internal) tool ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera topic.' + ONLY_SR }) - @ApiImplicitParam({ + @ApiParam({ name: 'id', type: String, description: 'Tool ID', required: true, - example: '000000000000000000000000' + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Tool configuration.', + type: ToolDTO, + required: true }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(ToolDTO) - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: ToolValidationDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolValidationDTO, ToolDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async publishTool(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async publishTool( + @AuthUser() user: IAuthUser, + @Param('id') id: string, + @Body() tool: ToolDTO + ): Promise { try { - const tool = await guardian.publishTool(req.params.id, req.user.did, req.body); - return res.json(tool); + if (!id) { + throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.publishTool(id, owner, tool); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -380,87 +358,95 @@ export class ToolsApi { * Publish tool (Async) */ @Put('/:id/push/publish') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Publishes the tool onto IPFS.', description: 'Publishes the tool with the specified (internal) tool ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera topic.' + ONLY_SR }) - @ApiImplicitParam({ + @ApiParam({ name: 'id', type: String, description: 'Tool ID', required: true, - example: '000000000000000000000000' + example: Examples.DB_ID + }) + @ApiBody({ + description: 'Tool configuration.', + type: ToolDTO, + required: true }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(TaskDTO) - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async publishToolAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const user = req.user; + async publishToolAsync( + @AuthUser() user: IAuthUser, + @Param('id') id: string, + @Body() tool: ToolDTO + ): Promise { + if (!id) { + throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.PUBLISH_TOOL, user.id); RunFunctionAsync(async () => { const guardian = new Guardians(); - await guardian.publishToolAsync(req.params.id, user.did, req.body, task); + await guardian.publishToolAsync(id, owner, tool, task); }, async (error) => { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message || error }); }); - return res.status(202).send(task); + return task; } /** * Validate tool */ @Post('/validate') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_UPDATE, + Permissions.TOOLS_TOOL_REVIEW, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Validates selected tool.', description: 'Validates selected tool.' + ONLY_SR }) - @ApiOkResponse({ - schema: { - type: 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'Tool configuration.', + type: ToolDTO, + required: true }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Validation result.', + type: ToolValidationDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolDTO, ToolValidationDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async validateTool(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async validateTool( + @AuthUser() user: IAuthUser, + @Body() tool: ToolDTO + ): Promise { try { - return res.send(await guardian.validateTool(req.user.did, req.body)); + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.validateTool(owner, tool); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } @@ -468,45 +454,46 @@ export class ToolsApi { * Export tool in file */ @Get('/:id/export/file') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return tool and its artifacts in a zip file format for the specified tool.', description: 'Returns a zip file containing the published tool and all associated artifacts, i.e. schemas and VCs.' + ONLY_SR }) - @ApiImplicitParam({ + @ApiParam({ name: 'id', type: String, description: 'Tool ID', required: true, - example: '000000000000000000000000' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation. Response zip file.' }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) @HttpCode(HttpStatus.OK) - async toolExportFile(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async toolExportFile( + @AuthUser() user: IAuthUser, + @Param('id') id: string, + @Response() res: any + ): Promise { try { - const file: any = await guardian.exportToolFile(req.params.id, req.user.did); - res.setHeader('Content-disposition', `attachment; filename=tool_${Date.now()}`); - res.setHeader('Content-type', 'application/zip'); + if (!id) { + throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); + const guardian = new Guardians(); + const file: any = await guardian.exportToolFile(id, owner); + res.header('Content-disposition', `attachment; filename=tool_${Date.now()}`); + res.header('Content-type', 'application/zip'); return res.send(file); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -514,45 +501,44 @@ export class ToolsApi { * Export tool in message */ @Get('/:id/export/message') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return Heder message ID for the specified published tool.', description: 'Returns the Hedera message ID for the specified tool published onto IPFS.' + ONLY_SR }) - @ApiImplicitParam({ + @ApiParam({ name: 'id', type: String, description: 'Tool ID', required: true, - example: '000000000000000000000000' + example: Examples.DB_ID }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: ExportMessageDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ExportMessageDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async toolExportMessage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async toolExportMessage( + @AuthUser() user: IAuthUser, + @Param('id') id: string, + ): Promise { try { - return res.send(await guardian.exportToolMessage(req.params.id, req.user.did)); + if (!id) { + throw new HttpException('Invalid id', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.exportToolMessage(id, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -560,39 +546,42 @@ export class ToolsApi { * Preview tool from IPFS */ @Post('/import/message/preview') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new tool from IPFS.', description: 'Imports new tool and all associated artifacts from IPFS into the local DB.' + ONLY_SR }) - @ApiOkResponse({ - description: 'Successful operation.', - schema: { - type: 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Tool preview.', + type: ToolPreviewDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ImportMessageDTO, ToolPreviewDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async toolImportMessagePreview(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async toolImportMessagePreview( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } try { - const tool = await guardian.previewToolMessage(req.body.messageId, req.user.did); - return res.send(tool); + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.previewToolMessage(messageId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -600,39 +589,42 @@ export class ToolsApi { * Import tool from IPFS */ @Post('/import/message') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new tool from IPFS.', description: 'Imports new tool and all associated artifacts from IPFS into the local DB.' + ONLY_SR }) + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(ToolDTO) - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: ToolDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ImportMessageDTO, ToolDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async toolImportMessage(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async toolImportMessage( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } + const owner = new EntityOwner(user); const guardian = new Guardians(); try { - const tool = await guardian.importToolMessage(req.body.messageId, req.user.did); - return res.status(201).send(tool); + return await guardian.importToolMessage(messageId, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -640,39 +632,37 @@ export class ToolsApi { * Preview tool from file */ @Post('/import/file/preview') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new tool from a zip file.', description: 'Imports new tool and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR }) - @ApiOkResponse({ - description: 'Successful operation.', - schema: { - 'type': 'object' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', + @ApiBody({ + description: 'File.', }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + @ApiOkResponse({ + description: 'Module preview.', + type: ToolPreviewDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolPreviewDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async toolImportFilePreview(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async toolImportFilePreview( + @AuthUser() user: IAuthUser, + @Body() body: any + ): Promise { try { - const tool = await guardian.previewToolFile(req.body, req.user.did); - return res.send(tool); + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.previewToolFile(body, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -680,39 +670,37 @@ export class ToolsApi { * Import tool from IPFS */ @Post('/import/file') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new tool from a zip file.', description: 'Imports new tool and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR }) + @ApiBody({ + description: 'File.', + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(ToolDTO) - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: ToolDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ToolDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async toolImportFile(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + async toolImportFile( + @AuthUser() user: IAuthUser, + @Body() body: any + ): Promise { try { - const tool = await guardian.importToolFile(req.body, req.user.did); - return res.status(201).send(tool); + const owner = new EntityOwner(user); + const guardian = new Guardians(); + return await guardian.importToolFile(body, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -720,16 +708,17 @@ export class ToolsApi { * Import tool from file with metadata */ @Post('/import/file-metadata') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOL_MIGRATION_CREATE, + //UserRole.STANDARD_REGISTRY + ) @ApiOperation({ summary: 'Imports new tool from a zip file.', description: 'Imports new tool and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(ToolDTO) - } + type: ToolDTO }) @ApiConsumes('multipart/form-data') @ApiBody({ @@ -749,27 +738,18 @@ export class ToolsApi { } } }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', - }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) @UseInterceptors(AnyFilesInterceptor()) @HttpCode(HttpStatus.CREATED) async toolImportFileWithMetadata( - @Req() req, + @AuthUser() user: IAuthUser, @UploadedFiles() files: any - ): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const guardian = new Guardians(); + ): Promise { try { + const owner = new EntityOwner(user); const file = files.find((item) => item.fieldname === 'file'); if (!file) { throw new Error('There is no tool file'); @@ -777,18 +757,15 @@ export class ToolsApi { const metadata = files.find( (item) => item.fieldname === 'metadata' ); + const guardian = new Guardians(); const tool = await guardian.importToolFile( file.buffer, - req.user.did, + owner, metadata?.buffer && JSON.parse(metadata.buffer.toString()) ); return tool; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } @@ -796,36 +773,35 @@ export class ToolsApi { * Import tool from IPFS (Async) */ @Post('/push/import/file') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new tool from a zip file.', description: 'Imports new tool and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.' + ONLY_SR }) + @ApiBody({ + description: 'A zip file containing tool config.', + required: true, + type: String + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(TaskDTO) - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async toolImportFileAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async toolImportFileAsync( + @AuthUser() user: IAuthUser, + @Body() zip: any + ): Promise { try { - const user = req.user; - const owner = req.user.did; - const zip = req.body; + const owner = new EntityOwner(user); const guardian = new Guardians(); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.IMPORT_TOOL_FILE, user.id); @@ -835,10 +811,9 @@ export class ToolsApi { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return res.status(202).send(task); + return task; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -846,7 +821,10 @@ export class ToolsApi { * Import tool from file with metadata (Async) */ @Post('/push/import/file-metadata') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOL_MIGRATION_CREATE, + //UserRole.STANDARD_REGISTRY + ) @ApiOperation({ summary: 'Imports new tool from a zip file.', description: @@ -873,37 +851,25 @@ export class ToolsApi { }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(TaskDTO), - }, - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO), - }, + type: InternalServerErrorDTO, }) @UseInterceptors(AnyFilesInterceptor()) @HttpCode(HttpStatus.ACCEPTED) async toolImportFileWithMetadataAsync( - @Req() req, - @UploadedFiles() files: any - ): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @AuthUser() user: IAuthUser, + @UploadedFiles() files: MultipartFile[] + ): Promise { try { const file = files.find(item => item.fieldname === 'file'); if (!file) { throw new Error('There is no tool file'); } + const owner = new EntityOwner(user); const metadata = files.find(item => item.fieldname === 'metadata'); - const user = req.user; - const owner = req.user.did; const guardian = new Guardians(); const taskManager = new TaskManager(); const task = taskManager.start( @@ -929,11 +895,7 @@ export class ToolsApi { ); return task; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException( - error.message, - HttpStatus.INTERNAL_SERVER_ERROR - ); + await InternalException(error); } } @@ -941,36 +903,38 @@ export class ToolsApi { * Import tool from IPFS (Async) */ @Post('/push/import/message') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.TOOLS_TOOL_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Imports new tool from IPFS.', description: 'Imports new tool and all associated artifacts from IPFS into the local DB.' + ONLY_SR }) + @ApiBody({ + description: 'Message.', + type: ImportMessageDTO, + }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - $ref: getSchemaPath(TaskDTO) - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) + @ApiExtraModels(ImportMessageDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async toolImportMessageAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async toolImportMessageAsync( + @AuthUser() user: IAuthUser, + @Body() body: ImportMessageDTO + ): Promise { + const messageId = body?.messageId; + if (!messageId) { + throw new HttpException('Message ID in body is empty', HttpStatus.UNPROCESSABLE_ENTITY); + } try { - const user = req.user; - const owner = req.user.did; - const messageId = req.body.messageId; + const owner = new EntityOwner(user); const guardian = new Guardians(); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.IMPORT_TOOL_MESSAGE, user.id); @@ -980,10 +944,9 @@ export class ToolsApi { new Logger().error(error, ['API_GATEWAY']); taskManager.addError(task.taskId, { code: 500, message: error.message }); }); - return res.status(202).send(task); + return task; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } @@ -991,38 +954,37 @@ export class ToolsApi { * Policy config menu */ @Get('/menu/all') - @ApiSecurity('bearerAuth') + @Auth( + Permissions.POLICIES_POLICY_UPDATE, + Permissions.MODULES_MODULE_UPDATE, + Permissions.TOOLS_TOOL_UPDATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Return a list of tools.', description: 'Returns tools menu.' + ONLY_SR }) @ApiOkResponse({ - schema: { - type: 'array' - } - }) - @ApiUnauthorizedResponse({ - description: 'Unauthorized.', - }) - @ApiForbiddenResponse({ - description: 'Forbidden.', + description: 'Modules.', + isArray: true, + type: ToolDTO, }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @HttpCode(HttpStatus.OK) + @ApiExtraModels(ToolDTO, InternalServerErrorDTO) @UseCache() - async getMenu(@Req() req): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + @HttpCode(HttpStatus.OK) + async getMenu( + @AuthUser() user: IAuthUser + ): Promise { try { + const owner = new EntityOwner(user); const guardians = new Guardians(); - return await guardians.getMenuTool(req.user.did); + return await guardians.getMenuTool(owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/trust-chains.ts b/api-gateway/src/api/service/trust-chains.ts index 55d79d7ba5..b8d2cf567f 100644 --- a/api-gateway/src/api/service/trust-chains.ts +++ b/api-gateway/src/api/service/trust-chains.ts @@ -1,62 +1,187 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { Users } from '../../helpers/users.js'; -import { IAuthUser, Logger } from '@guardian/common'; -import { Controller, Get, HttpCode, HttpStatus, Req, Response } from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { UserRole } from '@guardian/interfaces'; -import { ApiTags } from '@nestjs/swagger'; -import { UseCache } from '../../helpers/decorators/cache.js'; +import { IAuthUser } from '@guardian/common'; +import { Controller, Get, HttpCode, HttpStatus, Param, Query, Response } from '@nestjs/common'; +import { Permissions } from '@guardian/interfaces'; +import { ApiTags, ApiOperation, ApiOkResponse, ApiInternalServerErrorResponse, ApiExtraModels, ApiParam, ApiQuery } from '@nestjs/swagger'; +import { Guardians, Users, UseCache, ONLY_SR, InternalException } from '#helpers'; +import { Auth } from '#auth'; +import { Examples, InternalServerErrorDTO, VpDocumentDTO, pageHeader } from '#middlewares'; @Controller('trust-chains') @ApiTags('trust-chains') export class TrustChainsApi { + /** + * Get VP Document + */ @Get('/') + @Auth( + Permissions.AUDIT_TRUST_CHAIN_READ, + // UserRole.AUDITOR, + ) + @ApiOperation({ + summary: 'Returns a list of all VP documents.', + description: 'Returns a list of all VP documents.' + ONLY_SR, + }) + @ApiQuery({ + name: 'pageIndex', + type: Number, + description: 'The number of pages to skip before starting to collect the result set', + required: false, + example: 0 + }) + @ApiQuery({ + name: 'pageSize', + type: Number, + description: 'The numbers of items to return', + required: false, + example: 20 + }) + @ApiQuery({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: false, + example: Examples.DB_ID + }) + @ApiQuery({ + name: 'policyOwner', + type: String, + description: 'Policy Owner', + required: false, + example: Examples.DID + }) + @ApiOkResponse({ + description: 'Successful operation.', + isArray: true, + headers: pageHeader, + type: VpDocumentDTO + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(VpDocumentDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async getTrustChains(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.AUDITOR)(req.user); + async getTrustChains( + @Response() res: any, + @Query('pageIndex') pageIndex?: number, + @Query('pageSize') pageSize?: number, + @Query('policyId') policyId?: string, + @Query('policyOwner') policyOwner?: string + ): Promise { try { const guardians = new Guardians(); - let pageIndex: any; - let pageSize: any; let filters: any; - if (req.query) { - if (req.query.pageIndex && req.query.pageSize) { - pageIndex = req.query.pageIndex; - pageSize = req.query.pageSize; - } - if (req.query.policyId) { - filters = { - policyId: req.query.policyId - } - } else if (req.query.policyOwner) { - filters = { - policyOwner: req.query.policyOwner - } - } + if (policyId) { + filters = { policyId } + } else if (policyOwner) { + filters = { policyOwner } } - const { items, count } = await guardians.getVpDocuments({ - filters, - pageIndex, - pageSize - }); - return res.setHeader('X-Total-Count', count).json(items); + const { items, count } = await guardians.getVpDocuments({ filters, pageIndex, pageSize }); + return res.header('X-Total-Count', count).send(items); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } /** - * @param req + * Get TrustChain */ @Get('/:hash') - @HttpCode(HttpStatus.OK) + @Auth( + Permissions.AUDIT_TRUST_CHAIN_READ, + // UserRole.AUDITOR, + ) + @ApiOperation({ + summary: 'Builds and returns a trustchain, from the VP to the root VC document.', + description: 'Builds and returns a trustchain, from the VP to the root VC document.' + ONLY_SR, + }) + @ApiParam({ + name: 'hash', + type: String, + description: 'Hash', + required: true, + example: 'hash' + }) + @ApiOkResponse({ + description: 'Successful operation.', + schema: { + type: 'object', + properties: { + chain: { + type: 'array', + items: { + type: 'object', + properties: { + id: { + type: 'string' + }, + type: { + type: 'string' + }, + tag: { + type: 'string' + }, + label: { + type: 'string' + }, + schema: { + type: 'string' + }, + owner: { + type: 'string' + }, + document: { + type: 'object' + }, + }, + required: [ + 'id', + 'type', + 'tag', + 'label', + 'schema', + 'owner', + 'document' + ], + } + }, + userMap: { + type: 'array', + items: { + type: 'object', + properties: { + did: { + type: 'string' + }, + username: { + type: 'string' + }, + }, + required: [ + 'did', + 'username' + ], + } + } + }, + required: [ + 'chain', + 'userMap' + ], + }, + }) + @ApiInternalServerErrorResponse({ + description: 'Internal server error.', + type: InternalServerErrorDTO + }) + @ApiExtraModels(InternalServerErrorDTO) @UseCache() - async getTrustChainByHash(@Req() req): Promise { - await checkPermission(UserRole.AUDITOR)(req.user); + @HttpCode(HttpStatus.OK) + async getTrustChainByHash( + @Param('hash') hash: string, + ): Promise { try { const guardians = new Guardians(); - const hash = req.params.hash; const chain = await guardians.getChain(hash); const DIDs = chain.map((item) => { if (item.type === 'VC' && item.document) { @@ -80,8 +205,7 @@ export class TrustChainsApi { return { chain, userMap }; } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error + await InternalException(error); } } } diff --git a/api-gateway/src/api/service/websockets.ts b/api-gateway/src/api/service/websockets.ts index 25be7876b7..f70da811fa 100644 --- a/api-gateway/src/api/service/websockets.ts +++ b/api-gateway/src/api/service/websockets.ts @@ -1,12 +1,10 @@ import WebSocket, { WebSocketServer } from 'ws' - import { IncomingMessage, Server } from 'http'; -import { Users } from '../../helpers/users.js'; import { ExternalProviders, GenerateUUIDv4, MessageAPI, NotifyAPI, UserRole } from '@guardian/interfaces'; -import { generateNumberFromString, Logger, MeecoApprovedSubmission, MessageResponse, NatsService, NotificationHelper, Singleton } from '@guardian/common'; +import { generateNumberFromString, IAuthUser, Logger, MeecoApprovedSubmission, MessageResponse, NatsService, NotificationHelper, Singleton } from '@guardian/common'; import { NatsConnection } from 'nats'; -import { Injectable } from '@nestjs/common'; -import { MeecoAuth } from '../../helpers/meeco.js'; +// import { Injectable } from '@nestjs/common'; +import { MeecoAuth, Users } from '#helpers'; import { Mutex } from 'async-mutex'; /** @@ -38,40 +36,56 @@ export class WebSocketsServiceChannel extends NatsService { /** * WebSocket service class */ -@Injectable() +// @Injectable() +@Singleton export class WebSocketsService { /** * Channel * @private */ - private readonly channel: WebSocketsServiceChannel; + private channel: WebSocketsServiceChannel; + /** + * Server + * @private + */ + private server: Server /** * WebSocket server * @private */ - private readonly wss: WebSocketServer; - - private readonly clients = new Map(); + private wss: WebSocketServer; /** * Get statuses mutex + * @private */ private readonly getStatusesMutex = new Mutex(); - /** * Get statuses clients + * @private */ private readonly getStatusesClients: Set = new Set(); - /** * Notification reading set + * @private */ private readonly notificationReadingMap: Set = new Set(); + /** + * Clients + * @private + */ + private readonly clients = new Map(); - constructor(private readonly server: Server, cn: NatsConnection) { + /** + * Set connection + * @param cn + */ + public setConnection(server: Server, cn: NatsConnection): WebSocketsService { + this.server = server; this.wss = new WebSocketServer({ server: this.server }); this.channel = new WebSocketsServiceChannel(); this.channel.setConnection(cn); + return this; } /** @@ -83,6 +97,42 @@ export class WebSocketsService { await this.channel.init(); } + /** + * Update permissions + * @param user + */ + public updatePermissions(users: IAuthUser | IAuthUser[]): void { + if(!users) { + return; + } + const usersMap = new Map(); + if (Array.isArray(users)) { + for (const user of users) { + usersMap.set(user.id, { + username: user.username, + did: user.did, + permissions: user.permissions, + permissionsGroup: user.permissionsGroup + }) + } + } else { + usersMap.set(users.id, { + username: users.username, + did: users.did, + permissions: users.permissions, + permissionsGroup: users.permissionsGroup + }) + } + this.wss.clients.forEach((client: any) => { + if (usersMap.has(client.user?.id)) { + this.send(client, { + type: 'UPDATE_PERMISSIONS', + data: usersMap.get(client.user?.id) + }); + } + }); + } + /** * Update notification message * @param notification Notification @@ -174,7 +224,7 @@ export class WebSocketsService { MessageAPI.SEND_STATUS, // tslint:disable-next-line:no-shadowed-variable (msg) => { - const {name, state} = msg; + const { name, state } = msg; if (!statuses[name]) { statuses[name] = []; @@ -276,9 +326,9 @@ export class WebSocketsService { Object.assign(msg, { user: user ? { - username: user.username, - did: user.did, - } + username: user.username, + did: user.did, + } : null, }); if (this.checkUserByName(client, msg)) { @@ -391,15 +441,14 @@ export class WebSocketsService { const meecoUser = MeecoAuth.extractUserFromApprovedMeecoToken(meecoSubmissionApproveResp) // The username structure is necessary to avoid collisions - meeco doest not provide unique username const userProvider = { - role: data.role || UserRole.STANDARD_REGISTRY as UserRole, - username: `${meecoUser.firstName}${meecoUser.familyName}${ - generateNumberFromString(meecoUser.id) - }`.toLowerCase().replace(/\s+/g, ''), + role: data.role || UserRole.STANDARD_REGISTRY as UserRole, + username: `${meecoUser.firstName}${meecoUser.familyName}${generateNumberFromString(meecoUser.id) + }`.toLowerCase().replace(/\s+/g, ''), providerId: meecoUser.id, provider: ExternalProviders.MEECO, }; const guardianData = await new Users().generateNewUserTokenBasedOnExternalUserProvider( - userProvider + userProvider ); ws.send(JSON.stringify({ diff --git a/api-gateway/src/api/service/wizard.ts b/api-gateway/src/api/service/wizard.ts index d8bfc6128e..3de6b7e1ab 100644 --- a/api-gateway/src/api/service/wizard.ts +++ b/api-gateway/src/api/service/wizard.ts @@ -1,328 +1,87 @@ -import { Guardians } from '../../helpers/guardians.js'; -import { Logger, RunFunctionAsync, } from '@guardian/common'; -import { TaskManager } from '../../helpers/task-manager.js'; -import { ServiceError } from '../../helpers/service-requests-base.js'; -import { Controller, HttpCode, HttpStatus, Post, Req, Response } from '@nestjs/common'; -import { checkPermission } from '../../auth/authorization-helper.js'; -import { TaskAction, UserRole } from '@guardian/interfaces'; -import { ApiBody, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, getSchemaPath } from '@nestjs/swagger'; -import { InternalServerErrorDTO } from '../../middlewares/validation/schemas/errors.js'; +import { Guardians, TaskManager, ServiceError, ONLY_SR, InternalException, EntityOwner } from '#helpers'; +import { IAuthUser, Logger, RunFunctionAsync, } from '@guardian/common'; +import { Body, Controller, HttpCode, HttpStatus, Param, Post } from '@nestjs/common'; +import { Permissions, TaskAction } from '@guardian/interfaces'; +import { ApiBody, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, ApiParam, ApiExtraModels } from '@nestjs/swagger'; +import { Examples, InternalServerErrorDTO, TaskDTO, WizardConfigAsyncDTO, WizardConfigDTO, WizardPreviewDTO, WizardResultDTO } from '#middlewares'; +import { AuthUser, Auth } from '#auth'; @Controller('wizard') @ApiTags('wizard') export class WizardApi { + /** + * Creates a new policy + */ + @Post('/policy') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new policy.', - description: 'Creates a new policy by wizard. Only users with the Standard Registry role are allowed to make the request.', + description: 'Creates a new policy by wizard.' + ONLY_SR, }) @ApiBody({ - schema: { - 'type': 'object', - 'required': [ - 'policy', - 'roles', - 'schemas', - 'trustChain' - ], - 'properties': { - 'roles': { - 'type': 'array', - 'items': { - 'type': 'string' - } - }, - 'policy': { - 'type': 'object', - 'properties': { - 'name': { - 'type': 'string' - }, - 'description': { - 'type': 'string' - }, - 'topicDescription': { - 'type': 'string' - }, - 'policyTag': { - 'type': 'string' - } - } - }, - 'schemas': { - 'type': 'array', - 'items': { - 'type': 'object', - 'properties': { - 'name': { - 'type': 'string' - }, - 'iri': { - 'type': 'string' - }, - 'isApproveEnable': { - 'type': 'boolean' - }, - 'isMintSchema': { - 'type': 'boolean' - }, - 'mintOptions': { - 'type': 'object', - 'properties': { - 'tokenId': { - 'type': 'string' - }, - 'rule': { - 'type': 'string' - } - } - }, - 'dependencySchemaIri': { - 'type': 'string' - }, - 'relationshipsSchemaIri': { - 'type': 'string' - }, - 'initialRolesFor': { - 'type': 'array', - 'items': { - 'type': 'string' - } - }, - 'rolesConfig': { - 'type': 'array', - 'items': { - 'type': 'object', - 'properties': { - 'role': { - 'type': 'string' - }, - 'isApprover': { - 'type': 'boolean' - }, - 'isCreator': { - 'type': 'boolean' - }, - 'gridColumns': { - 'type': 'array', - 'items': { - 'type': 'object', - 'properties': { - 'field': { - 'type': 'string' - }, - 'title': { - 'type': 'string' - } - } - } - } - } - } - } - } - } - }, - 'trustChain': { - 'type': 'array', - 'items': { - 'type': 'object', - 'properties': { - 'role': { - 'type': 'string' - }, - 'mintSchemaIri': { - 'type': 'string' - }, - 'viewOnlyOwnDocuments': { - 'type': 'boolean' - } - } - } - } - } - } + description: 'Object that contains wizard configuration.', + type: WizardConfigDTO, + required: true }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'boolean' - } + type: WizardResultDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/policy') + @ApiExtraModels(WizardConfigDTO, WizardResultDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.CREATED) - async setPolicy(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async setPolicy( + @AuthUser() user: IAuthUser, + @Body() wizardConfig: WizardConfigDTO + ): Promise { try { - const wizardConfig = req.body; - const user = req.user; + const owner = new EntityOwner(user); const guardians = new Guardians(); - return res.status(201).json( - await guardians.wizardPolicyCreate(wizardConfig, user.did) - ); + return await guardians.wizardPolicyCreate(wizardConfig, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } + /** + * Creates a new policy + */ + @Post('/push/policy') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Creates a new policy.', - description: 'Creates a new policy by wizard. Only users with the Standard Registry role are allowed to make the request.', + description: 'Creates a new policy by wizard.' + ONLY_SR, }) @ApiBody({ - schema: { - type: 'object', - properties: { - saveState: { - type: 'boolean', - }, - wizardConfig: { - type: 'object', - required: ['policy', 'roles', 'schemas', 'trustChain'], - properties: { - roles: { - type: 'array', - items: { - type: 'string', - }, - }, - policy: { - type: 'object', - properties: { - name: { - type: 'string', - }, - description: { - type: 'string', - }, - topicDescription: { - type: 'string', - }, - policyTag: { - type: 'string', - }, - }, - }, - schemas: { - type: 'array', - items: { - type: 'object', - properties: { - name: { - type: 'string', - }, - iri: { - type: 'string', - }, - isApproveEnable: { - type: 'boolean', - }, - isMintSchema: { - type: 'boolean', - }, - mintOptions: { - type: 'object', - properties: { - tokenId: { - type: 'string', - }, - rule: { - type: 'string', - }, - }, - }, - dependencySchemaIri: { - type: 'string', - }, - relationshipsSchemaIri: { - type: 'string', - }, - initialRolesFor: { - type: 'array', - items: { - type: 'string', - }, - }, - rolesConfig: { - type: 'array', - items: { - type: 'object', - properties: { - role: { - type: 'string', - }, - isApprover: { - type: 'boolean', - }, - isCreator: { - type: 'boolean', - }, - gridColumns: { - type: 'array', - items: { - type: 'object', - properties: { - field: { - type: 'string', - }, - title: { - type: 'string', - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - trustChain: { - type: 'array', - items: { - type: 'object', - properties: { - role: { - type: 'string', - }, - mintSchemaIri: { - type: 'string', - }, - viewOnlyOwnDocuments: { - type: 'boolean', - }, - }, - }, - }, - }, - }, - }, - }, + description: 'Object that contains wizard configuration.', + type: WizardConfigAsyncDTO, + required: true }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'boolean' - } + type: TaskDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/push/policy') + @ApiExtraModels(WizardConfigAsyncDTO, TaskDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.ACCEPTED) - async setPolicyAsync(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); - const { wizardConfig, saveState } = req.body; - const user = req.user; + async setPolicyAsync( + @AuthUser() user: IAuthUser, + @Body() body: WizardConfigAsyncDTO + ): Promise { + const { wizardConfig, saveState } = body; + const owner = new EntityOwner(user); const taskManager = new TaskManager(); const task = taskManager.start(TaskAction.WIZARD_CREATE_POLICY, user.id); RunFunctionAsync( @@ -330,7 +89,7 @@ export class WizardApi { const guardians = new Guardians(); await guardians.wizardPolicyCreateAsyncNew( wizardConfig, - user.did, + owner, saveState, task ); @@ -343,171 +102,54 @@ export class WizardApi { }); } ); - return res.status(202).send(task); + return task; } + /** + * Get config + */ + @Post('/:policyId/config') + @Auth( + Permissions.POLICIES_POLICY_CREATE, + // UserRole.STANDARD_REGISTRY, + ) @ApiOperation({ summary: 'Get policy config.', - description: 'Get policy config by wizard. Only users with the Standard Registry role are allowed to make the request.', + description: 'Get policy config by wizard.' + ONLY_SR, + }) + @ApiParam({ + name: 'policyId', + type: String, + description: 'Policy Id', + required: true, + example: Examples.DB_ID }) @ApiBody({ - schema: { - 'type': 'object', - 'required': [ - 'policy', - 'roles', - 'schemas', - 'trustChain' - ], - 'properties': { - 'roles': { - 'type': 'array', - 'items': { - 'type': 'string' - } - }, - 'policy': { - 'type': 'object', - 'properties': { - 'name': { - 'type': 'string' - }, - 'description': { - 'type': 'string' - }, - 'topicDescription': { - 'type': 'string' - }, - 'policyTag': { - 'type': 'string' - } - } - }, - 'schemas': { - 'type': 'array', - 'items': { - 'type': 'object', - 'properties': { - 'name': { - 'type': 'string' - }, - 'iri': { - 'type': 'string' - }, - 'isApproveEnable': { - 'type': 'boolean' - }, - 'isMintSchema': { - 'type': 'boolean' - }, - 'mintOptions': { - 'type': 'object', - 'properties': { - 'tokenId': { - 'type': 'string' - }, - 'rule': { - 'type': 'string' - } - } - }, - 'dependencySchemaIri': { - 'type': 'string' - }, - 'relationshipsSchemaIri': { - 'type': 'string' - }, - 'initialRolesFor': { - 'type': 'array', - 'items': { - 'type': 'string' - } - }, - 'rolesConfig': { - 'type': 'array', - 'items': { - 'type': 'object', - 'properties': { - 'role': { - 'type': 'string' - }, - 'isApprover': { - 'type': 'boolean' - }, - 'isCreator': { - 'type': 'boolean' - }, - 'gridColumns': { - 'type': 'array', - 'items': { - 'type': 'object', - 'properties': { - 'field': { - 'type': 'string' - }, - 'title': { - 'type': 'string' - } - } - } - } - } - } - } - } - } - }, - 'trustChain': { - 'type': 'array', - 'items': { - 'type': 'object', - 'properties': { - 'role': { - 'type': 'string' - }, - 'mintSchemaIri': { - 'type': 'string' - }, - 'viewOnlyOwnDocuments': { - 'type': 'boolean' - } - } - } - } - } - } + description: 'Object that contains wizard configuration.', + type: WizardConfigDTO, + required: true }) @ApiOkResponse({ description: 'Successful operation.', - schema: { - type: 'boolean' - } + type: WizardPreviewDTO }) @ApiInternalServerErrorResponse({ description: 'Internal server error.', - schema: { - $ref: getSchemaPath(InternalServerErrorDTO) - } + type: InternalServerErrorDTO, }) - @Post('/:policyId/config') + @ApiExtraModels(WizardConfigDTO, WizardPreviewDTO, InternalServerErrorDTO) @HttpCode(HttpStatus.OK) - async setPolicyConfig(@Req() req, @Response() res): Promise { - await checkPermission(UserRole.STANDARD_REGISTRY)(req.user); + async setPolicyConfig( + @AuthUser() user: IAuthUser, + @Param('policyId') policyId: string, + @Body() wizardConfig: WizardConfigDTO + ): Promise { try { - const wizardConfig = req.body; - const user = req.user; - const {policyId} = req.params; const guardians = new Guardians(); - return res.json( - await guardians.wizardGetPolicyConfig( - policyId, - wizardConfig, - user.did - ) - ); + const owner = new EntityOwner(user); + return await guardians.wizardGetPolicyConfig(policyId, wizardConfig, owner); } catch (error) { - new Logger().error(error, ['API_GATEWAY']); - throw error; + await InternalException(error); } } } diff --git a/api-gateway/src/app.module.ts b/api-gateway/src/app.module.ts index c453e66604..dc4f179b85 100644 --- a/api-gateway/src/app.module.ts +++ b/api-gateway/src/app.module.ts @@ -13,7 +13,6 @@ import { MetricsApi } from './api/service/metrics.js'; import { ModulesApi } from './api/service/module.js'; import { ToolsApi } from './api/service/tool.js'; import { ProfileApi } from './api/service/profile.js'; -import { authorizationHelper } from './auth/authorization-helper.js'; import { PolicyApi } from './api/service/policy.js'; import { SchemaApi, SingleSchemaApi } from './api/service/schema.js'; import { SettingsApi } from './api/service/settings.js'; @@ -23,7 +22,6 @@ import { TokensApi } from './api/service/tokens.js'; import { TrustChainsApi } from './api/service/trust-chains.js'; import { WizardApi } from './api/service/wizard.js'; import process from 'process'; -import express from 'express'; import hpp from 'hpp'; import { ThemesApi } from './api/service/themes.js'; import { BrandingApi } from './api/service/branding.js'; @@ -40,22 +38,10 @@ import { ProjectsAPI } from './api/service/project.js'; import { AISuggestionsAPI } from './api/service/ai-suggestions.js'; import { cacheProvider } from './helpers/cache-provider.js'; import { CacheService } from './helpers/cache-service.js'; +import { PermissionsApi } from './api/service/permissions.js'; -const JSON_REQUEST_LIMIT = process.env.JSON_REQUEST_LIMIT || '1mb'; -const RAW_REQUEST_LIMIT = process.env.RAW_REQUEST_LIMIT || '1gb'; - -// class LogClientSerializer implements Serializer { -// serialize(value: any, options?: Record): any { -// value.data = Buffer.from(JSON.stringify(value), 'utf-8') -// return value; -// } -// } -// -// class LogClientDeserializer implements Deserializer { -// deserialize(value: any, options?: Record): any { -// return JSON.parse(value.toString()) -// } -// } +// const JSON_REQUEST_LIMIT = process.env.JSON_REQUEST_LIMIT || '1mb'; +// const RAW_REQUEST_LIMIT = process.env.RAW_REQUEST_LIMIT || '1gb'; @Module({ imports: [ @@ -101,7 +87,8 @@ const RAW_REQUEST_LIMIT = process.env.RAW_REQUEST_LIMIT || '1gb'; NotificationsApi, ProjectsAPI, RecordApi, - AISuggestionsAPI + AISuggestionsAPI, + PermissionsApi ], providers: [ LoggerService, @@ -116,39 +103,14 @@ const RAW_REQUEST_LIMIT = process.env.RAW_REQUEST_LIMIT || '1gb'; }) export class AppModule { configure(consumer: MiddlewareConsumer) { - // consumer.apply(authorizationHelper).forRoutes(AccountApi); - consumer.apply(authorizationHelper).forRoutes(ProfileApi); - consumer.apply(authorizationHelper).forRoutes(PolicyApi); - consumer.apply(authorizationHelper).forRoutes(SettingsApi); - consumer.apply(authorizationHelper).forRoutes(SingleSchemaApi); - consumer.apply(authorizationHelper).forRoutes(SchemaApi); - consumer.apply(authorizationHelper).forRoutes(ArtifactApi); - consumer.apply(authorizationHelper).forRoutes(IpfsApi); - consumer.apply(authorizationHelper).forRoutes(LoggerApi); - consumer.apply(authorizationHelper).forRoutes(AnalyticsApi); - consumer.apply(authorizationHelper).forRoutes(ContractsApi); - consumer.apply(authorizationHelper).forRoutes(ModulesApi); - consumer.apply(authorizationHelper).forRoutes(ToolsApi); - consumer.apply(authorizationHelper).forRoutes(TagsApi); - consumer.apply(authorizationHelper).forRoutes(ThemesApi); - consumer.apply(authorizationHelper).forRoutes(TokensApi); - consumer.apply(authorizationHelper).forRoutes(TrustChainsApi); - consumer.apply(authorizationHelper).forRoutes(WizardApi); - // consumer.apply(authorizationHelper).forRoutes(BrandingApi); - consumer.apply(authorizationHelper).forRoutes(SuggestionsApi); - consumer.apply(authorizationHelper).forRoutes(NotificationsApi); - consumer.apply(authorizationHelper).forRoutes(TaskApi); - consumer.apply(authorizationHelper).forRoutes(RecordApi); - consumer.apply(authorizationHelper).forRoutes(AISuggestionsAPI); - - consumer.apply(express.json({ - limit: JSON_REQUEST_LIMIT - })).forRoutes('*'); - consumer.apply(express.raw({ - inflate: true, - limit: RAW_REQUEST_LIMIT, - type: 'binary/octet-stream' - })).forRoutes('*'); + // consumer.apply(express.json({ + // limit: JSON_REQUEST_LIMIT + // })).forRoutes('*'); + // consumer.apply(express.raw({ + // inflate: true, + // limit: RAW_REQUEST_LIMIT, + // type: 'binary/octet-stream' + // })).forRoutes('*'); consumer.apply(hpp()).forRoutes('*'); } } diff --git a/api-gateway/src/app.ts b/api-gateway/src/app.ts index b2a861e06f..8bc8e1a711 100644 --- a/api-gateway/src/app.ts +++ b/api-gateway/src/app.ts @@ -10,29 +10,25 @@ import { AppModule } from './app.module.js'; import { NestFactory } from '@nestjs/core'; import { MicroserviceOptions, Transport } from '@nestjs/microservices'; import process from 'process'; -import { HttpStatus, ValidationPipe } from '@nestjs/common'; -import { json } from 'express'; +import { HttpStatus, ValidationPipe, VersioningType } from '@nestjs/common'; import { SwaggerModule } from '@nestjs/swagger'; import { SwaggerConfig } from './helpers/swagger-config.js'; -import { SwaggerModels, SwaggerPaths } from './old-descriptions.js'; import { MeecoAuth } from './helpers/meeco.js'; -import * as extraModels from './middlewares/validation/schemas/index.js' +import * as extraModels from './middlewares/index.js' import { ProjectService } from './helpers/projects.js'; import { AISuggestions } from './helpers/ai-suggestions.js'; +import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'; +import fastifyFormbody from '@fastify/formbody' +import fastifyMultipart from '@fastify/multipart'; const PORT = process.env.PORT || 3002; -// const restResponseTimeHistogram = new client.Histogram({ -// name: 'api_gateway_rest_response_time_duration_seconds', -// help: 'api-gateway a histogram metric', -// labelNames: ['method', 'route', 'statusCode'], -// buckets: [0.1, 5, 15, 50, 100, 500], -// }); +const BODY_LIMIT = 1024 * 1024 * 1024 Promise.all([ - NestFactory.create(AppModule, { + NestFactory.create(AppModule, new FastifyAdapter({ ignoreTrailingSlash: true }), { rawBody: true, - bodyParser: false + bodyParser: false, }), MessageBrokerChannel.connect('API_GATEWAY'), ]).then(async ([app, cn]) => { @@ -46,11 +42,19 @@ Promise.all([ ] }, }); + app.enableVersioning({ + type: VersioningType.HEADER, + header: 'Api-Version', + }); app.useGlobalPipes(new ValidationPipe({ errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY })); - app.use(json({ limit: '10mb' })); + await app.register(fastifyFormbody); + await app.register(fastifyMultipart); + + app.useBodyParser('json', { bodyLimit: BODY_LIMIT }); + app.useBodyParser('binary/octet-stream', { bodyLimit: BODY_LIMIT }); new Logger().setConnection(cn); await new Guardians().setConnection(cn).init(); @@ -65,10 +69,10 @@ Promise.all([ await new MeecoAuth().registerListeners(); const server = app.getHttpServer(); - const wsService = new WebSocketsService(server, cn); - wsService.init(); + const wsService = new WebSocketsService(); + wsService.setConnection(server, cn).init(); - new TaskManager().setDependecies(wsService, cn); + new TaskManager().setDependencies(wsService, cn); const document = SwaggerModule.createDocument(app, SwaggerConfig, { extraModels: Object.values(extraModels).filter((constructor: new (...args: any[]) => any) => { @@ -79,17 +83,17 @@ Promise.all([ } catch { return false; } - }) + }) as any }); - Object.assign(document.paths, SwaggerPaths) - Object.assign(document.components.schemas, SwaggerModels.schemas); + // Object.assign(document.paths, SwaggerPaths) + // Object.assign(document.components.schemas, SwaggerModels.schemas); SwaggerModule.setup('api-docs', app, document); const maxPayload = parseInt(process.env.MQ_MAX_PAYLOAD, 10); if (Number.isInteger(maxPayload)) { new LargePayloadContainer().runServer(); } - app.listen(PORT, async () => { + app.listen(PORT, '0.0.0.0', async () => { new Logger().info(`Started on ${PORT}`, ['API_GATEWAY']); }); } catch (error) { diff --git a/api-gateway/src/auth/auth.decorator.ts b/api-gateway/src/auth/auth.decorator.ts index 82acad2c4c..d7ff057bcb 100644 --- a/api-gateway/src/auth/auth.decorator.ts +++ b/api-gateway/src/auth/auth.decorator.ts @@ -1,17 +1,18 @@ import { applyDecorators, SetMetadata, UseGuards } from '@nestjs/common'; import { AuthGuard } from '../auth/auth-guard.js'; -import { ApiBearerAuth, ApiUnauthorizedResponse } from '@nestjs/swagger'; -import { UserRole } from '@guardian/interfaces'; +import { ApiBearerAuth, ApiForbiddenResponse, ApiUnauthorizedResponse } from '@nestjs/swagger'; +import { Permissions } from '@guardian/interfaces'; import { RolesGuard } from '../auth/roles-guard.js'; -export function Auth(...roles: UserRole[]) { +export function Auth(...permissions: Permissions[]) { return applyDecorators( - SetMetadata('roles', roles), + SetMetadata('permissions', permissions), UseGuards( AuthGuard, RolesGuard ), ApiBearerAuth(), - ApiUnauthorizedResponse({description: 'Unauthorized'}), + ApiUnauthorizedResponse({ description: 'Unauthorized.' }), + ApiForbiddenResponse({ description: 'Forbidden.' }) ) } diff --git a/api-gateway/src/auth/authorization-helper.ts b/api-gateway/src/auth/authorization-helper.ts index 301a4d830a..f61b8a2dde 100644 --- a/api-gateway/src/auth/authorization-helper.ts +++ b/api-gateway/src/auth/authorization-helper.ts @@ -48,7 +48,7 @@ export async function authorizationHelper(req: AuthenticatedRequest, res: Respon new Logger().warn(error.message, ['API_GATEWAY']); } } - res.sendStatus(401); + throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED) } /** @@ -83,9 +83,9 @@ export function permissionHelper(...roles: string[]) { return; } } - res.sendStatus(403); + throw new HttpException('Forbidden', HttpStatus.FORBIDDEN) } else { - res.sendStatus(401); + throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); } } } diff --git a/api-gateway/src/auth/index.ts b/api-gateway/src/auth/index.ts new file mode 100644 index 0000000000..ba919eb61c --- /dev/null +++ b/api-gateway/src/auth/index.ts @@ -0,0 +1,4 @@ +export * from './auth.decorator.js'; +export * from './authorization-helper.js'; +export * from './auth-guard.js'; +export * from './roles-guard.js'; \ No newline at end of file diff --git a/api-gateway/src/auth/roles-guard.ts b/api-gateway/src/auth/roles-guard.ts index f17e005286..5ebaf1f15f 100644 --- a/api-gateway/src/auth/roles-guard.ts +++ b/api-gateway/src/auth/roles-guard.ts @@ -1,3 +1,5 @@ +import { IAuthUser } from '@guardian/common'; +import { Permissions } from '@guardian/interfaces'; import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; @@ -8,11 +10,20 @@ export class RolesGuard implements CanActivate { } canActivate(context: ExecutionContext): boolean { - const roles = this.reflector.get('roles', context.getHandler()); - - const request = context.switchToHttp().getRequest(); - const user = request.user; - - return roles.indexOf(user.role) !== -1; + const permissions: Permissions[] = this.reflector.get('permissions', context.getHandler()); + if (Array.isArray(permissions) && permissions.length) { + const request = context.switchToHttp().getRequest(); + const user: IAuthUser = request.user; + if (user && user.permissions) { + for (const permission of permissions) { + if (user.permissions.indexOf(permission) !== -1) { + return true; + } + } + } + return false; + } else { + return true; + } } } diff --git a/api-gateway/src/helpers/decorators/cache.ts b/api-gateway/src/helpers/decorators/cache.ts index 33d8926ac8..91817fd834 100644 --- a/api-gateway/src/helpers/decorators/cache.ts +++ b/api-gateway/src/helpers/decorators/cache.ts @@ -7,12 +7,12 @@ import { CacheInterceptor } from '../../helpers/interceptors/cache.js'; import { CACHE, META_DATA } from '../../constants/index.js'; export function UseCache( - { ttl = CACHE.DEFAULT_TTL, isExpress = false, interceptors = [] }: - { ttl?: number, isExpress?: boolean, interceptors?: any[] } = {}) { + { ttl = CACHE.DEFAULT_TTL, isExpress = false, interceptors = [] }: + { ttl?: number, isExpress?: boolean, interceptors?: any[] } = {}) { - return applyDecorators( - SetMetadata(META_DATA.EXPRESS, isExpress), - SetMetadata(META_DATA.TTL, ttl), - UseInterceptors(...[...interceptors, CacheInterceptor]), - ); + return applyDecorators( + SetMetadata(META_DATA.EXPRESS, isExpress), + SetMetadata(META_DATA.TTL, ttl), + UseInterceptors(...[...interceptors, CacheInterceptor]), + ); } diff --git a/api-gateway/src/helpers/decorators/file.ts b/api-gateway/src/helpers/decorators/file.ts new file mode 100644 index 0000000000..f4fa397fd1 --- /dev/null +++ b/api-gateway/src/helpers/decorators/file.ts @@ -0,0 +1,11 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; + +//types and interfaces +import { FastifyRequest, MultipartFile } from '../interceptors/types/index.js'; + +export const UploadedFiles = createParamDecorator( + async (_data: unknown, ctx: ExecutionContext): Promise => { + const req = ctx.switchToHttp().getRequest() as FastifyRequest; + return req.storedFiles; + }, +); \ No newline at end of file diff --git a/api-gateway/src/helpers/decorators/index.ts b/api-gateway/src/helpers/decorators/index.ts new file mode 100644 index 0000000000..ec8a143da9 --- /dev/null +++ b/api-gateway/src/helpers/decorators/index.ts @@ -0,0 +1,6 @@ +export * from './cache.js'; +export * from './inject.js'; +export * from './match.validator.js'; +export * from './singleton.js'; +export * from './user.js'; +export * from './file.js'; \ No newline at end of file diff --git a/api-gateway/src/helpers/entity-owner.ts b/api-gateway/src/helpers/entity-owner.ts new file mode 100644 index 0000000000..0eb22b0fa3 --- /dev/null +++ b/api-gateway/src/helpers/entity-owner.ts @@ -0,0 +1,12 @@ +import { IAuthUser } from '@guardian/common'; +import { EntityOwner as Owner } from '@guardian/interfaces'; +import { HttpException, HttpStatus } from '@nestjs/common'; + +export class EntityOwner extends Owner { + constructor(user?: IAuthUser) { + if (user && !user.did) { + throw new HttpException('User is not registered.', HttpStatus.UNPROCESSABLE_ENTITY); + } + super(user); + } +} \ No newline at end of file diff --git a/api-gateway/src/helpers/guardians.ts b/api-gateway/src/helpers/guardians.ts index ac884afebe..c45a19dc77 100644 --- a/api-gateway/src/helpers/guardians.ts +++ b/api-gateway/src/helpers/guardians.ts @@ -1,7 +1,34 @@ import { Singleton } from '../helpers/decorators/singleton.js'; -import { ApplicationStates, CommonSettings, ContractAPI, ContractType, GenerateUUIDv4, IArtifact, IChainItem, IContract, IDidObject, IRetirePool, IRetireRequest, ISchema, IToken, ITokenInfo, IUser, IVCDocument, IVPDocument, MessageAPI, PolicyToolMetadata, RetireTokenPool, RetireTokenRequest, SchemaNode, SuggestionsOrderPriority } from '@guardian/interfaces'; +import { + ApplicationStates, + AssignedEntityType, + CommonSettings, + ContractAPI, + ContractType, + GenerateUUIDv4, + IArtifact, + IChainItem, + IContract, + IDidObject, + IOwner, + IRetirePool, + IRetireRequest, + ISchema, + IToken, + ITokenInfo, + IUser, + IVCDocument, + IVPDocument, + MessageAPI, + PolicyToolMetadata, + RetireTokenPool, + RetireTokenRequest, + SchemaNode, + SuggestionsOrderPriority +} from '@guardian/interfaces'; import { IAuthUser, NatsService } from '@guardian/common'; import { NewTask } from './task-manager.js'; +import { ModuleDTO, TagDTO, ThemeDTO, TokenDTO, ToolDTO } from '#middlewares'; /** * Filters type @@ -106,8 +133,8 @@ export class Guardians extends NatsService { * * @returns {IToken[]} - tokens */ - public async getTokens(params?: IFilter): Promise { - return await this.sendMessage(MessageAPI.GET_TOKENS, params); + public async getTokens(filters: IFilter, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.GET_TOKENS, { filters, owner }); } /** @@ -120,11 +147,11 @@ export class Guardians extends NatsService { * @returns {ResponseAndCount} - tokens */ public async getTokensPage( - did?: string, + owner?: IOwner, pageIndex?: number, pageSize?: number ): Promise> { - return await this.sendMessage(MessageAPI.GET_TOKENS_PAGE, { did, pageIndex, pageSize }); + return await this.sendMessage(MessageAPI.GET_TOKENS_PAGE, { owner, pageIndex, pageSize }); } /** @@ -134,8 +161,8 @@ export class Guardians extends NatsService { * * @returns {IToken} - token */ - public async getTokenById(tokenId: string): Promise { - return await this.sendMessage(MessageAPI.GET_TOKEN, { tokenId }); + public async getTokenById(tokenId: string, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.GET_TOKEN, { tokenId, owner }); } /** @@ -156,8 +183,8 @@ export class Guardians extends NatsService { * * @returns {IToken[]} - all tokens */ - public async setToken(item: IToken | any): Promise { - return await this.sendMessage(MessageAPI.SET_TOKEN, item); + public async setToken(item: TokenDTO, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.SET_TOKEN, { item, owner }); } /** @@ -166,7 +193,7 @@ export class Guardians extends NatsService { * @param owner * @param task */ - public async setTokenAsync(token: IToken | any, owner: any, task: NewTask): Promise { + public async setTokenAsync(token: TokenDTO, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.SET_TOKEN_ASYNC, { token, owner, task }); } @@ -174,8 +201,8 @@ export class Guardians extends NatsService { * Update token * @param token */ - public async updateToken(token: IToken | any): Promise { - return await this.sendMessage(MessageAPI.UPDATE_TOKEN, { token }); + public async updateToken(token: TokenDTO, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.UPDATE_TOKEN, { token, owner }); } /** @@ -183,8 +210,8 @@ export class Guardians extends NatsService { * @param token * @param task */ - public async updateTokenAsync(token: IToken | any, task: NewTask): Promise { - return await this.sendMessage(MessageAPI.UPDATE_TOKEN_ASYNC, { token, task }); + public async updateTokenAsync(token: TokenDTO, owner: IOwner, task: NewTask): Promise { + return await this.sendMessage(MessageAPI.UPDATE_TOKEN_ASYNC, { token, owner, task }); } /** @@ -192,8 +219,8 @@ export class Guardians extends NatsService { * @param tokenId * @param task */ - public async deleteTokenAsync(tokenId: string, task: NewTask): Promise { - return await this.sendMessage(MessageAPI.DELETE_TOKEN_ASYNC, { tokenId, task }); + public async deleteTokenAsync(tokenId: string, owner: IOwner, task: NewTask): Promise { + return await this.sendMessage(MessageAPI.DELETE_TOKEN_ASYNC, { tokenId, owner, task }); } /** @@ -203,7 +230,7 @@ export class Guardians extends NatsService { * @param owner * @returns {Promise} */ - public async freezeToken(tokenId: string, username: string, owner: string): Promise { + public async freezeToken(tokenId: string, username: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.FREEZE_TOKEN, { tokenId, username, @@ -219,7 +246,7 @@ export class Guardians extends NatsService { * @param owner * @param task */ - public async freezeTokenAsync(tokenId: string, username: string, owner: string, task: NewTask): Promise { + public async freezeTokenAsync(tokenId: string, username: string, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.FREEZE_TOKEN_ASYNC, { tokenId, username, @@ -251,7 +278,7 @@ export class Guardians extends NatsService { * @param owner * @param task */ - public async unfreezeTokenAsync(tokenId: string, username: string, owner: string, task: NewTask): Promise { + public async unfreezeTokenAsync(tokenId: string, username: string, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.FREEZE_TOKEN_ASYNC, { tokenId, username, @@ -267,7 +294,7 @@ export class Guardians extends NatsService { * @param username * @param owner */ - public async grantKycToken(tokenId: string, username: string, owner: string): Promise { + public async grantKycToken(tokenId: string, username: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.KYC_TOKEN, { tokenId, username, @@ -283,7 +310,7 @@ export class Guardians extends NatsService { * @param owner * @param task */ - public async grantKycTokenAsync(tokenId: string, username: string, owner: string, task: NewTask): Promise { + public async grantKycTokenAsync(tokenId: string, username: string, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.KYC_TOKEN_ASYNC, { tokenId, username, @@ -299,7 +326,7 @@ export class Guardians extends NatsService { * @param username * @param owner */ - public async revokeKycToken(tokenId: string, username: string, owner: string): Promise { + public async revokeKycToken(tokenId: string, username: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.KYC_TOKEN, { tokenId, username, @@ -315,7 +342,7 @@ export class Guardians extends NatsService { * @param owner * @param task */ - public async revokeKycTokenAsync(tokenId: string, username: string, owner: string, task: NewTask): Promise { + public async revokeKycTokenAsync(tokenId: string, username: string, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.KYC_TOKEN_ASYNC, { tokenId, username, @@ -330,10 +357,10 @@ export class Guardians extends NatsService { * @param tokenId * @param did */ - public async associateToken(tokenId: string, did: string): Promise { + public async associateToken(tokenId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.ASSOCIATE_TOKEN, { tokenId, - did, + owner, associate: true, }); } @@ -344,10 +371,10 @@ export class Guardians extends NatsService { * @param did * @param task */ - public async associateTokenAsync(tokenId: string, did: string, task: NewTask): Promise { + public async associateTokenAsync(tokenId: string, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.ASSOCIATE_TOKEN_ASYNC, { tokenId, - did, + owner, associate: true, task, }); @@ -358,10 +385,10 @@ export class Guardians extends NatsService { * @param tokenId * @param did */ - public async dissociateToken(tokenId: string, did: string): Promise { + public async dissociateToken(tokenId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.ASSOCIATE_TOKEN, { tokenId, - did, + owner, associate: false, }); } @@ -372,10 +399,10 @@ export class Guardians extends NatsService { * @param did * @param task */ - public async dissociateTokenAsync(tokenId: string, did: string, task: NewTask): Promise { + public async dissociateTokenAsync(tokenId: string, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.ASSOCIATE_TOKEN_ASYNC, { tokenId, - did, + owner, associate: false, task, }); @@ -387,7 +414,7 @@ export class Guardians extends NatsService { * @param username * @param owner */ - public async getInfoToken(tokenId: string, username: string, owner: string): Promise { + public async getInfoToken(tokenId: string, username: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_INFO_TOKEN, { tokenId, username, @@ -401,11 +428,8 @@ export class Guardians extends NatsService { * @param did DID * @returns Serials */ - public async getTokenSerials(tokenId: string, did: string): Promise { - return await this.sendMessage(MessageAPI.GET_SERIALS, { - tokenId, - did - }); + public async getTokenSerials(tokenId: string, did: string): Promise { + return await this.sendMessage(MessageAPI.GET_SERIALS, { tokenId, did }); } /** @@ -501,8 +525,8 @@ export class Guardians extends NatsService { * * @returns {ISchema[]} - all schemas */ - public async getSchemasByOwner(options: any): Promise> { - return await this.sendMessage(MessageAPI.GET_SCHEMAS, options); + public async getSchemasByOwner(options: any, owner: IOwner): Promise> { + return await this.sendMessage(MessageAPI.GET_SCHEMAS, { options, owner }); } /** @@ -543,7 +567,7 @@ export class Guardians extends NatsService { * @param id Schema identifier * @returns Schemas */ - public async getSchemaParents(id: string, owner: string): Promise { + public async getSchemaParents(id: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_SCHEMA_PARENTS, { id, owner }); } @@ -553,7 +577,7 @@ export class Guardians extends NatsService { * @param owner Owner * @returns Schema tree */ - public async getSchemaTree(id: string, owner: string): Promise { + public async getSchemaTree(id: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_SCHEMA_TREE, { id, owner }); } @@ -566,7 +590,7 @@ export class Guardians extends NatsService { * * @returns {any[]} - Schema Document */ - public async importSchemasByMessages(messageIds: string[], owner: string, topicId: string): Promise { + public async importSchemasByMessages(messageIds: string[], owner: IOwner, topicId: string): Promise { return await this.sendMessage(MessageAPI.IMPORT_SCHEMAS_BY_MESSAGES, { messageIds, owner, topicId }); } @@ -578,7 +602,7 @@ export class Guardians extends NatsService { * @param {string} topicId * @param {NewTask} task */ - public async importSchemasByMessagesAsync(messageIds: string[], owner: string, topicId: string, task: NewTask): Promise { + public async importSchemasByMessagesAsync(messageIds: string[], owner: IOwner, topicId: string, task: NewTask): Promise { return await this.sendMessage(MessageAPI.IMPORT_SCHEMAS_BY_MESSAGES_ASYNC, { messageIds, owner, topicId, task }); } @@ -593,7 +617,7 @@ export class Guardians extends NatsService { */ public async importSchemasByFile( files: any, - owner: string, + owner: IOwner, topicId: string ): Promise<{ /** @@ -617,7 +641,7 @@ export class Guardians extends NatsService { */ public async importSchemasByFileAsync( files: any, - owner: string, + owner: IOwner, topicId: string, task: NewTask, ): Promise { @@ -663,8 +687,8 @@ export class Guardians extends NatsService { * * @returns {ISchema[]} - all schemas */ - public async createSchema(item: ISchema | any): Promise { - return await this.sendMessage(MessageAPI.CREATE_SCHEMA, item); + public async createSchema(item: ISchema | any, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.CREATE_SCHEMA, { item, owner }); } /** @@ -672,8 +696,8 @@ export class Guardians extends NatsService { * @param {ISchema} item - schema * @param {NewTask} task - task */ - public async createSchemaAsync(item: ISchema | any, task: NewTask): Promise { - return await this.sendMessage(MessageAPI.CREATE_SCHEMA_ASYNC, { item, task }); + public async createSchemaAsync(item: ISchema | any, owner: IOwner, task: NewTask): Promise { + return await this.sendMessage(MessageAPI.CREATE_SCHEMA_ASYNC, { item, owner, task }); } /** @@ -684,7 +708,13 @@ export class Guardians extends NatsService { * @param owner * @param task */ - public async copySchemaAsync(iri: string, topicId: string, name: string, owner: string, task: NewTask): Promise { + public async copySchemaAsync( + iri: string, + topicId: string, + name: string, + owner: IOwner, + task: NewTask + ): Promise { return await this.sendMessage(MessageAPI.COPY_SCHEMA_ASYNC, { iri, topicId, name, task, owner }); } @@ -695,8 +725,11 @@ export class Guardians extends NatsService { * * @returns {ISchema[]} - all schemas */ - public async updateSchema(item: ISchema | any): Promise { - return await this.sendMessage(MessageAPI.UPDATE_SCHEMA, item); + public async updateSchema( + item: ISchema | any, + owner: IOwner, + ): Promise { + return await this.sendMessage(MessageAPI.UPDATE_SCHEMA, { item, owner }); } /** @@ -706,7 +739,7 @@ export class Guardians extends NatsService { * * @returns {ISchema[]} - all schemas */ - public async deleteSchema(id: string, owner: string, needResult = false): Promise { + public async deleteSchema(id: string, owner: IOwner, needResult = false): Promise { return await this.sendMessage(MessageAPI.DELETE_SCHEMA, { id, owner, needResult }); } @@ -719,7 +752,7 @@ export class Guardians extends NatsService { * * @returns {ISchema} - message */ - public async publishSchema(id: string, version: string, owner: string): Promise { + public async publishSchema(id: string, version: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.PUBLISH_SCHEMA, { id, version, owner }); } @@ -733,7 +766,7 @@ export class Guardians extends NatsService { * * @returns {ISchema} - message */ - public async publishSchemaAsync(id: string, version: string, owner: string, task: NewTask): Promise { + public async publishSchemaAsync(id: string, version: string, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.PUBLISH_SCHEMA_ASYNC, { id, version, owner, task }); } @@ -744,8 +777,8 @@ export class Guardians extends NatsService { * * @returns {any[]} - Exported schemas */ - public async exportSchemas(ids: string[]): Promise { - return await this.sendMessage(MessageAPI.EXPORT_SCHEMAS, ids); + public async exportSchemas(ids: string[], owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.EXPORT_SCHEMAS, { ids, owner }); } /** @@ -789,7 +822,7 @@ export class Guardians extends NatsService { * @returns {ISchema[]} - all schemas */ public async createSystemSchema(item: ISchema | any): Promise { - return await this.sendMessage(MessageAPI.CREATE_SYSTEM_SCHEMA, item); + return await this.sendMessage(MessageAPI.CREATE_SYSTEM_SCHEMA, { item }); } /** @@ -801,12 +834,10 @@ export class Guardians extends NatsService { * @returns {ISchema[]} - all schemas */ public async getSystemSchemas( - owner: string, pageIndex?: any, pageSize?: any ): Promise> { return await this.sendMessage(MessageAPI.GET_SYSTEM_SCHEMAS, { - owner, pageIndex, pageSize }); @@ -841,7 +872,7 @@ export class Guardians extends NatsService { * * @returns {any[]} - schemas */ - public async getListSchemas(owner: string): Promise { + public async getListSchemas(owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_LIST_SCHEMAS, { owner }); } @@ -854,7 +885,7 @@ export class Guardians extends NatsService { * * @returns {ISchema[]} - schemas */ - public async getSubSchemas(category: string, topicId: string, owner: string): Promise { + public async getSubSchemas(category: string, topicId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_SUB_SCHEMAS, { topicId, owner, category }); } @@ -867,7 +898,11 @@ export class Guardians extends NatsService { * * @returns - Uploaded Artifacts */ - public async uploadArtifact(artifact: any, owner: string, parentId: string): Promise { + public async uploadArtifact( + artifact: any, + owner: IOwner, + parentId: string + ): Promise { return await this.sendMessage(MessageAPI.UPLOAD_ARTIFACT, { owner, artifact, @@ -892,7 +927,7 @@ export class Guardians extends NatsService { * @param owner Owner * @returns Deleted Flag */ - public async deleteArtifact(artifactId, owner): Promise { + public async deleteArtifact(artifactId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.DELETE_ARTIFACT, { owner, artifactId @@ -908,11 +943,11 @@ export class Guardians extends NatsService { /** * CID */ - cid, + cid: string, /** * URL */ - url + url: string }> { return await this.sendMessage(MessageAPI.IPFS_ADD_FILE, buffer); } @@ -926,13 +961,13 @@ export class Guardians extends NatsService { /** * CID */ - cid, + cid: string, /** * URL */ - url + url: string }> { - return await this.sendMessage(MessageAPI.ADD_FILE_DRY_RUN_STORAGE, {buffer, policyId}); + return await this.sendMessage(MessageAPI.ADD_FILE_DRY_RUN_STORAGE, { buffer, policyId }); } /** @@ -970,16 +1005,16 @@ export class Guardians extends NatsService { * @param idLvl */ public async compareDocuments( - user: any, - type: any, + user: IAuthUser, + type: string, ids: string[], - eventsLvl: any, - propLvl: any, - childrenLvl: any, - idLvl: any, - keyLvl: any, - refLvl: any - ) { + eventsLvl: string | number, + propLvl: string | number, + childrenLvl: string | number, + idLvl: string | number, + keyLvl: string | number, + refLvl: string | number + ): Promise { return await this.sendMessage(MessageAPI.COMPARE_DOCUMENTS, { type, user, @@ -993,6 +1028,40 @@ export class Guardians extends NatsService { }); } + /** + * Compare documents + * @param user + * @param type + * @param ids + * @param eventsLvl + * @param propLvl + * @param childrenLvl + * @param idLvl + */ + public async compareVPDocuments( + user: IAuthUser, + type: string, + ids: string[], + eventsLvl: string | number, + propLvl: string | number, + childrenLvl: string | number, + idLvl: string | number, + keyLvl: string | number, + refLvl: string | number + ) { + return await this.sendMessage(MessageAPI.COMPARE_VP_DOCUMENTS, { + type, + user, + ids, + eventsLvl, + propLvl, + childrenLvl, + idLvl, + keyLvl, + refLvl + }); + } + /** * Compare tools * @param user @@ -1004,14 +1073,14 @@ export class Guardians extends NatsService { * @param idLvl */ public async compareTools( - user: any, - type: any, + user: IAuthUser, + type: string, ids: string[], - eventsLvl: any, - propLvl: any, - childrenLvl: any, - idLvl: any, - ) { + eventsLvl: string | number, + propLvl: string | number, + childrenLvl: string | number, + idLvl: string | number + ): Promise { return await this.sendMessage(MessageAPI.COMPARE_TOOLS, { type, user, @@ -1034,14 +1103,14 @@ export class Guardians extends NatsService { * @param idLvl */ public async comparePolicies( - user: any, - type: any, + user: IAuthUser, + type: string, ids: string[], - eventsLvl: any, - propLvl: any, - childrenLvl: any, - idLvl: any, - ) { + eventsLvl: string | number, + propLvl: string | number, + childrenLvl: string | number, + idLvl: string | number + ): Promise { return await this.sendMessage(MessageAPI.COMPARE_POLICIES, { type, user, @@ -1065,15 +1134,15 @@ export class Guardians extends NatsService { * @param idLvl */ public async compareModules( - user: any, - type: any, - moduleId1: any, - moduleId2: any, - eventsLvl: any, - propLvl: any, - childrenLvl: any, - idLvl: any, - ) { + user: IAuthUser, + type: string, + moduleId1: string, + moduleId2: string, + eventsLvl: string | number, + propLvl: string | number, + childrenLvl: string | number, + idLvl: string | number + ): Promise { return await this.sendMessage(MessageAPI.COMPARE_MODULES, { type, user, @@ -1095,12 +1164,12 @@ export class Guardians extends NatsService { * @param idLvl */ public async compareSchemas( - user: any, - type: any, - schemaId1: any, - schemaId2: any, - idLvl: any, - ) { + user: IAuthUser, + type: string, + schemaId1: string, + schemaId2: string, + idLvl: string | number + ): Promise { return await this.sendMessage(MessageAPI.COMPARE_SCHEMAS, { user, type, schemaId1, schemaId2, idLvl }); @@ -1109,17 +1178,13 @@ export class Guardians extends NatsService { /** * Search policies * @param user - * @param type * @param policyId */ public async searchPolicies( - user: any, + user: IAuthUser, policyId: string - ) { - return await this.sendMessage(MessageAPI.SEARCH_POLICIES, { - user, - policyId - }); + ): Promise { + return await this.sendMessage(MessageAPI.SEARCH_POLICIES, { user, policyId }); } //#region Contracts @@ -1133,7 +1198,7 @@ export class Guardians extends NatsService { * @returns Contracts and count */ public async getContracts( - owner: string, + owner: IOwner, type: ContractType = ContractType.RETIRE, pageIndex?: any, pageSize?: any @@ -1154,12 +1219,12 @@ export class Guardians extends NatsService { * @returns Created contract */ public async createContract( - did: string, + owner: IOwner, description: string, type: ContractType ): Promise { return await this.sendMessage(ContractAPI.CREATE_CONTRACT, { - did, + owner, description, type, }); @@ -1173,12 +1238,12 @@ export class Guardians extends NatsService { * @returns Imported contract */ public async importContract( - did: string, + owner: IOwner, contractId: string, description: string ): Promise { return await this.sendMessage(ContractAPI.IMPORT_CONTRACT, { - did, + owner, contractId, description, }); @@ -1191,12 +1256,12 @@ export class Guardians extends NatsService { * @returns Permissions */ public async checkContractPermissions( - did: string, + owner: IOwner, id: string ): Promise { return await this.sendMessage(ContractAPI.CONTRACT_PERMISSIONS, { id, - did, + owner, }); } @@ -1206,10 +1271,10 @@ export class Guardians extends NatsService { * @param id * @returns Successful operation */ - public async removeContract(owner: string, id: string): Promise { + public async removeContract(owner: IOwner, id: string): Promise { return await this.sendMessage(ContractAPI.REMOVE_CONTRACT, { owner, - id, + id }); } @@ -1222,13 +1287,13 @@ export class Guardians extends NatsService { * @returns Wipe requests and count */ public async getWipeRequests( - did: string, + owner: IOwner, contractId?: string, pageIndex?: any, pageSize?: any ): Promise<[{ user: string }[], number]> { return await this.sendMessage(ContractAPI.GET_WIPE_REQUESTS, { - did, + owner, contractId, pageIndex, pageSize, @@ -1242,7 +1307,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async enableWipeRequests( - owner: string, + owner: IOwner, id: string ): Promise { return await this.sendMessage(ContractAPI.ENABLE_WIPE_REQUESTS, { @@ -1258,7 +1323,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async disableWipeRequests( - owner: string, + owner: IOwner, id: string ): Promise { return await this.sendMessage(ContractAPI.DISABLE_WIPE_REQUESTS, { @@ -1274,7 +1339,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async approveWipeRequest( - owner: string, + owner: IOwner, requestId: string ): Promise { return await this.sendMessage(ContractAPI.APPROVE_WIPE_REQUEST, { @@ -1291,7 +1356,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async rejectWipeRequest( - owner: string, + owner: IOwner, requestId: string, ban: boolean = false ): Promise { @@ -1309,7 +1374,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async clearWipeRequests( - owner: string, + owner: IOwner, id: string ): Promise { return await this.sendMessage(ContractAPI.CLEAR_WIPE_REQUESTS, { @@ -1326,7 +1391,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async addWipeAdmin( - owner: string, + owner: IOwner, id: string, hederaId: string ): Promise { @@ -1345,7 +1410,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async removeWipeAdmin( - owner: string, + owner: IOwner, id: string, hederaId: string ): Promise { @@ -1364,7 +1429,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async addWipeManager( - owner: string, + owner: IOwner, id: string, hederaId: string ): Promise { @@ -1383,7 +1448,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async removeWipeManager( - owner: string, + owner: IOwner, id: string, hederaId: string ): Promise { @@ -1402,7 +1467,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async addWipeWiper( - owner: string, + owner: IOwner, id: string, hederaId: string ): Promise { @@ -1421,7 +1486,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async removeWipeWiper( - owner: string, + owner: IOwner, id: string, hederaId: string ): Promise { @@ -1438,7 +1503,7 @@ export class Guardians extends NatsService { * @param id * @returns Sync date */ - public async syncRetirePools(owner: string, id: string): Promise { + public async syncRetirePools(owner: IOwner, id: string): Promise { return await this.sendMessage(ContractAPI.SYNC_RETIRE_POOLS, { owner, id, @@ -1454,13 +1519,13 @@ export class Guardians extends NatsService { * @returns Retire requests and count */ public async getRetireRequests( - did: string, + owner: IOwner, contractId?: string, pageIndex?: any, pageSize?: any ): Promise<[IRetireRequest, number]> { return await this.sendMessage(ContractAPI.GET_RETIRE_REQUESTS, { - did, + owner, contractId, pageIndex, pageSize, @@ -1477,7 +1542,7 @@ export class Guardians extends NatsService { * @returns Retire pools and count */ public async getRetirePools( - owner: string, + owner: IOwner, tokens?: string[], contractId?: string, pageIndex?: any, @@ -1499,7 +1564,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async clearRetireRequests( - owner: string, + owner: IOwner, id: string ): Promise { return await this.sendMessage(ContractAPI.CLEAR_RETIRE_REQUESTS, { @@ -1514,7 +1579,7 @@ export class Guardians extends NatsService { * @param id * @returns Operation successful */ - public async clearRetirePools(owner: string, id: string): Promise { + public async clearRetirePools(owner: IOwner, id: string): Promise { return await this.sendMessage(ContractAPI.CLEAR_RETIRE_POOLS, { owner, id, @@ -1529,7 +1594,7 @@ export class Guardians extends NatsService { * @returns Pool */ public async setRetirePool( - owner: string, + owner: IOwner, id: string, options: { tokens: RetireTokenPool[]; immediately: boolean } ): Promise { @@ -1547,7 +1612,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async unsetRetirePool( - owner: string, + owner: IOwner, poolId: string ): Promise { return await this.sendMessage(ContractAPI.UNSET_RETIRE_POOLS, { @@ -1563,7 +1628,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async unsetRetireRequest( - owner: string, + owner: IOwner, requestId: string ): Promise { return await this.sendMessage(ContractAPI.UNSET_RETIRE_REQUEST, { @@ -1580,12 +1645,12 @@ export class Guardians extends NatsService { * @returns Tokens retired */ public async retire( - did: string, + owner: IOwner, poolId: string, tokens: RetireTokenRequest[] ): Promise { return await this.sendMessage(ContractAPI.RETIRE, { - did, + owner, poolId, tokens, }); @@ -1598,7 +1663,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async approveRetire( - owner: string, + owner: IOwner, requestId: string ): Promise { return await this.sendMessage(ContractAPI.APPROVE_RETIRE, { @@ -1614,7 +1679,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async cancelRetire( - owner: string, + owner: IOwner, requestId: string ): Promise { return await this.sendMessage(ContractAPI.CANCEL_RETIRE, { @@ -1631,7 +1696,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async addRetireAdmin( - owner: string, + owner: IOwner, id: string, hederaId: string ): Promise { @@ -1650,7 +1715,7 @@ export class Guardians extends NatsService { * @returns Operation successful */ public async removeRetireAdmin( - owner: string, + owner: IOwner, id: string, hederaId: string ): Promise { @@ -1669,7 +1734,7 @@ export class Guardians extends NatsService { * @returns Retire VCs and count */ public async getRetireVCs( - owner: string, + owner: IOwner, pageIndex?: any, pageSize?: any ): Promise<[IVCDocument, number]> { @@ -1688,7 +1753,10 @@ export class Guardians extends NatsService { * @param owner * @returns module */ - public async createModule(module: any, owner: string): Promise { + public async createModule( + module: ModuleDTO, + owner: IOwner + ): Promise { return await this.sendMessage(MessageAPI.CREATE_MODULE, { module, owner }); } @@ -1699,8 +1767,8 @@ export class Guardians extends NatsService { * * @returns {ResponseAndCount} */ - public async getModule(params?: IFilter): Promise> { - return await this.sendMessage(MessageAPI.GET_MODULES, params); + public async getModule(filters: IFilter, owner: IOwner): Promise> { + return await this.sendMessage(MessageAPI.GET_MODULES, { filters, owner }); } /** @@ -1709,7 +1777,7 @@ export class Guardians extends NatsService { * @param owner * @returns Operation Success */ - public async deleteModule(uuid: string, owner: string): Promise { + public async deleteModule(uuid: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.DELETE_MODULES, { uuid, owner }); } @@ -1718,7 +1786,7 @@ export class Guardians extends NatsService { * @param owner * @returns modules */ - public async getMenuModule(owner: string): Promise { + public async getMenuModule(owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_MENU_MODULES, { owner }); } @@ -1731,8 +1799,8 @@ export class Guardians extends NatsService { */ public async updateModule( uuid: string, - module: any, - owner: string + module: ModuleDTO, + owner: IOwner ): Promise { return await this.sendMessage(MessageAPI.UPDATE_MODULES, { uuid, module, owner }); } @@ -1743,7 +1811,7 @@ export class Guardians extends NatsService { * @param owner * @returns Operation Success */ - public async getModuleById(uuid: string, owner: string): Promise { + public async getModuleById(uuid: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_MODULE, { uuid, owner }); } @@ -1752,7 +1820,7 @@ export class Guardians extends NatsService { * @param uuid * @param owner */ - public async exportModuleFile(uuid: string, owner: string) { + public async exportModuleFile(uuid: string, owner: IOwner) { const file = await this.sendMessage(MessageAPI.MODULE_EXPORT_FILE, { uuid, owner }) as any; return Buffer.from(file, 'base64'); } @@ -1762,7 +1830,7 @@ export class Guardians extends NatsService { * @param uuid * @param owner */ - public async exportModuleMessage(uuid: string, owner: string) { + public async exportModuleMessage(uuid: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.MODULE_EXPORT_MESSAGE, { uuid, owner }); } @@ -1771,7 +1839,7 @@ export class Guardians extends NatsService { * @param zip * @param owner */ - public async importModuleFile(zip: any, owner: string) { + public async importModuleFile(zip: any, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.MODULE_IMPORT_FILE, { zip, owner }); } @@ -1780,7 +1848,7 @@ export class Guardians extends NatsService { * @param messageId * @param owner */ - public async importModuleMessage(messageId: string, owner: string) { + public async importModuleMessage(messageId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.MODULE_IMPORT_MESSAGE, { messageId, owner }); } @@ -1789,7 +1857,7 @@ export class Guardians extends NatsService { * @param zip * @param owner */ - public async previewModuleFile(zip: any, owner: string) { + public async previewModuleFile(zip: any, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.MODULE_IMPORT_FILE_PREVIEW, { zip, owner }); } @@ -1798,7 +1866,7 @@ export class Guardians extends NatsService { * @param messageId * @param owner */ - public async previewModuleMessage(messageId: string, owner: string) { + public async previewModuleMessage(messageId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.MODULE_IMPORT_MESSAGE_PREVIEW, { messageId, owner }); } @@ -1808,7 +1876,7 @@ export class Guardians extends NatsService { * @param owner * @param module */ - public async publishModule(uuid: string, owner: string, module: any) { + public async publishModule(uuid: string, owner: IOwner, module: ModuleDTO): Promise { return await this.sendMessage(MessageAPI.PUBLISH_MODULES, { uuid, owner, module }); } @@ -1817,7 +1885,7 @@ export class Guardians extends NatsService { * @param owner * @param module */ - public async validateModule(owner: string, module: any) { + public async validateModule(owner: IOwner, module: ModuleDTO): Promise { return await this.sendMessage(MessageAPI.VALIDATE_MODULES, { owner, module }); } @@ -1827,7 +1895,7 @@ export class Guardians extends NatsService { * @param owner * @returns tool */ - public async createTool(tool: any, owner: string): Promise { + public async createTool(tool: ToolDTO, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.CREATE_TOOL, { tool, owner }); } @@ -1838,7 +1906,7 @@ export class Guardians extends NatsService { * @param task * @returns tool */ - public async createToolAsync(tool: any, owner: string, task: NewTask): Promise { + public async createToolAsync(tool: ToolDTO, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.CREATE_TOOL_ASYNC, { tool, owner, task }); } @@ -1849,8 +1917,8 @@ export class Guardians extends NatsService { * * @returns {ResponseAndCount} */ - public async getTools(params?: IFilter): Promise> { - return await this.sendMessage(MessageAPI.GET_TOOLS, params); + public async getTools(filters: IFilter, owner: IOwner): Promise> { + return await this.sendMessage(MessageAPI.GET_TOOLS, { filters, owner }); } /** @@ -1859,7 +1927,7 @@ export class Guardians extends NatsService { * @param owner * @returns Operation Success */ - public async deleteTool(id: string, owner: string): Promise { + public async deleteTool(id: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.DELETE_TOOL, { id, owner }); } @@ -1869,7 +1937,7 @@ export class Guardians extends NatsService { * @param owner * @returns Operation Success */ - public async getToolById(id: string, owner: string): Promise { + public async getToolById(id: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_TOOL, { id, owner }); } @@ -1882,8 +1950,8 @@ export class Guardians extends NatsService { */ public async updateTool( id: string, - tool: any, - owner: string + tool: ToolDTO, + owner: IOwner ): Promise { return await this.sendMessage(MessageAPI.UPDATE_TOOL, { id, tool, owner }); } @@ -1894,7 +1962,7 @@ export class Guardians extends NatsService { * @param owner * @param tool */ - public async publishTool(id: string, owner: string, tool: any) { + public async publishTool(id: string, owner: IOwner, tool: ToolDTO): Promise { return await this.sendMessage(MessageAPI.PUBLISH_TOOL, { id, owner, tool }); } @@ -1905,7 +1973,7 @@ export class Guardians extends NatsService { * @param tool * @param task */ - public async publishToolAsync(id: string, owner: string, tool: any, task: NewTask) { + public async publishToolAsync(id: string, owner: IOwner, tool: ToolDTO, task: NewTask) { return await this.sendMessage(MessageAPI.PUBLISH_TOOL_ASYNC, { id, owner, tool, task }); } @@ -1914,7 +1982,7 @@ export class Guardians extends NatsService { * @param owner * @param tool */ - public async validateTool(owner: string, tool: any) { + public async validateTool(owner: IOwner, tool: ToolDTO) { return await this.sendMessage(MessageAPI.VALIDATE_TOOL, { owner, tool }); } @@ -1923,7 +1991,7 @@ export class Guardians extends NatsService { * @param owner * @returns tools */ - public async getMenuTool(owner: string): Promise { + public async getMenuTool(owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_MENU_TOOLS, { owner }); } @@ -1932,7 +2000,7 @@ export class Guardians extends NatsService { * @param id * @param owner */ - public async exportToolFile(id: string, owner: string) { + public async exportToolFile(id: string, owner: IOwner) { const file = await this.sendMessage(MessageAPI.TOOL_EXPORT_FILE, { id, owner }) as any; return Buffer.from(file, 'base64'); } @@ -1942,7 +2010,7 @@ export class Guardians extends NatsService { * @param id * @param owner */ - public async exportToolMessage(id: string, owner: string) { + public async exportToolMessage(id: string, owner: IOwner) { return await this.sendMessage(MessageAPI.TOOL_EXPORT_MESSAGE, { id, owner }); } @@ -1952,7 +2020,7 @@ export class Guardians extends NatsService { * @param owner * @param metadata */ - public async importToolFile(zip: any, owner: string, metadata?: PolicyToolMetadata) { + public async importToolFile(zip: any, owner: IOwner, metadata?: PolicyToolMetadata): Promise { return await this.sendMessage(MessageAPI.TOOL_IMPORT_FILE, { zip, owner, metadata }); } @@ -1961,7 +2029,7 @@ export class Guardians extends NatsService { * @param messageId * @param owner */ - public async importToolMessage(messageId: string, owner: string) { + public async importToolMessage(messageId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.TOOL_IMPORT_MESSAGE, { messageId, owner }); } @@ -1970,7 +2038,7 @@ export class Guardians extends NatsService { * @param zip * @param owner */ - public async previewToolFile(zip: any, owner: string) { + public async previewToolFile(zip: any, owner: IOwner) { return await this.sendMessage(MessageAPI.TOOL_IMPORT_FILE_PREVIEW, { zip, owner }); } @@ -1979,7 +2047,7 @@ export class Guardians extends NatsService { * @param messageId * @param owner */ - public async previewToolMessage(messageId: string, owner: string) { + public async previewToolMessage(messageId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.TOOL_IMPORT_MESSAGE_PREVIEW, { messageId, owner }); } @@ -1990,7 +2058,7 @@ export class Guardians extends NatsService { * @param task * @param metadata */ - public async importToolFileAsync(zip: any, owner: string, task: NewTask, metadata?: PolicyToolMetadata) { + public async importToolFileAsync(zip: any, owner: IOwner, task: NewTask, metadata?: PolicyToolMetadata) { return await this.sendMessage(MessageAPI.TOOL_IMPORT_FILE_ASYNC, { zip, owner, task, metadata }); } @@ -2000,7 +2068,7 @@ export class Guardians extends NatsService { * @param owner * @param task */ - public async importToolMessageAsync(messageId: string, owner: string, task: NewTask) { + public async importToolMessageAsync(messageId: string, owner: IOwner, task: NewTask) { return await this.sendMessage(MessageAPI.TOOL_IMPORT_MESSAGE_ASYNC, { messageId, owner, task }); } @@ -2024,7 +2092,7 @@ export class Guardians extends NatsService { * @param owner * @returns tag */ - public async createTag(tag: any, owner: string): Promise { + public async createTag(tag: TagDTO, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.CREATE_TAG, { tag, owner }); } @@ -2044,7 +2112,7 @@ export class Guardians extends NatsService { * @param owner * @returns Operation Success */ - public async deleteTag(uuid: string, owner: string): Promise { + public async deleteTag(uuid: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.DELETE_TAG, { uuid, owner }); } @@ -2087,7 +2155,7 @@ export class Guardians extends NatsService { * @returns {ISchema[]} - all schemas */ public async getTagSchemas( - owner: string, + owner: IOwner, pageIndex?: any, pageSize?: any ): Promise> { @@ -2105,8 +2173,8 @@ export class Guardians extends NatsService { * * @returns {ISchema[]} - all schemas */ - public async createTagSchema(item: ISchema | any): Promise { - return await this.sendMessage(MessageAPI.CREATE_TAG_SCHEMA, item); + public async createTagSchema(item: ISchema | any, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.CREATE_TAG_SCHEMA, { item, owner }); } /** @@ -2118,7 +2186,7 @@ export class Guardians extends NatsService { * * @returns {ISchema} - message */ - public async publishTagSchema(id: string, version: string, owner: string): Promise { + public async publishTagSchema(id: string, version: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.PUBLISH_TAG_SCHEMA, { id, version, owner }); } @@ -2127,7 +2195,7 @@ export class Guardians extends NatsService { * * @returns {ISchema[]} - schemas */ - public async getPublishedTagSchemas(): Promise { + public async getPublishedTagSchemas(): Promise { return await this.sendMessage(MessageAPI.GET_PUBLISHED_TAG_SCHEMAS); } @@ -2137,7 +2205,7 @@ export class Guardians extends NatsService { * @param owner * @returns theme */ - public async createTheme(theme: any, owner: string): Promise { + public async createTheme(theme: ThemeDTO, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.CREATE_THEME, { theme, owner }); } @@ -2151,7 +2219,7 @@ export class Guardians extends NatsService { public async updateTheme( themeId: string, theme: any, - owner: string + owner: IOwner ): Promise { return await this.sendMessage(MessageAPI.UPDATE_THEME, { themeId, theme, owner }); } @@ -2161,7 +2229,7 @@ export class Guardians extends NatsService { * @param owner * @returns themes */ - public async getThemes(owner: string): Promise { + public async getThemes(owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_THEMES, { owner }); } @@ -2170,8 +2238,8 @@ export class Guardians extends NatsService { * @param themeId * @returns theme */ - public async getThemeById(themeId: string): Promise { - return await this.sendMessage(MessageAPI.GET_THEME, { themeId }); + public async getThemeById(themeId: string, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.GET_THEME, { themeId, owner }); } /** @@ -2180,7 +2248,7 @@ export class Guardians extends NatsService { * @param owner * @returns Operation Success */ - public async deleteTheme(themeId: string, owner: string): Promise { + public async deleteTheme(themeId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.DELETE_THEME, { themeId, owner }); } @@ -2189,7 +2257,7 @@ export class Guardians extends NatsService { * @param zip * @param owner */ - public async importThemeFile(zip: any, owner: string) { + public async importThemeFile(zip: any, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.THEME_IMPORT_FILE, { zip, owner }); } @@ -2198,7 +2266,7 @@ export class Guardians extends NatsService { * @param uuid * @param owner */ - public async exportThemeFile(themeId: string, owner: string) { + public async exportThemeFile(themeId: string, owner: IOwner) { const file = await this.sendMessage(MessageAPI.THEME_EXPORT_FILE, { themeId, owner }) as any; return Buffer.from(file, 'base64'); } @@ -2209,7 +2277,7 @@ export class Guardians extends NatsService { * @returns Config */ // tslint:disable-next-line:completed-docs - public async wizardPolicyCreate(config: any, owner: string): Promise<{ wizardConfig: any; policyId: string; }> { + public async wizardPolicyCreate(config: any, owner: IOwner): Promise<{ wizardConfig: any; policyId: string; }> { return await this.sendMessage(MessageAPI.WIZARD_POLICY_CREATE, { owner, config, @@ -2223,7 +2291,7 @@ export class Guardians extends NatsService { * @param task Task * @returns Config */ - public async wizardPolicyCreateAsync(config: any, owner: string, task: NewTask): Promise { + public async wizardPolicyCreateAsync(config: any, owner: IOwner, task: NewTask): Promise { return await this.sendMessage(MessageAPI.WIZARD_POLICY_CREATE_ASYNC, { owner, config, @@ -2238,7 +2306,7 @@ export class Guardians extends NatsService { * @param task Task * @returns Config */ - public async wizardPolicyCreateAsyncNew(config: any, owner: string, saveState: boolean, task: NewTask): Promise { + public async wizardPolicyCreateAsyncNew(config: any, owner: IOwner, saveState: boolean, task: NewTask): Promise { return await this.sendMessage(MessageAPI.WIZARD_POLICY_CREATE_ASYNC, { owner, config, @@ -2254,7 +2322,7 @@ export class Guardians extends NatsService { * @returns Config */ // tslint:disable-next-line:completed-docs - public async wizardGetPolicyConfig(policyId: string, config: any, owner: string): Promise<{ wizardConfig: any; policyConfig: any; }> { + public async wizardGetPolicyConfig(policyId: string, config: any, owner: IOwner): Promise<{ wizardConfig: any; policyConfig: any; }> { return await this.sendMessage(MessageAPI.WIZARD_GET_POLICY_CONFIG, { policyId, config, @@ -2287,7 +2355,7 @@ export class Guardians extends NatsService { */ public async policySuggestions( suggestionsInput: any, - user: any + user: IAuthUser ): Promise<{ next: string, nested: string }> { return await this.sendMessage(MessageAPI.SUGGESTIONS, { user, @@ -2301,7 +2369,7 @@ export class Guardians extends NatsService { */ public async setPolicySuggestionsConfig( items: SuggestionsOrderPriority[], - user: any + user: IAuthUser ): Promise { return await this.sendMessage( MessageAPI.SET_SUGGESTIONS_CONFIG, @@ -2314,7 +2382,7 @@ export class Guardians extends NatsService { * @param suggestionsInput */ public async getPolicySuggestionsConfig( - user: any + user: IAuthUser ): Promise { return await this.sendMessage( MessageAPI.GET_SUGGESTIONS_CONFIG, @@ -2331,7 +2399,7 @@ export class Guardians extends NatsService { public async searchBlocks( config: any, blockId: string, - user: any + user: IAuthUser ): Promise { return await this.sendMessage(MessageAPI.SEARCH_BLOCKS, { config, blockId, user }); } @@ -2343,7 +2411,7 @@ export class Guardians extends NatsService { * @param options * @returns {any} */ - public async startRecording(policyId: string, owner: string, options: any): Promise { + public async startRecording(policyId: string, owner: IOwner, options: any): Promise { return await this.sendMessage(MessageAPI.START_RECORDING, { policyId, owner, options }); } @@ -2354,7 +2422,7 @@ export class Guardians extends NatsService { * @param options * @returns {any} */ - public async stopRecording(policyId: string, owner: string, options: any): Promise { + public async stopRecording(policyId: string, owner: IOwner, options: any): Promise { const file = await this.sendMessage(MessageAPI.STOP_RECORDING, { policyId, owner, options }); return Buffer.from(file, 'base64'); } @@ -2365,7 +2433,7 @@ export class Guardians extends NatsService { * @param owner * @returns {any} */ - public async getRecordedActions(policyId: string, owner: string): Promise { + public async getRecordedActions(policyId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_RECORDED_ACTIONS, { policyId, owner }); } @@ -2375,7 +2443,7 @@ export class Guardians extends NatsService { * @param owner * @returns {any} */ - public async getRecordStatus(policyId: string, owner: string): Promise { + public async getRecordStatus(policyId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_RECORD_STATUS, { policyId, owner }); } @@ -2386,7 +2454,7 @@ export class Guardians extends NatsService { * @param options * @returns {any} */ - public async runRecord(policyId: string, owner: string, options: any): Promise { + public async runRecord(policyId: string, owner: IOwner, options: any): Promise { return await this.sendMessage(MessageAPI.RUN_RECORD, { policyId, owner, options }); } @@ -2397,7 +2465,7 @@ export class Guardians extends NatsService { * @param options * @returns {any} */ - public async stopRunning(policyId: string, owner: string, options: any): Promise { + public async stopRunning(policyId: string, owner: IOwner, options: any): Promise { return await this.sendMessage(MessageAPI.STOP_RUNNING, { policyId, owner, options }); } @@ -2407,7 +2475,7 @@ export class Guardians extends NatsService { * @param owner * @returns {any} */ - public async getRecordResults(policyId: string, owner: string): Promise { + public async getRecordResults(policyId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_RECORD_RESULTS, { policyId, owner }); } @@ -2417,7 +2485,7 @@ export class Guardians extends NatsService { * @param owner * @returns {any} */ - public async getRecordDetails(policyId: string, owner: string): Promise { + public async getRecordDetails(policyId: string, owner: IOwner): Promise { return await this.sendMessage(MessageAPI.GET_RECORD_DETAILS, { policyId, owner }); } @@ -2428,7 +2496,7 @@ export class Guardians extends NatsService { * @param options * @returns {any} */ - public async fastForward(policyId: string, owner: string, options: any): Promise { + public async fastForward(policyId: string, owner: IOwner, options: any): Promise { return await this.sendMessage(MessageAPI.FAST_FORWARD, { policyId, owner, options }); } @@ -2439,7 +2507,7 @@ export class Guardians extends NatsService { * @param options * @returns {any} */ - public async retryStep(policyId: string, owner: string, options: any): Promise { + public async retryStep(policyId: string, owner: IOwner, options: any): Promise { return await this.sendMessage(MessageAPI.RECORD_RETRY_STEP, { policyId, owner, options }); } @@ -2450,7 +2518,7 @@ export class Guardians extends NatsService { * @param options * @returns {any} */ - public async skipStep(policyId: string, owner: string, options: any): Promise { + public async skipStep(policyId: string, owner: IOwner, options: any): Promise { return await this.sendMessage(MessageAPI.RECORD_SKIP_STEP, { policyId, owner, options }); } @@ -2459,8 +2527,8 @@ export class Guardians extends NatsService { * @param user * @param ids */ - public async exportSchemasXlsx(user: IAuthUser, ids: string[]) { - const file = await this.sendMessage(MessageAPI.SCHEMA_EXPORT_XLSX, { ids, user }) as any; + public async exportSchemasXlsx(owner: IOwner, ids: string[]) { + const file = await this.sendMessage(MessageAPI.SCHEMA_EXPORT_XLSX, { ids, owner }) as any; return Buffer.from(file, 'base64'); } @@ -2470,8 +2538,8 @@ export class Guardians extends NatsService { * @param topicId * @param xlsx */ - public async importSchemasByXlsx(user: IAuthUser, topicId: string, xlsx: ArrayBuffer) { - return await this.sendMessage(MessageAPI.SCHEMA_IMPORT_XLSX, { user, xlsx, topicId }); + public async importSchemasByXlsx(owner: IOwner, topicId: string, xlsx: ArrayBuffer) { + return await this.sendMessage(MessageAPI.SCHEMA_IMPORT_XLSX, { owner, xlsx, topicId }); } /** @@ -2481,8 +2549,8 @@ export class Guardians extends NatsService { * @param versionOfTopicId * @param task */ - public async importSchemasByXlsxAsync(user: IAuthUser, topicId: string, xlsx: ArrayBuffer, task: NewTask) { - return await this.sendMessage(MessageAPI.SCHEMA_IMPORT_XLSX_ASYNC, { user, xlsx, topicId, task }); + public async importSchemasByXlsxAsync(owner: IOwner, topicId: string, xlsx: ArrayBuffer, task: NewTask) { + return await this.sendMessage(MessageAPI.SCHEMA_IMPORT_XLSX_ASYNC, { owner, xlsx, topicId, task }); } /** @@ -2490,8 +2558,8 @@ export class Guardians extends NatsService { * @param user * @param zip */ - public async previewSchemasByFileXlsx(user: IAuthUser, xlsx: ArrayBuffer) { - return await this.sendMessage(MessageAPI.SCHEMA_IMPORT_XLSX_PREVIEW, { user, xlsx }); + public async previewSchemasByFileXlsx(owner: IOwner, xlsx: ArrayBuffer) { + return await this.sendMessage(MessageAPI.SCHEMA_IMPORT_XLSX_PREVIEW, { owner, xlsx }); } /** @@ -2518,4 +2586,107 @@ export class Guardians extends NatsService { public async validateDidKeys(document: any, keys: any): Promise { return await this.sendMessage(MessageAPI.VALIDATE_DID_KEY, { document, keys }); } + + /** + * Assign entity + * @param type + * @param entityId + * @param assign + * @param did + */ + public async assignEntity( + type: AssignedEntityType, + entityIds: string[], + assign: boolean, + did: string, + owner: string + ): Promise { + return await this.sendMessage(MessageAPI.ASSIGN_ENTITY, { type, entityIds, assign, did, owner }); + } + + /** + * Assign entity + * @param type + * @param entityId + * @param assign + * @param did + */ + public async delegateEntity( + type: AssignedEntityType, + entityIds: string[], + assign: boolean, + did: string, + owner: string + ): Promise { + return await this.sendMessage(MessageAPI.DELEGATE_ENTITY, { type, entityIds, assign, did, owner }); + } + + /** + * Check entity + * @param type + * @param entityId + * @param checkAssign + * @param did + */ + public async checkEntity( + type: AssignedEntityType, + entityId: string, + checkAssign: boolean, + did: string + ): Promise { + return await this.sendMessage(MessageAPI.CHECK_ENTITY, { type, entityId, checkAssign, did }); + } + + /** + * Get assigned entities + * @param type + * @param did + */ + public async assignedEntities( + did: string, + type?: AssignedEntityType + ): Promise { + return await this.sendMessage(MessageAPI.ASSIGNED_ENTITIES, { type, did }); + } + + /** + * Get policy + * @param filters + */ + public async getAssignedPolicies(options: any): Promise { + return await this.sendMessage(MessageAPI.GET_ASSIGNED_POLICIES, options); + } + + /** + * Create role + * @param role + * @param owner + */ + public async createRole(role: any, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.CREATE_ROLE, { role, owner }); + } + /** + * Update role + * @param role + * @param owner + */ + public async updateRole(role: any, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.UPDATE_ROLE, { role, owner }); + } + /** + * Delete role + * @param role + * @param owner + */ + public async deleteRole(role: any, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.DELETE_ROLE, { role, owner }); + } + /** + * Set role + * @param user + * @param owner + */ + public async setRole(user: IAuthUser, owner: IOwner): Promise { + return await this.sendMessage(MessageAPI.SET_ROLE, { user, owner }); + } } diff --git a/api-gateway/src/helpers/index.ts b/api-gateway/src/helpers/index.ts new file mode 100644 index 0000000000..47b61e7902 --- /dev/null +++ b/api-gateway/src/helpers/index.ts @@ -0,0 +1,18 @@ +export * from './ai-suggestions.js'; +export * from './cache-provider.js'; +export * from './cache-service.js'; +export * from './guardians.js'; +export * from './ipfs.js'; +export * from './meeco.js'; +export * from './policy-engine.js'; +export * from './projects.js'; +export * from './schema-utils.js'; +export * from './service-requests-base.js'; +export * from './swagger-config.js'; +export * from './task-manager.js'; +export * from './users.js'; +export * from './utils.js'; +export * from './wallet.js'; +export * from './decorators/index.js'; +export * from './interceptors/index.js'; +export * from './entity-owner.js'; \ No newline at end of file diff --git a/api-gateway/src/helpers/interceptors/cache.ts b/api-gateway/src/helpers/interceptors/cache.ts index 6781147e50..d3b60ca297 100644 --- a/api-gateway/src/helpers/interceptors/cache.ts +++ b/api-gateway/src/helpers/interceptors/cache.ts @@ -13,62 +13,62 @@ import { CACHE, META_DATA } from '../../constants/index.js'; @Injectable() export class CacheInterceptor implements NestInterceptor { - constructor(private readonly cacheService: CacheService) { - } - - async intercept(context: ExecutionContext, next: CallHandler): Promise> { - const httpContext = context.switchToHttp(); - const request = httpContext.getRequest(); - const responseContext = httpContext.getResponse(); - - const ttl = Reflect.getMetadata(META_DATA.TTL, context.getHandler()) ?? CACHE.DEFAULT_TTL; - const isExpress = Reflect.getMetadata(META_DATA.EXPRESS, context.getHandler()); - - const token = request.headers.authorization?.split(' ')[1]; - let user = {} - - if(token) { - const users: Users = new Users(); - try { - user = await users.getUserByToken(token); - } catch (error) { - throw new HttpException(error.message, HttpStatus.UNAUTHORIZED) - } + constructor(private readonly cacheService: CacheService) { } - const hashUser: string = crypto.createHash('md5').update(JSON.stringify(user)).digest('hex'); - const { url: route } = request; - const cacheKey = `cache/${route}:${hashUser}`; + async intercept(context: ExecutionContext, next: CallHandler): Promise> { + const httpContext = context.switchToHttp(); + const request = httpContext.getRequest(); + const responseContext = httpContext.getResponse(); - return of(null).pipe( - switchMap(async () => { - const cachedResponse: string = await this.cacheService.get(cacheKey); + const ttl = Reflect.getMetadata(META_DATA.TTL, context.getHandler()) ?? CACHE.DEFAULT_TTL; + const isExpress = Reflect.getMetadata(META_DATA.EXPRESS, context.getHandler()); - if (cachedResponse) { - return JSON.parse(cachedResponse); - } - }), - switchMap(resultResponse => { - if (resultResponse) { - if (isExpress) { - return of(responseContext.json(resultResponse)); - } - - return of(resultResponse); - } - - return next.handle().pipe( - tap(async response => { - let result = response; + const token = request.headers.authorization?.split(' ')[1]; + let user = {} - if (isExpress) { - result = response.locals.data; + if (token) { + const users: Users = new Users(); + try { + user = await users.getUserByToken(token); + } catch (error) { + throw new HttpException(error.message, HttpStatus.UNAUTHORIZED) } + } - await this.cacheService.set(cacheKey, JSON.stringify(result), ttl); - }), + const hashUser: string = crypto.createHash('md5').update(JSON.stringify(user)).digest('hex'); + const { url: route } = request; + const cacheKey = `cache/${route}:${hashUser}`; + + return of(null).pipe( + switchMap(async () => { + const cachedResponse: string = await this.cacheService.get(cacheKey); + + if (cachedResponse) { + return JSON.parse(cachedResponse); + } + }), + switchMap(resultResponse => { + if (resultResponse) { + if (isExpress) { + return of(responseContext.send(resultResponse)); + } + + return of(resultResponse); + } + + return next.handle().pipe( + tap(async response => { + let result = response; + + if (isExpress) { + result = response.locals.data; + } + + await this.cacheService.set(cacheKey, JSON.stringify(result), ttl); + }), + ); + }), ); - }), - ); - } + } } diff --git a/api-gateway/src/helpers/interceptors/index.ts b/api-gateway/src/helpers/interceptors/index.ts new file mode 100644 index 0000000000..86be449993 --- /dev/null +++ b/api-gateway/src/helpers/interceptors/index.ts @@ -0,0 +1,4 @@ +export * from './performance.js'; +export * from './multipart.js'; +export * from './cache.js'; +export * from './types/index.js'; \ No newline at end of file diff --git a/api-gateway/src/helpers/interceptors/multipart.ts b/api-gateway/src/helpers/interceptors/multipart.ts new file mode 100644 index 0000000000..81acaff5a1 --- /dev/null +++ b/api-gateway/src/helpers/interceptors/multipart.ts @@ -0,0 +1,54 @@ +import { CallHandler, ExecutionContext, HttpException, HttpStatus, mixin, NestInterceptor, Type } from '@nestjs/common'; + +import { MultipartValue } from '@fastify/multipart'; +import { Observable } from 'rxjs'; + +//utils +import { getFileFromPart } from './utils/index.js'; + +//types and interfaces +import { FastifyRequest, MultipartFile, MultipartOptions } from './types/index.js'; + +export function AnyFilesInterceptor(options: MultipartOptions = {}): Type { + class MixinInterceptor implements NestInterceptor { + async intercept(context: ExecutionContext, next: CallHandler): Promise> { + const req = context.switchToHttp().getRequest() as FastifyRequest; + + if (!req.isMultipart()) { + throw new HttpException('The request should be a form-data', HttpStatus.BAD_REQUEST); + } + + const files: MultipartFile[] = []; + const body = {}; + + try { + for await (const part of req.parts()) { + const { type, fieldname } = part; + + if (type !== 'file') { + body[fieldname] = (part as MultipartValue).value; + continue; + } + + const file: MultipartFile | null = await getFileFromPart(part); + + if (file) { + files.push(file); + } + } + } catch (error) { + throw new HttpException(error.message, HttpStatus.BAD_REQUEST); + } + + if (files.length) { + req.storedFiles = files; + } + + req.body = body; + + return next.handle(); + } + } + + return mixin(MixinInterceptor); +} \ No newline at end of file diff --git a/api-gateway/src/helpers/interceptors/types/index.ts b/api-gateway/src/helpers/interceptors/types/index.ts new file mode 100644 index 0000000000..df348d04ea --- /dev/null +++ b/api-gateway/src/helpers/interceptors/types/index.ts @@ -0,0 +1 @@ +export { MultipartFile, MultipartOptions, FastifyRequest } from './multipart.js'; \ No newline at end of file diff --git a/api-gateway/src/helpers/interceptors/types/multipart.ts b/api-gateway/src/helpers/interceptors/types/multipart.ts new file mode 100644 index 0000000000..e14a84db7e --- /dev/null +++ b/api-gateway/src/helpers/interceptors/types/multipart.ts @@ -0,0 +1,23 @@ +import * as fastify from 'fastify' + +export interface FastifyRequest extends fastify.FastifyRequest { + storedFiles: MultipartFile[]; + body: unknown; +} + +export interface MultipartFile { + buffer: Buffer; + filename: string; + size: number; + mimetype: string; + fieldname: string; + encoding: string; + originalname: string; +} + +export class MultipartOptions { + constructor( + public maxFileSize?: number, + public fileType?: string | RegExp, + ) {} +} \ No newline at end of file diff --git a/api-gateway/src/helpers/interceptors/utils/index.ts b/api-gateway/src/helpers/interceptors/utils/index.ts new file mode 100644 index 0000000000..7aa65a3a50 --- /dev/null +++ b/api-gateway/src/helpers/interceptors/utils/index.ts @@ -0,0 +1 @@ +export { getFileFromPart } from './multipart.js'; \ No newline at end of file diff --git a/api-gateway/src/helpers/interceptors/utils/multipart.ts b/api-gateway/src/helpers/interceptors/utils/multipart.ts new file mode 100644 index 0000000000..2c4016bf4e --- /dev/null +++ b/api-gateway/src/helpers/interceptors/utils/multipart.ts @@ -0,0 +1,25 @@ +import { MultipartFile as MultipartFileFastify } from '@fastify/multipart'; + +//types and interfaces +import { MultipartFile } from '../types/index.js'; + +export const getFileFromPart = async (part: MultipartFileFastify): Promise => { + const buffer: Buffer = await part.toBuffer(); + + const { byteLength: size } = buffer; + const { filename, mimetype, fieldname, encoding } = part; + + if (!size || !fieldname) { + return null; + } + + return { + buffer, + size, + filename, + mimetype, + fieldname, + encoding, + originalname: fieldname, + }; +}; \ No newline at end of file diff --git a/api-gateway/src/helpers/policy-engine.ts b/api-gateway/src/helpers/policy-engine.ts index e64df03c3f..74a58914e3 100644 --- a/api-gateway/src/helpers/policy-engine.ts +++ b/api-gateway/src/helpers/policy-engine.ts @@ -1,7 +1,8 @@ import { Singleton } from '../helpers/decorators/singleton.js'; -import { DocumentType, GenerateUUIDv4, MigrationConfig, PolicyEngineEvents, PolicyToolMetadata } from '@guardian/interfaces'; +import { DocumentType, GenerateUUIDv4, IOwner, MigrationConfig, PolicyEngineEvents, PolicyToolMetadata } from '@guardian/interfaces'; import { IAuthUser, NatsService } from '@guardian/common'; import { NewTask } from './task-manager.js'; +import { ExportMessageDTO, PoliciesValidationDTO, PolicyDTO, PolicyPreviewDTO, PolicyValidationDTO } from '#middlewares'; /** * Policy engine service @@ -23,25 +24,38 @@ export class PolicyEngine extends NatsService { * Get policy * @param filters */ - public async getPolicy(filters): Promise { - return await this.sendMessage(PolicyEngineEvents.GET_POLICY, filters); + public async getPolicy(options: any, owner: IOwner): Promise { + return await this.sendMessage(PolicyEngineEvents.GET_POLICY, { options, owner }); + } + + /** + * Get policy + * @param policyId + */ + public async accessPolicy( + policyId: string, + owner: IOwner, + action: string + ): Promise { + return await this.sendMessage(PolicyEngineEvents.ACCESS_POLICY, { policyId, owner, action }); } /** * Get policies * @param filters + * @param owner */ public async getPolicies(filters): Promise { - return await this.sendMessage(PolicyEngineEvents.GET_POLICIES, filters); + count: number + }>(options: any, owner: IOwner): Promise { + return await this.sendMessage(PolicyEngineEvents.GET_POLICIES, { options, owner }); } /** @@ -49,99 +63,142 @@ export class PolicyEngine extends NatsService { * @param owner * @param status */ - public async getTokensMap(owner: string, status?: string): Promise { + public async getTokensMap( + owner: IOwner, + status?: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.GET_TOKENS_MAP, { owner, status }); } /** * Create policy * @param model - * @param user + * @param owner */ - public async createPolicy(model: any, user: IAuthUser) { - return await this.sendMessage(PolicyEngineEvents.CREATE_POLICIES, { model, user }); + public async createPolicy( + model: PolicyDTO, + owner: IOwner + ): Promise { + return await this.sendMessage(PolicyEngineEvents.CREATE_POLICIES, { model, owner }); } /** * Async create policy * @param model - * @param user + * @param owner * @param task */ - public async createPolicyAsync(model: any, user: IAuthUser, task: NewTask) { - return await this.sendMessage(PolicyEngineEvents.CREATE_POLICIES_ASYNC, { model, user, task }); + public async createPolicyAsync( + model: PolicyDTO, + owner: IOwner, + task: NewTask + ): Promise { + return await this.sendMessage(PolicyEngineEvents.CREATE_POLICIES_ASYNC, { model, owner, task }); } /** * Async clone policy * @param policyId Policy identifier * @param model Policy configuration - * @param user User + * @param owner User * @param task Task */ - public async clonePolicyAsync(policyId: string, model, user: IAuthUser, task: NewTask) { - return await this.sendMessage(PolicyEngineEvents.CLONE_POLICY_ASYNC, { policyId, model, user, task }); + public async clonePolicyAsync( + policyId: string, + model: PolicyDTO, + owner: IOwner, + task: NewTask + ): Promise { + return await this.sendMessage(PolicyEngineEvents.CLONE_POLICY_ASYNC, { policyId, model, owner, task }); } /** * Async delete policy * @param policyId Policy identifier - * @param user User + * @param owner User * @param task Task */ - public async deletePolicyAsync(policyId: string, user: IAuthUser, task: NewTask) { - return await this.sendMessage(PolicyEngineEvents.DELETE_POLICY_ASYNC, { policyId, user, task }); + public async deletePolicyAsync( + policyId: string, + owner: IOwner, + task: NewTask + ): Promise { + return await this.sendMessage(PolicyEngineEvents.DELETE_POLICY_ASYNC, { policyId, owner, task }); } /** * Save policy * @param model - * @param user + * @param owner * @param policyId */ - public async savePolicy(model: any, user: IAuthUser, policyId: string) { - return await this.sendMessage(PolicyEngineEvents.SAVE_POLICIES, { model, user, policyId }); + public async savePolicy( + model: PolicyDTO, + owner: IOwner, + policyId: string + ): Promise { + return await this.sendMessage(PolicyEngineEvents.SAVE_POLICIES, { model, owner, policyId }); } /** * Publish policy * @param model - * @param user + * @param owner * @param policyId */ - public async publishPolicy(model: any, user: IAuthUser, policyId: string) { - return await this.sendMessage(PolicyEngineEvents.PUBLISH_POLICIES, { model, user, policyId }); + public async publishPolicy( + model: any, + owner: IOwner, + policyId: string + ): Promise { + return await this.sendMessage(PolicyEngineEvents.PUBLISH_POLICIES, { model, owner, policyId }); } /** * Async publish policy * @param model - * @param user + * @param owner * @param policyId * @param task */ - public async publishPolicyAsync(model: any, user: IAuthUser, policyId: string, task: NewTask) { - return await this.sendMessage(PolicyEngineEvents.PUBLISH_POLICIES_ASYNC, { model, user, policyId, task }); + public async publishPolicyAsync( + model: any, + owner: IOwner, + policyId: string, + task: NewTask + ): Promise { + return await this.sendMessage(PolicyEngineEvents.PUBLISH_POLICIES_ASYNC, { model, owner, policyId, task }); } /** * Dry-run policy - * @param user * @param policyId + * @param owner */ - public async dryRunPolicy(user: IAuthUser, policyId: string) { - return await this.sendMessage(PolicyEngineEvents.DRY_RUN_POLICIES, { user, policyId }); + public async dryRunPolicy( + policyId: string, + owner: IOwner, + ): Promise { + return await this.sendMessage(PolicyEngineEvents.DRY_RUN_POLICIES, { policyId, owner }); } /** * Dry-run policy - * @param user * @param policyId + * @param owner */ - public async draft(user: IAuthUser, policyId: string) { - return await this.sendMessage(PolicyEngineEvents.DRAFT_POLICIES, { user, policyId }); + public async draft( + policyId: string, + owner: IOwner + ): Promise { + return await this.sendMessage(PolicyEngineEvents.DRAFT_POLICIES, { policyId, owner }); } + /** + * Restart policy + * @param user + * @param policyId + */ public async restartPolicyInstance(user: IAuthUser, policyId: string) { return await this.sendMessage(PolicyEngineEvents.RESTART_POLICY_INSTANCE, { user, policyId }); } @@ -149,11 +206,15 @@ export class PolicyEngine extends NatsService { /** * Validate policy * @param model - * @param user + * @param owner * @param policyId */ - public async validatePolicy(model: any, user: IAuthUser, policyId?: string) { - return await this.sendMessage(PolicyEngineEvents.VALIDATE_POLICIES, { model, user, policyId }); + public async validatePolicy( + model: PolicyDTO, + owner: IOwner, + policyId?: string + ): Promise { + return await this.sendMessage(PolicyEngineEvents.VALIDATE_POLICIES, { model, owner, policyId }); } /** @@ -161,7 +222,7 @@ export class PolicyEngine extends NatsService { * @param user * @param policyId */ - public async getPolicyBlocks(user: IAuthUser, policyId: string) { + public async getPolicyBlocks(user: IAuthUser, policyId: string): Promise { return await this.sendMessage(PolicyEngineEvents.POLICY_BLOCKS, { user, policyId }); } @@ -169,7 +230,10 @@ export class PolicyEngine extends NatsService { * Get policies by category Id * @param filters */ - public async getPoliciesByCategoriesAndText(categoryIds: string[], text: string): Promise { + public async getPoliciesByCategoriesAndText( + categoryIds: string[], + text: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.GET_POLICIES_BY_CATEGORY, { categoryIds, text }); } @@ -179,7 +243,11 @@ export class PolicyEngine extends NatsService { * @param policyId * @param blockId */ - public async getBlockData(user: IAuthUser, policyId: string, blockId: string) { + public async getBlockData( + user: IAuthUser, + policyId: string, + blockId: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.GET_BLOCK_DATA, { user, blockId, policyId }); } @@ -189,7 +257,11 @@ export class PolicyEngine extends NatsService { * @param policyId * @param tag */ - public async getBlockDataByTag(user: IAuthUser, policyId: string, tag: string) { + public async getBlockDataByTag( + user: IAuthUser, + policyId: string, + tag: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.GET_BLOCK_DATA_BY_TAG, { user, tag, policyId }); } @@ -200,7 +272,12 @@ export class PolicyEngine extends NatsService { * @param blockId * @param data */ - public async setBlockData(user: IAuthUser, policyId: string, blockId: string, data: any) { + public async setBlockData( + user: IAuthUser, + policyId: string, + blockId: string, + data: any + ): Promise { return await this.sendMessage(PolicyEngineEvents.SET_BLOCK_DATA, { user, blockId, policyId, data }); } @@ -211,7 +288,12 @@ export class PolicyEngine extends NatsService { * @param blockId * @param data */ - public async setBlockDataByTag(user: IAuthUser, policyId: string, tag: string, data: any) { + public async setBlockDataByTag( + user: IAuthUser, + policyId: string, + tag: string, + data: any + ): Promise { return await this.sendMessage(PolicyEngineEvents.SET_BLOCK_DATA_BY_TAG, { user, tag, policyId, data }); } @@ -221,7 +303,11 @@ export class PolicyEngine extends NatsService { * @param policyId * @param tag */ - public async getBlockByTagName(user: IAuthUser, policyId: string, tag: string) { + public async getBlockByTagName( + user: IAuthUser, + policyId: string, + tag: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.BLOCK_BY_TAG, { user, tag, policyId }); } @@ -231,55 +317,68 @@ export class PolicyEngine extends NatsService { * @param policyId * @param blockId */ - public async getBlockParents(user: IAuthUser, policyId: string, blockId: string) { + public async getBlockParents( + user: IAuthUser, + policyId: string, + blockId: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.GET_BLOCK_PARENTS, { user, blockId, policyId }); } /** * Get policy export file - * @param user * @param policyId + * @param owner */ - public async exportFile(user: IAuthUser, policyId: string) { - const file = await this.sendMessage(PolicyEngineEvents.POLICY_EXPORT_FILE, { policyId, user }) as any; + public async exportFile( + policyId: string, + owner: IOwner + ): Promise { + const file = await this.sendMessage(PolicyEngineEvents.POLICY_EXPORT_FILE, { policyId, owner }) as any; return Buffer.from(file, 'base64'); } /** * Get policy export message id - * @param user * @param policyId + * @param owner */ - public async exportMessage(user: IAuthUser, policyId: string) { - return await this.sendMessage(PolicyEngineEvents.POLICY_EXPORT_MESSAGE, { policyId, user }); + public async exportMessage( + policyId: string, + owner: IOwner + ): Promise { + return await this.sendMessage(PolicyEngineEvents.POLICY_EXPORT_MESSAGE, { policyId, owner }); } /** * Get policy export xlsx - * @param user * @param policyId + * @param owner */ - public async exportXlsx(user: IAuthUser, policyId: string) { - const file = await this.sendMessage(PolicyEngineEvents.POLICY_EXPORT_XLSX, { policyId, user }) as any; + public async exportXlsx( + policyId: string, + owner: IOwner + ): Promise { + const file = await this.sendMessage(PolicyEngineEvents.POLICY_EXPORT_XLSX, { policyId, owner }) as any; return Buffer.from(file, 'base64'); } /** * Load policy file for import - * @param user * @param zip + * @param owner * @param versionOfTopicId * @param metadata */ public async importFile( - user: IAuthUser, zip: Buffer, + owner: IOwner, versionOfTopicId?: string, metadata?: PolicyToolMetadata - ) { + ): Promise { return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_FILE, { zip, - user, + owner, versionOfTopicId, metadata, }); @@ -287,121 +386,143 @@ export class PolicyEngine extends NatsService { /** * Async load policy file for import - * @param user * @param zip + * @param owner * @param versionOfTopicId * @param task * @param metadata */ public async importFileAsync( - user: IAuthUser, zip: Buffer, + owner: IOwner, versionOfTopicId: string, task: NewTask, metadata?: PolicyToolMetadata ) { return await this.sendMessage( PolicyEngineEvents.POLICY_IMPORT_FILE_ASYNC, - { zip, user, versionOfTopicId, task, metadata } + { zip, owner, versionOfTopicId, task, metadata } ); } /** * Import policy from message - * @param user * @param messageId + * @param owner * @param versionOfTopicId * @param metadata */ public async importMessage( - user: IAuthUser, messageId: string, + owner: IOwner, versionOfTopicId: string, metadata?: PolicyToolMetadata - ) { + ): Promise { return await this.sendMessage( PolicyEngineEvents.POLICY_IMPORT_MESSAGE, - { messageId, user, versionOfTopicId, metadata } + { messageId, owner, versionOfTopicId, metadata } ); } /** * Async import policy from message - * @param user * @param messageId + * @param owner * @param versionOfTopicId * @param task * @param metadata */ public async importMessageAsync( - user: IAuthUser, messageId: string, + owner: IOwner, versionOfTopicId: string, task: NewTask, metadata?: PolicyToolMetadata ) { return await this.sendMessage( PolicyEngineEvents.POLICY_IMPORT_MESSAGE_ASYNC, - { messageId, user, versionOfTopicId, task, metadata } + { messageId, owner, versionOfTopicId, task, metadata } ); } /** * Get policy info from file - * @param user * @param zip + * @param owner */ - public async importFilePreview(user: IAuthUser, zip: ArrayBuffer) { - return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_FILE_PREVIEW, { zip, user }); + public async importFilePreview( + zip: ArrayBuffer, + owner: IOwner + ): Promise { + return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_FILE_PREVIEW, { zip, owner }); } /** * Load xlsx file for import - * @param user - * @param zip - * @param versionOfTopicId + * @param xlsx + * @param owner + * @param policyId */ - public async importXlsx(user: IAuthUser, xlsx: ArrayBuffer, policyId: string) { - return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_XLSX, { user, xlsx, policyId }); + public async importXlsx( + xlsx: ArrayBuffer, + owner: IOwner, + policyId: string + ): Promise { + return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_XLSX, { xlsx, owner, policyId }); } /** * Async load xlsx file for import - * @param user - * @param zip - * @param versionOfTopicId + * @param xlsx + * @param owner + * @param policyId * @param task */ - public async importXlsxAsync(user: IAuthUser, xlsx: ArrayBuffer, policyId: string, task: NewTask) { - return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_XLSX_ASYNC, { user, xlsx, policyId, task }); + public async importXlsxAsync( + xlsx: ArrayBuffer, + owner: IOwner, + policyId: string, + task: NewTask + ) { + return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_XLSX_ASYNC, { xlsx, owner, policyId, task }); } /** * Get policy info from xlsx file - * @param user * @param zip + * @param owner */ - public async importXlsxPreview(user: IAuthUser, xlsx: ArrayBuffer) { - return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_XLSX_FILE_PREVIEW, { user, xlsx }); + public async importXlsxPreview( + xlsx: ArrayBuffer, + owner: IOwner + ): Promise { + return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_XLSX_FILE_PREVIEW, { owner, xlsx }); } /** * Get policy info from message - * @param user * @param messageId + * @param owner */ - public async importMessagePreview(user: IAuthUser, messageId: string) { - return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_MESSAGE_PREVIEW, { messageId, user }); + public async importMessagePreview( + messageId: string, + owner: IOwner + ): Promise { + return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_MESSAGE_PREVIEW, { messageId, owner }); } /** * Async get policy info from message - * @param user * @param messageId + * @param owner * @param task */ - public async importMessagePreviewAsync(user: IAuthUser, messageId: string, task: NewTask) { - return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_MESSAGE_PREVIEW_ASYNC, { messageId, user, task }); + public async importMessagePreviewAsync( + messageId: string, + owner: IOwner, + task: NewTask + ): Promise { + return await this.sendMessage(PolicyEngineEvents.POLICY_IMPORT_MESSAGE_PREVIEW_ASYNC, { messageId, owner, task }); } /** @@ -423,8 +544,11 @@ export class PolicyEngine extends NatsService { * Get Virtual Users by policy id * @param policyId */ - public async getVirtualUsers(policyId: string) { - return await this.sendMessage(PolicyEngineEvents.GET_VIRTUAL_USERS, { policyId }); + public async getVirtualUsers( + policyId: string, + owner: IOwner + ) { + return await this.sendMessage(PolicyEngineEvents.GET_VIRTUAL_USERS, { policyId, owner }); } /** @@ -432,7 +556,10 @@ export class PolicyEngine extends NatsService { * @param policyId * @param owner */ - public async createVirtualUser(policyId: string, owner: string) { + public async createVirtualUser( + policyId: string, + owner: IOwner + ) { return await this.sendMessage(PolicyEngineEvents.CREATE_VIRTUAL_USER, { policyId, owner }); } @@ -441,18 +568,26 @@ export class PolicyEngine extends NatsService { * @param policyId * @param did */ - public async loginVirtualUser(policyId: string, did: string) { - return await this.sendMessage(PolicyEngineEvents.SET_VIRTUAL_USER, { policyId, did }); + public async loginVirtualUser( + policyId: string, + virtualDID: string, + owner: IOwner + ) { + return await this.sendMessage(PolicyEngineEvents.SET_VIRTUAL_USER, { policyId, virtualDID, owner }); } /** * Restart Dry-run policy * @param model - * @param user + * @param owner * @param policyId */ - public async restartDryRun(model: any, user: IAuthUser, policyId: string) { - return await this.sendMessage(PolicyEngineEvents.RESTART_DRY_RUN, { model, user, policyId }); + public async restartDryRun( + model: any, + owner: IOwner, + policyId: string + ) { + return await this.sendMessage(PolicyEngineEvents.RESTART_DRY_RUN, { model, owner, policyId }); } /** @@ -465,12 +600,14 @@ export class PolicyEngine extends NatsService { public async getVirtualDocuments( policyId: string, type: string, - pageIndex?: string, - pageSize?: string + owner: IOwner, + pageIndex?: number, + pageSize?: number ): Promise<[any[], number]> { return await this.sendMessage(PolicyEngineEvents.GET_VIRTUAL_DOCUMENTS, { policyId, type, + owner, pageIndex, pageSize }); @@ -482,7 +619,10 @@ export class PolicyEngine extends NatsService { * @param user * @param policyId */ - public async getNavigation(user: IAuthUser, policyId: string) { + public async getNavigation( + user: IAuthUser, + policyId: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.GET_POLICY_NAVIGATION, { user, policyId }); } @@ -492,7 +632,10 @@ export class PolicyEngine extends NatsService { * @param user * @param policyId */ - public async getGroups(user: IAuthUser, policyId: string) { + public async getGroups( + user: IAuthUser, + policyId: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.GET_POLICY_GROUPS, { user, policyId }); } @@ -503,7 +646,11 @@ export class PolicyEngine extends NatsService { * @param policyId * @param uuid */ - public async selectGroup(user: IAuthUser, policyId: string, uuid: string) { + public async selectGroup( + user: IAuthUser, + policyId: string, + uuid: string + ): Promise { return await this.sendMessage(PolicyEngineEvents.SELECT_POLICY_GROUP, { user, policyId, uuid }); } @@ -512,8 +659,11 @@ export class PolicyEngine extends NatsService { * @param user * @param policyId */ - public async getMultiPolicy(user: IAuthUser, policyId: string) { - return await this.sendMessage(PolicyEngineEvents.GET_MULTI_POLICY, { user, policyId }); + public async getMultiPolicy( + owner: IOwner, + policyId: string + ) { + return await this.sendMessage(PolicyEngineEvents.GET_MULTI_POLICY, { owner, policyId }); } /** @@ -522,17 +672,26 @@ export class PolicyEngine extends NatsService { * @param policyId * @param data */ - public async setMultiPolicy(user: IAuthUser, policyId: string, data: any) { - return await this.sendMessage(PolicyEngineEvents.SET_MULTI_POLICY, { user, policyId, data }); + public async setMultiPolicy( + owner: IOwner, + policyId: string, + data: any + ) { + return await this.sendMessage(PolicyEngineEvents.SET_MULTI_POLICY, { owner, policyId, data }); } /** * Discontinue policy - * @param user * @param policyId + * @param owner + * @param date */ - public async discontinuePolicy(user: any, policyId: string, date?: string) { - return await this.sendMessage(PolicyEngineEvents.DISCONTINUE_POLICY, { user, policyId, date }); + public async discontinuePolicy( + policyId: string, + owner: IOwner, + date?: string + ): Promise { + return await this.sendMessage(PolicyEngineEvents.DISCONTINUE_POLICY, { policyId, owner, date }); } /** @@ -546,14 +705,15 @@ export class PolicyEngine extends NatsService { * @returns Documents and count */ public async getDocuments( - owner: string, + owner: IOwner, policyId: string, includeDocument: boolean = false, type?: DocumentType, - pageIndex?: string, - pageSize?: string + pageIndex?: number | string, + pageSize?: number | string ): Promise<[any[], number]> { - return await this.sendMessage(PolicyEngineEvents.GET_POLICY_DOCUMENTS, { owner, policyId, includeDocument, type, pageIndex, pageSize }); + return await this.sendMessage(PolicyEngineEvents.GET_POLICY_DOCUMENTS, + { owner, policyId, includeDocument, type, pageIndex, pageSize }); } /** @@ -563,7 +723,7 @@ export class PolicyEngine extends NatsService { * @returns Errors */ public async migrateData( - owner: string, + owner: IOwner, migrationConfig: MigrationConfig, ): Promise<{ error: string, id: string }[]> { return await this.sendMessage(PolicyEngineEvents.MIGRATE_DATA, { owner, migrationConfig }); @@ -576,11 +736,11 @@ export class PolicyEngine extends NatsService { * @param task Task */ public async migrateDataAsync( - owner: string, + owner: IOwner, migrationConfig: MigrationConfig, - task - ): Promise { - await this.sendMessage(PolicyEngineEvents.MIGRATE_DATA_ASYNC, { owner, migrationConfig, task }); + task: NewTask + ): Promise { + return await this.sendMessage(PolicyEngineEvents.MIGRATE_DATA_ASYNC, { owner, migrationConfig, task }); } /** @@ -589,7 +749,10 @@ export class PolicyEngine extends NatsService { * @param owner Owner * @returns Data */ - public async downloadPolicyData(policyId: string, owner: string) { + public async downloadPolicyData( + policyId: string, + owner: IOwner + ) { return Buffer.from( (await this.sendMessage(PolicyEngineEvents.DOWNLOAD_POLICY_DATA, { policyId, @@ -605,7 +768,7 @@ export class PolicyEngine extends NatsService { * @param owner Owner * @returns Virtual keys */ - public async downloadVirtualKeys(policyId: string, owner: string) { + public async downloadVirtualKeys(policyId: string, owner: IOwner) { return Buffer.from( (await this.sendMessage(PolicyEngineEvents.DOWNLOAD_VIRTUAL_KEYS, { policyId, @@ -621,9 +784,12 @@ export class PolicyEngine extends NatsService { * @param data Data * @returns Uploaded policy */ - public async uploadPolicyData(user: string, data: any) { + public async uploadPolicyData( + owner: IOwner, + data: any + ) { return await this.sendMessage(PolicyEngineEvents.UPLOAD_POLICY_DATA, { - user, + owner, data, }); } @@ -635,7 +801,11 @@ export class PolicyEngine extends NatsService { * @param policyId Policy identifier * @returns Operation completed */ - public async uploadVirtualKeys(owner: string, data: any, policyId: string) { + public async uploadVirtualKeys( + owner: IOwner, + data: any, + policyId: string + ) { return await this.sendMessage(PolicyEngineEvents.UPLOAD_VIRTUAL_KEYS, { owner, data, @@ -649,7 +819,10 @@ export class PolicyEngine extends NatsService { * @param owner Owner * @returns Tag block map */ - public async getTagBlockMap(policyId: string, owner: string): Promise { + public async getTagBlockMap( + policyId: string, + owner: IOwner + ): Promise { return await this.sendMessage(PolicyEngineEvents.GET_TAG_BLOCK_MAP, { policyId, owner, diff --git a/api-gateway/src/helpers/schema-utils.ts b/api-gateway/src/helpers/schema-utils.ts index d149c51540..0c4604947a 100644 --- a/api-gateway/src/helpers/schema-utils.ts +++ b/api-gateway/src/helpers/schema-utils.ts @@ -1,5 +1,4 @@ -import { IAuthUser } from '@guardian/common'; -import { ISchema, SchemaCategory } from '@guardian/interfaces'; +import { IOwner, ISchema, SchemaCategory } from '@guardian/interfaces'; /** * API Schema Utils @@ -51,6 +50,20 @@ export class SchemaUtils { return schema; } + /** + * Clear ids + * @param {ISchema} schema + * @returns {ISchema} + */ + public static clearIds(schema: ISchema): ISchema { + delete schema.version; + delete schema.id; + delete schema.status; + delete schema.topicId; + delete schema._id; + return schema; + } + /** * Check schema permission * @param {ISchema} schema @@ -59,16 +72,23 @@ export class SchemaUtils { * * @returns {string} error */ - public static checkPermission(schema: ISchema, user: IAuthUser, type: SchemaCategory): string | null { + public static checkPermission( + schema: ISchema, + user: IOwner, + type: SchemaCategory + ): string | null { if (!schema) { return 'Schema does not exist.'; } if (schema.system) { - if (schema.creator !== user.username) { + if ( + schema.creator !== user.username && + schema.creator !== user.creator + ) { return 'Invalid creator.'; } } else { - if (schema.creator !== user.did) { + if (schema.owner !== user.owner) { return 'Invalid creator.'; } } diff --git a/api-gateway/src/helpers/swagger-config.ts b/api-gateway/src/helpers/swagger-config.ts index d2bf7fa09d..554da58fe2 100644 --- a/api-gateway/src/helpers/swagger-config.ts +++ b/api-gateway/src/helpers/swagger-config.ts @@ -23,7 +23,7 @@ export const SwaggerConfig = new DocumentBuilder() 'version 1.0' ) .addSecurity( - 'bearerAuth', + 'bearer', { type: 'http', scheme: 'bearer', diff --git a/api-gateway/src/helpers/task-manager.ts b/api-gateway/src/helpers/task-manager.ts index f4ec920b9b..382e7410e4 100644 --- a/api-gateway/src/helpers/task-manager.ts +++ b/api-gateway/src/helpers/task-manager.ts @@ -89,7 +89,7 @@ export class TaskManager { * @param wsService * @param cn */ - public setDependecies(wsService: WebSocketsService, cn: NatsConnection) { + public setDependencies(wsService: WebSocketsService, cn: NatsConnection) { this.wsService = wsService; this.channel = new TaskManagerChannel(); this.channel.setConnection(cn); diff --git a/api-gateway/src/helpers/users.ts b/api-gateway/src/helpers/users.ts index cdad3842fb..3283c65577 100644 --- a/api-gateway/src/helpers/users.ts +++ b/api-gateway/src/helpers/users.ts @@ -1,7 +1,22 @@ import { Singleton } from '../helpers/decorators/singleton.js'; -import { ApplicationStates, AuthEvents, GenerateUUIDv4, MessageAPI, UserRole } from '@guardian/interfaces'; +import { ApplicationStates, AuthEvents, GenerateUUIDv4, IOwner, MessageAPI, UserRole } from '@guardian/interfaces'; import { AuthenticatedRequest, IAuthUser, NatsService, ProviderAuthUser } from '@guardian/common'; import { Injectable } from '@nestjs/common'; +import { RoleDTO } from '#middlewares'; + +/** + * Items and count + */ +interface ResponseAndCount { + /** + * Return count + */ + count: number; + /** + * Schemas array + */ + items: U[]; +} /** * Users service @@ -35,7 +50,7 @@ export class Users extends NatsService { if (!(target as AuthenticatedRequest).user || !(target as AuthenticatedRequest).user.username) { return null; } - user = await this.sendMessage(AuthEvents.GET_USER, {username: (target as AuthenticatedRequest).user.username}); + user = await this.sendMessage(AuthEvents.GET_USER, { username: (target as AuthenticatedRequest).user.username }); } return user; } @@ -70,7 +85,7 @@ export class Users extends NatsService { * @param username */ public async getUser(username: string): Promise { - return await this.sendMessage(AuthEvents.GET_USER, {username}); + return await this.sendMessage(AuthEvents.GET_USER, { username }); } /** @@ -78,7 +93,7 @@ export class Users extends NatsService { * @param did */ public async getUserById(did: string): Promise { - return await this.sendMessage(AuthEvents.GET_USER_BY_ID, {did}); + return await this.sendMessage(AuthEvents.GET_USER_BY_ID, { did }); } /** @@ -94,7 +109,7 @@ export class Users extends NatsService { * @param dids */ public async getUsersByIds(dids: string[]): Promise { - return await this.sendMessage(AuthEvents.GET_USERS_BY_ID, {dids}); + return await this.sendMessage(AuthEvents.GET_USERS_BY_ID, { dids }); } /** @@ -102,7 +117,7 @@ export class Users extends NatsService { * @param role */ public async getUsersByRole(role: UserRole): Promise { - return await this.sendMessage(AuthEvents.GET_USERS_BY_ROLE, {role}); + return await this.sendMessage(AuthEvents.GET_USERS_BY_ROLE, { role }); } /** @@ -127,7 +142,7 @@ export class Users extends NatsService { * @param token */ public async getUserByToken(token: string) { - return await this.sendMessage(AuthEvents.GET_USER_BY_TOKEN, {token}); + return await this.sendMessage(AuthEvents.GET_USER_BY_TOKEN, { token }); } /** @@ -136,7 +151,7 @@ export class Users extends NatsService { * @param password * @param role */ - public async registerNewUser(username: string, password: string, role: string) { + public async registerNewUser(username: string, password: string, role: string): Promise { return await this.sendMessage(AuthEvents.REGISTER_NEW_USER, { username, password, role }); } @@ -150,13 +165,13 @@ export class Users extends NatsService { } public async generateNewAccessToken(refreshToken: string): Promise { - return await this.sendMessage(AuthEvents.GENERATE_NEW_ACCESS_TOKEN, {refreshToken}); + return await this.sendMessage(AuthEvents.GENERATE_NEW_ACCESS_TOKEN, { refreshToken }); } /** * Get all user accounts */ - public async getAllUserAccounts(): Promise { + public async getAllUserAccounts(): Promise { return await this.sendMessage(AuthEvents.GET_ALL_USER_ACCOUNTS); } @@ -191,6 +206,124 @@ export class Users extends NatsService { public async generateNewUserTokenBasedOnExternalUserProvider(userProvider: ProviderAuthUser): Promise { return await this.sendMessage(AuthEvents.GENERATE_NEW_TOKEN_BASED_ON_USER_PROVIDER, userProvider); } + + /** + * Get permissions + * @param options + * @returns Operation Success + */ + public async getPermissions(): Promise { + return await this.sendMessage(AuthEvents.GET_PERMISSIONS, {}); + } + + /** + * Get roles + * @param options + * @returns Operation Success + */ + public async getRoles(options: any): Promise> { + return await this.sendMessage(AuthEvents.GET_ROLES, options); + } + + /** + * Get role + * @param id + * @returns Operation Success + */ + public async getRoleById(id: string): Promise { + return await this.sendMessage(AuthEvents.GET_ROLE, { id }); + } + + /** + * Create role + * @param id + * @param role + * @param owner + * @returns Operation Success + */ + public async createRole(role: any, owner: IOwner): Promise { + return await this.sendMessage(AuthEvents.CREATE_ROLE, { role, owner }); + } + + /** + * Update role + * @param id + * @param role + * @param owner + * @returns Operation Success + */ + public async updateRole(id: string, role: any, owner: IOwner): Promise { + return await this.sendMessage(AuthEvents.UPDATE_ROLE, { id, role, owner }); + } + + /** + * Delete role + * @param id + * @param owner + * @returns Operation Success + */ + public async deleteRole(id: string, owner: IOwner): Promise { + return await this.sendMessage(AuthEvents.DELETE_ROLE, { id, owner }); + } + + /** + * Det default role + * @param id + * @param owner + * @returns Operation Success + */ + public async setDefaultRole(id: string, owner: string): Promise { + return await this.sendMessage(AuthEvents.SET_DEFAULT_ROLE, { id, owner }); + } + + /** + * Get roles + * @param options + * @returns Operation Success + */ + public async getWorkers(options: any): Promise> { + return await this.sendMessage(AuthEvents.GET_USER_ACCOUNTS, options); + } + + /** + * Update user role + * @param username + * @param user + * @param owner + * @returns Operation Success + */ + public async updateUserRole( + username: string, + userRoles: string[], + owner: IOwner + ): Promise { + return await this.sendMessage(AuthEvents.UPDATE_USER_ROLE, { username, userRoles, owner }); + } + + /** + * Delegate user role + * @param username + * @param userRoles + * @param owner + * @returns Operation Success + */ + public async delegateUserRole( + username: string, + userRoles: string[], + owner: IOwner + ): Promise { + return await this.sendMessage(AuthEvents.DELEGATE_USER_ROLE, { username, userRoles, owner }); + } + + /** + * Refresh user permissions + * @param id + * @param owner + * @returns Operation Success + */ + public async refreshUserPermissions(id: string, owner: string): Promise { + return await this.sendMessage(AuthEvents.REFRESH_USER_PERMISSIONS, { id, owner }); + } } @Injectable() diff --git a/api-gateway/src/helpers/utils.ts b/api-gateway/src/helpers/utils.ts index c92fae12b8..8de87c4019 100644 --- a/api-gateway/src/helpers/utils.ts +++ b/api-gateway/src/helpers/utils.ts @@ -1,16 +1,21 @@ +import { HttpException, HttpStatus } from '@nestjs/common'; +import { IAuthUser, Logger } from '@guardian/common'; +import { IOwner, PolicyType, UserRole } from '@guardian/interfaces'; +import { PolicyEngine } from './policy-engine.js'; + /** * Find all field values in object by field name * @param obj * @param name */ -export function findAllEntities(obj: {[key:string]: any}, name: string): string[] { +export function findAllEntities(obj: { [key: string]: any }, name: string): string[] { const result = []; - const finder = (o: {[key:string]: any}): void => { - if(!o) { + const finder = (o: { [key: string]: any }): void => { + if (!o) { return; } - if(o.hasOwnProperty(name)) { + if (o.hasOwnProperty(name)) { result.push(o[name]); } @@ -37,13 +42,13 @@ export function findAllEntities(obj: {[key:string]: any}, name: string): string[ * @param newValue */ export function replaceAllEntities( - obj: {[key:string]: any}, + obj: { [key: string]: any }, name: string, oldValue: string, newValue: string ): void { - const finder = (o: {[key:string]: any}): void => { - if(o.hasOwnProperty(name) && o[name] === oldValue) { + const finder = (o: { [key: string]: any }): void => { + if (o.hasOwnProperty(name) && o[name] === oldValue) { o[name] = newValue; } @@ -55,3 +60,69 @@ export function replaceAllEntities( } finder(obj); } + +/** + * Pars int + * @param value + */ +export function parseInteger(value: any): number | undefined { + if (typeof value === 'string') { + const result = Number.parseInt(value, 10); + if (Number.isFinite(result)) { + return result; + } else { + return undefined; + } + } + if (typeof value === 'number') { + if (Number.isFinite(value)) { + return Math.floor(value); + } else { + return undefined; + } + } + return undefined; +} + +export const ONLY_SR = ' Only users with the Standard Registry role are allowed to make the request.'; + +/** + * Generate HttpException + * @param error + */ +export async function InternalException(error: HttpException | Error | string) { + await (new Logger()).error(error, ['API_GATEWAY']); + if (error instanceof HttpException) { + throw error; + } else if (typeof error === 'string') { + throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR); + } else { + throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); + }; +} + +/** + * Check policy + * @param policyId + * @param owner + */ +export async function checkPolicy(policyId: string, owner: IOwner): Promise { + const policy = await (new PolicyEngine().accessPolicy(policyId, owner, 'read')); + if (policy.status !== PolicyType.DRY_RUN) { + throw new HttpException('Invalid status.', HttpStatus.FORBIDDEN) + } + return policy; +} + +/** + * Check policy + * @param policyId + * @param owner + */ +export function getParentUser(user: IAuthUser): string { + if (user.role === UserRole.STANDARD_REGISTRY) { + return user.did; + } else { + return user.parent; + } +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/index.ts b/api-gateway/src/middlewares/index.ts new file mode 100644 index 0000000000..578958f2a4 --- /dev/null +++ b/api-gateway/src/middlewares/index.ts @@ -0,0 +1 @@ +export * from './validation/index.js'; \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/examples.ts b/api-gateway/src/middlewares/validation/examples.ts new file mode 100644 index 0000000000..189cae2832 --- /dev/null +++ b/api-gateway/src/middlewares/validation/examples.ts @@ -0,0 +1,11 @@ +export enum Examples { + DB_ID = '000000000000000000000001', + MESSAGE_ID = '0000000000.000000001', + UUID = '00000000-0000-0000-0000-000000000000', + ACCOUNT_ID = '0.0.1', + DATE = '1900-01-01T00:00:00.000Z', + IPFS = 'ipfs://AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', + COLOR = '#000000', + DID = '#did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001', + HASH = 'GcDE9NsPJc7oCZvSVJySCZHxTxvjc3ZAMgtKozP1r1Eh', +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/index.ts b/api-gateway/src/middlewares/validation/index.ts index d196aa60b4..99416da4e4 100644 --- a/api-gateway/src/middlewares/validation/index.ts +++ b/api-gateway/src/middlewares/validation/index.ts @@ -34,8 +34,13 @@ const validate = (schema) => async (req, res, next) => { }, { abortEarly: false }); return next(); } catch (err) { - return res.status(422).json(prepareValidationResponse(err, err.name)); + return res.status(422).send(prepareValidationResponse(err, err.name)); } }; -export default validate \ No newline at end of file +export default validate + +export * from './examples.js'; +export * from './page-header.js'; +export * from './fields-validation.js'; +export * from './schemas/index.js'; \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/page-header.ts b/api-gateway/src/middlewares/validation/page-header.ts new file mode 100644 index 0000000000..1c0dcd6799 --- /dev/null +++ b/api-gateway/src/middlewares/validation/page-header.ts @@ -0,0 +1,8 @@ +export const pageHeader = { + 'X-Total-Count': { + schema: { + type: 'integer', + }, + description: 'Total items in the collection.', + }, +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/accounts.ts b/api-gateway/src/middlewares/validation/schemas/accounts.ts index 24cdff8eab..0827eeffdd 100644 --- a/api-gateway/src/middlewares/validation/schemas/accounts.ts +++ b/api-gateway/src/middlewares/validation/schemas/accounts.ts @@ -5,6 +5,7 @@ import { UserRole } from '@guardian/interfaces'; import { Expose } from 'class-transformer'; import { ApiProperty } from '@nestjs/swagger'; import { Match } from '../../../helpers/decorators/match.validator.js'; +import { PolicyDTO } from './policies.dto.js'; export class AccountsResponseDTO { @ApiProperty() @@ -20,7 +21,7 @@ export class AccountsResponseDTO { @ApiProperty() @IsString() @Expose() - did: string + did?: string } export class AccountsSessionResponseDTO { @@ -142,56 +143,6 @@ export class VcDocumentDTO { proof: ProofDTO; } -export class PolicyDTO { - @ApiProperty() - _id: string; - - @ApiProperty() - createDate: Date; - - @ApiProperty() - uuid: string; - - @ApiProperty() - name: string; - - @ApiProperty() - description: string; - - @ApiProperty() - status: string; - - @ApiProperty() - creator: string; - - @ApiProperty() - owner: string; - - @ApiProperty() - topicId: string; - - @ApiProperty() - policyTag: string; - - @ApiProperty() - codeVersion: string; - - @ApiProperty() - userRoles: string[]; - - @ApiProperty() - userGroups: Object[]; - - @ApiProperty() - userRole: string; - - @ApiProperty() - userGroup: string; - - @ApiProperty() - id: string; -} - export class AggregatedDTOItem { @ApiProperty() did: string; @@ -208,7 +159,7 @@ export class AggregatedDTOItem { export type AggregatedDTO = AggregatedDTOItem[] -export class UserDTO { +class UserDTO { @ApiProperty() username: string; diff --git a/api-gateway/src/middlewares/validation/schemas/analytics.dto.ts b/api-gateway/src/middlewares/validation/schemas/analytics.dto.ts new file mode 100644 index 0000000000..b7628a9f08 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/analytics.dto.ts @@ -0,0 +1,219 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsArray, IsString, Validate, IsOptional, IsObject } from 'class-validator'; +import { Examples } from '../examples.js'; +import { IsNumberOrString } from '../string-or-number.js'; + +class Options { + @ApiProperty({ + oneOf: [ + { type: 'string' }, + { type: 'number' }, + ], + enum: [0, 1], + example: 0 + }) + @IsOptional() + @Validate(IsNumberOrString) + idLvl?: number | string; + + @ApiProperty({ + oneOf: [ + { type: 'string' }, + { type: 'number' }, + ], + enum: [0, 1], + example: 0 + }) + @IsOptional() + @Validate(IsNumberOrString) + eventsLvl?: number | string; + + @ApiProperty({ + oneOf: [ + { type: 'string' }, + { type: 'number' }, + ], + enum: [0, 1, 2], + example: 0 + }) + @IsOptional() + @Validate(IsNumberOrString) + propLvl?: number | string; + + @ApiProperty({ + oneOf: [ + { type: 'string' }, + { type: 'number' }, + ], + enum: [0, 1, 2], + example: 0 + }) + @IsOptional() + @Validate(IsNumberOrString) + childrenLvl?: number | string; +} + +export class FilterPoliciesDTO extends Options { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + policyId1?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + policyId2?: string; + + @ApiProperty({ + type: 'string', + isArray: true, + example: [ + Examples.DB_ID, + Examples.DB_ID + ] + }) + @IsOptional() + @IsArray() + policyIds?: string[]; +} + +export class FilterModulesDTO extends Options { + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DB_ID + }) + @IsString() + moduleId1: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DB_ID + }) + @IsString() + moduleId2: string; +} + +export class FilterSchemasDTO { + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DB_ID + }) + @IsString() + schemaId1: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DB_ID + }) + @IsString() + schemaId2: string; + + @ApiProperty({ + oneOf: [ + { type: 'string' }, + { type: 'number' }, + ], + enum: [0, 1], + example: 0 + }) + @IsOptional() + @Validate(IsNumberOrString) + idLvl?: number | string; +} + +export class FilterDocumentsDTO extends Options { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + documentId1?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + documentId2?: string; + + @ApiProperty({ + type: 'string', + isArray: true, + example: [ + Examples.DB_ID, + Examples.DB_ID + ] + }) + @IsOptional() + @IsArray() + documentIds?: string[]; +} + +export class FilterToolsDTO extends Options { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + toolId1?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + toolId2?: string; + + @ApiProperty({ + type: 'string', + isArray: true, + example: [ + Examples.DB_ID, + Examples.DB_ID + ] + }) + @IsOptional() + @IsArray() + toolIds?: string[]; +} + +export class FilterSearchPoliciesDTO { + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DB_ID + }) + @IsString() + policyId: string; +} + +export class FilterSearchBlocksDTO { + @ApiProperty({ + type: 'string', + required: true, + example: Examples.UUID + }) + @IsString() + id: string; + + @ApiProperty({ + type: 'object', + required: true + }) + @IsObject() + config: any; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/analytics.ts b/api-gateway/src/middlewares/validation/schemas/analytics.ts index f29528cfc1..89b8e6a567 100644 --- a/api-gateway/src/middlewares/validation/schemas/analytics.ts +++ b/api-gateway/src/middlewares/validation/schemas/analytics.ts @@ -1,5 +1,5 @@ import { ApiProperty } from '@nestjs/swagger'; -import { IsArray, IsObject, IsString, IsNumber } from 'class-validator'; +import { IsArray, IsObject, IsString } from 'class-validator'; import { Type } from 'class-transformer'; export class SearchPoliciesDTO { @@ -12,6 +12,41 @@ export class SearchPoliciesDTO { result: any; } +export class SearchBlocksDTO { + @ApiProperty() + @IsString() + name: string; + + @ApiProperty() + @IsString() + description: string; + + @ApiProperty() + @IsString() + version: string; + + @ApiProperty() + @IsString() + owner: string; + + @ApiProperty() + @IsString() + topicId: string; + + @ApiProperty() + @IsString() + messageId: string; + + @ApiProperty() + @IsString() + hash: string; + + @ApiProperty({ type: () => Object }) + @IsArray() + @Type(() => Object) + chains: any[]; +} + export class ComparePoliciesDTO { @ApiProperty() @IsObject() @@ -112,6 +147,16 @@ export class CompareDocumentsDTO { total: any; } +export class CompareDocumentsV2DTO { + @ApiProperty() + @IsObject() + projects: CompareDocumentsDTO; + + @ApiProperty() + @IsObject() + presentations: CompareDocumentsDTO; +} + export class CompareToolsDTO { @ApiProperty() @IsObject() @@ -140,111 +185,4 @@ export class CompareToolsDTO { @ApiProperty() @IsObject() total: any; -} - -export class FilterSearchPoliciesDTO { - @ApiProperty() - @IsString() - policyId: string; -} - -export class FilterPoliciesDTO { - @ApiProperty() - @IsString() - policyId1: string; - - @ApiProperty() - @IsString() - policyId2: string; - - @ApiProperty({ type: () => String }) - @IsArray() - @Type(() => String) - policyIds: string[]; - - @ApiProperty() - @IsNumber() - eventsLvl: number; - - @ApiProperty() - @IsNumber() - propLvl: number; - - @ApiProperty() - @IsNumber() - childrenLvl: number; - - @ApiProperty() - @IsNumber() - idLvl: number; -} - -export class FilterModulesDTO { - @ApiProperty() - @IsString() - moduleId1: string; - - @ApiProperty() - @IsString() - moduleId2: string; - - @ApiProperty() - @IsNumber() - eventsLvl: number; - - @ApiProperty() - @IsNumber() - propLvl: number; - - @ApiProperty() - @IsNumber() - childrenLvl: number; - - @ApiProperty() - @IsNumber() - idLvl: number; -} - -export class FilterSchemasDTO { - @ApiProperty() - @IsString() - schemaId1: string; - - @ApiProperty() - @IsString() - schemaId2: string; - - @ApiProperty() - @IsNumber() - idLvl: number; -} - -export class FilterDocumentsDTO { - @ApiProperty() - @IsString() - documentId1: string; - - @ApiProperty() - @IsString() - documentId2: string; - - @ApiProperty({ type: () => String }) - @IsArray() - @Type(() => String) - documentIds: string[]; -} - -export class FilterToolsDTO { - @ApiProperty() - @IsString() - toolId1: string; - - @ApiProperty() - @IsString() - toolId2: string; - - @ApiProperty({ type: () => String }) - @IsArray() - @Type(() => String) - toolIds: string[]; -} +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/blocks.ts b/api-gateway/src/middlewares/validation/schemas/blocks.ts new file mode 100644 index 0000000000..ef46df3678 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/blocks.ts @@ -0,0 +1,34 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class BlockDTO { + @ApiProperty({ type: 'string' }) + id: string; + + @ApiProperty({ type: 'string' }) + blockType: string; + + @ApiProperty({ type: () => BlockDTO, isArray: true }) + blocks: BlockDTO[]; +} + +export class BlockErrorsDTO { + @ApiProperty({ type: 'string' }) + id: string; + + @ApiProperty({ type: 'string' }) + name: string; + + @ApiProperty({ type: 'string', isArray: true }) + errors: string[]; + + @ApiProperty({ type: 'boolean' }) + isValid: boolean; +} + +export class ValidationErrorsDTO { + @ApiProperty({ type: () => BlockErrorsDTO, isArray: true, nullable: true }) + blocks?: BlockErrorsDTO[]; + + @ApiProperty({ type: 'string', isArray: true, nullable: true }) + errors?: string[]; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/branding.ts b/api-gateway/src/middlewares/validation/schemas/branding.ts new file mode 100644 index 0000000000..8eefd9d390 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/branding.ts @@ -0,0 +1,20 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class BrandingDTO { + @ApiProperty() + headerColor: string; + @ApiProperty() + primaryColor: string; + @ApiProperty() + companyName: string; + @ApiProperty() + companyLogoUrl: string; + @ApiProperty() + loginBannerUrl: string; + @ApiProperty() + faviconUrl: string; + @ApiProperty() + headerColor1: string; + @ApiProperty() + termsAndConditions: string; +} diff --git a/api-gateway/src/middlewares/validation/schemas/contracts.ts b/api-gateway/src/middlewares/validation/schemas/contracts.ts index 91b7ea5e64..d7ee104485 100644 --- a/api-gateway/src/middlewares/validation/schemas/contracts.ts +++ b/api-gateway/src/middlewares/validation/schemas/contracts.ts @@ -9,6 +9,13 @@ import { TokenType, } from '@guardian/interfaces'; +export class ContractConfigDTO { + @ApiProperty() + type: ContractType; + @ApiProperty() + description: string; +} + export class ContractDTO implements IContract { @ApiProperty({ required: true }) id: string; diff --git a/api-gateway/src/middlewares/validation/schemas/document.dto.ts b/api-gateway/src/middlewares/validation/schemas/document.dto.ts new file mode 100644 index 0000000000..da4964997d --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/document.dto.ts @@ -0,0 +1,109 @@ +import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; +import { Examples } from '../examples.js'; + +export class VpDTO { + @ApiProperty({ + type: 'string', + isArray: true + }) + '@context': string[]; + + @ApiProperty({ + type: 'string', + example: Examples.UUID + }) + id: string; + + @ApiProperty({ + type: 'string', + isArray: true + }) + type: string[]; + + @ApiProperty({ + type: 'object', + isArray: true + }) + verifiableCredential: any[]; + + @ApiProperty({ + type: 'object', + }) + proof?: any; +} + +@ApiExtraModels(VpDTO) +export class VpDocumentDTO { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + id?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + policyId?: string; + + @ApiProperty({ + type: 'string', + example: 'hash' + }) + hash?: string; + + @ApiProperty({ + type: 'number', + example: 0 + }) + signature?: number; + + @ApiProperty({ + type: 'string', + enum: [ + 'NEW', + 'ISSUE', + 'REVOKE', + 'SUSPEND', + 'RESUME', + 'FAILED' + ], + example: 'NEW' + }) + status?: string; + + @ApiProperty({ + type: 'string', + example: 'Block tag' + }) + tag?: string; + + @ApiProperty({ + type: 'string', + example: 'Document type' + }) + type?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DATE + }) + createDate?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DATE + }) + updateDate?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DID + }) + owner?: string; + + @ApiProperty({ + type: () => VpDTO, + }) + document?: VpDTO[]; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/documents.ts b/api-gateway/src/middlewares/validation/schemas/documents.ts new file mode 100644 index 0000000000..7d6fc7c5f2 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/documents.ts @@ -0,0 +1,35 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class VCDocumentDTO { + @ApiProperty({ type: 'string', nullable: false }) + id?: string; + + @ApiProperty({ type: 'string', isArray: true, required: true }) + '@context': string | string[]; + + @ApiProperty({ type: 'string', isArray: true, required: true }) + type: string[]; + + @ApiProperty({ type: 'object', isArray: true, required: true }) + credentialSubject: any | any[]; + + @ApiProperty({ type: 'object', required: true }) + issuer: any | string; + + @ApiProperty({ type: 'string', required: true }) + issuanceDate: string; + + @ApiProperty({ type: 'object', nullable: true }) + proof?: any; +} + +export class ExternalDocumentDTO { + @ApiProperty({ required: true }) + owner: string; + + @ApiProperty({ required: true }) + policyTag: string; + + @ApiProperty({ nullable: false, required: true, type: () => VCDocumentDTO }) + document: VCDocumentDTO; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/errors.ts b/api-gateway/src/middlewares/validation/schemas/errors.ts index 555109514e..a0b828075c 100644 --- a/api-gateway/src/middlewares/validation/schemas/errors.ts +++ b/api-gateway/src/middlewares/validation/schemas/errors.ts @@ -3,12 +3,20 @@ import { IsNumber, IsString } from 'class-validator'; import { Expose } from 'class-transformer'; export class InternalServerErrorDTO { - @ApiProperty() + @ApiProperty({ + type: 'number', + required: true, + example: 500 + }) @IsNumber() @Expose() code: number; - @ApiProperty() + @ApiProperty({ + type: 'string', + required: true, + example: 'Error message' + }) @IsString() @Expose() message: string; diff --git a/api-gateway/src/middlewares/validation/schemas/index.ts b/api-gateway/src/middlewares/validation/schemas/index.ts index 59ebd587cd..8fa5c7563c 100644 --- a/api-gateway/src/middlewares/validation/schemas/index.ts +++ b/api-gateway/src/middlewares/validation/schemas/index.ts @@ -3,11 +3,29 @@ export * from './artifacts.js' export * from './contracts.js' export * from './errors.js' export * from './notifications.js' -export * from './schemas.js' export * from './settings.js' export * from './suggestions.js' -export * from './task.js' -export * from './tool.js' +export * from './task.dto.js' +export * from './tool.dto.js' export * from './analytics.js' export * from './demo.js' export * from './profiles.js' +export * from './branding.js' +export * from './documents.js' +export * from './logs.js' +export * from './modules.js' +export * from './messages.js' +export * from './blocks.js' +export * from './policies.js' +export * from './record.js' +export * from './projects.js' +export * from './analytics.dto.js' +export * from './tag.dto.js' +export * from './theme.dto.js' +export * from './token.dto.js' +export * from './document.dto.js' +export * from './wizard.dto.js' +export * from './permissions.dto.js' +export * from './schemas.dto.js' +export * from './policies.dto.js' +export * from './profiles.dto.js' \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/logs.ts b/api-gateway/src/middlewares/validation/schemas/logs.ts new file mode 100644 index 0000000000..d1a5ed9374 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/logs.ts @@ -0,0 +1,35 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class LogFilterDTO { + @ApiProperty({ type: 'string', nullable: true }) + type?: string; + + @ApiProperty({ type: 'string', nullable: true }) + startDate?: string; + + @ApiProperty({ type: 'string', nullable: true }) + endDate?: string; + + @ApiProperty({ type: 'string', isArray: true, nullable: true }) + attributes?: string[]; + + @ApiProperty({ type: 'string', nullable: true }) + message?: string; + + @ApiProperty({ type: 'number', nullable: true }) + pageSize?: number; + + @ApiProperty({ type: 'number', nullable: true }) + pageIndex?: number; + + @ApiProperty({ type: 'string', nullable: true }) + sortDirection?: string; +} + +export class LogResultDTO { + @ApiProperty({ type: 'number' }) + totalCount: number; + + @ApiProperty({ type: 'object', isArray: true }) + logs?: any[]; +} diff --git a/api-gateway/src/middlewares/validation/schemas/messages.ts b/api-gateway/src/middlewares/validation/schemas/messages.ts new file mode 100644 index 0000000000..f87fe7406b --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/messages.ts @@ -0,0 +1,26 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class ExportMessageDTO { + @ApiProperty({ type: 'string' }) + uuid: string; + + @ApiProperty({ type: 'string' }) + name: string; + + @ApiProperty({ type: 'string' }) + description: string; + + @ApiProperty({ type: 'string' }) + messageId: string; + + @ApiProperty({ type: 'string' }) + owner: string; +} + +export class ImportMessageDTO { + @ApiProperty({ type: 'string' }) + messageId: string; + + @ApiProperty({ type: 'object', nullable: true }) + metadata?: any +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/modules.ts b/api-gateway/src/middlewares/validation/schemas/modules.ts new file mode 100644 index 0000000000..5924371013 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/modules.ts @@ -0,0 +1,68 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { ValidationErrorsDTO } from './blocks.js'; + +export class ModuleDTO { + @ApiProperty({ type: 'string', nullable: false }) + id?: string; + + @ApiProperty({ type: 'string', nullable: false }) + uuid?: string; + + @ApiProperty({ type: 'string', nullable: false }) + type?: string; + + @ApiProperty({ type: 'string', nullable: false }) + name?: string; + + @ApiProperty({ type: 'string', nullable: false }) + description?: string; + + @ApiProperty({ type: 'string', nullable: false }) + status?: string; + + @ApiProperty({ type: 'string', nullable: false }) + creator?: string; + + @ApiProperty({ type: 'string', nullable: false }) + owner?: string; + + @ApiProperty({ type: 'string', nullable: false }) + topicId?: string; + + @ApiProperty({ type: 'string', nullable: false }) + messageId?: string; + + @ApiProperty({ type: 'string', nullable: false }) + codeVersion?: string; + + @ApiProperty({ type: 'string', nullable: false }) + createDate?: string; + + @ApiProperty({ type: 'object', nullable: true }) + config?: any; +} + +export class ModulePreviewDTO { + @ApiProperty({ nullable: false, required: true, type: () => ModuleDTO }) + module: ModuleDTO; + + @ApiProperty({ type: 'string', required: true }) + messageId: string; + + @ApiProperty({ type: 'object', isArray: true, nullable: true }) + schemas?: any[]; + + @ApiProperty({ type: 'object', isArray: true, nullable: true }) + tags?: any[]; + + @ApiProperty({ type: 'string', nullable: true }) + moduleTopicId?: string; +} + +export class ModuleValidationDTO { + @ApiProperty({ nullable: false, required: true, type: () => ModuleDTO }) + module: ModuleDTO; + + @ApiProperty({ nullable: false, required: true, type: () => ValidationErrorsDTO }) + results: ValidationErrorsDTO; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/permissions.dto.ts b/api-gateway/src/middlewares/validation/schemas/permissions.dto.ts new file mode 100644 index 0000000000..b4d5f810ab --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/permissions.dto.ts @@ -0,0 +1,112 @@ +import { Examples } from '#middlewares'; +import { PermissionCategories, Permissions, PermissionsArray, PermissionEntities, PermissionActions } from '@guardian/interfaces'; +import { ApiProperty } from '@nestjs/swagger'; +import { IsArray, IsBoolean } from 'class-validator'; + +const permission = PermissionsArray.filter((p) => !p.disabled)[0]; +const permissions = PermissionsArray.filter((p) => !p.disabled).map((p) => p.name); + +export class PermissionsDTO { + @ApiProperty({ + type: 'string', + required: true, + enum: permissions, + example: permission.name + }) + name: string; + + @ApiProperty({ + type: 'string', + required: true, + enum: PermissionCategories, + example: permission.category + }) + category: string; + + @ApiProperty({ + type: 'string', + required: true, + enum: PermissionEntities, + example: permission.entity + }) + entity: string; + + @ApiProperty({ + type: 'string', + required: true, + enum: PermissionActions, + example: permission.action + }) + action: string; + + @ApiProperty({ + type: 'boolean', + required: true, + example: permission.disabled + }) + disabled: boolean; + + @ApiProperty({ + type: 'string', + isArray: true, + example: [Permissions.POLICIES_POLICY_READ] + }) + dependOn?: string[]; +} + +export class RoleDTO { + @ApiProperty({ + type: 'string', + required: true, + example: Examples.UUID + }) + uuid: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Name' + }) + name: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Description' + }) + description: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DID + }) + owner: string; + + @ApiProperty({ + type: 'string', + required: true, + enum: permissions, + example: [Permissions.POLICIES_POLICY_READ] + }) + permissions: string[]; +} + +export class AssignPolicyDTO { + @ApiProperty({ + type: 'string', + required: true, + isArray: true, + example: [Examples.DB_ID] + }) + @IsArray() + policyIds: string[]; + + @ApiProperty({ + type: 'boolean', + required: true, + example: true + }) + @IsBoolean() + assign: boolean; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/policies.dto.ts b/api-gateway/src/middlewares/validation/schemas/policies.dto.ts new file mode 100644 index 0000000000..48600714a6 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/policies.dto.ts @@ -0,0 +1,374 @@ +import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; +import { IsArray, IsBoolean, IsObject, IsOptional, IsString } from 'class-validator'; +import { PolicyType } from '@guardian/interfaces'; +import { Examples } from '../examples.js'; +import { ValidationErrorsDTO } from './blocks.js'; + +export class PolicyDTO { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + id?: string; + + @ApiProperty({ + type: 'string', + example: Examples.UUID + }) + @IsOptional() + @IsString() + uuid?: string; + + @ApiProperty({ + type: 'string', + example: 'Policy name' + }) + @IsOptional() + @IsString() + name?: string; + + @ApiProperty({ + type: 'string', + example: 'Description' + }) + @IsOptional() + @IsString() + description?: string; + + @ApiProperty({ + type: 'string', + example: 'Description' + }) + @IsOptional() + @IsString() + topicDescription?: string; + + @ApiProperty({ + type: 'string', + example: 'Tag' + }) + @IsOptional() + @IsString() + policyTag?: string; + + @ApiProperty({ + type: 'string', + enum: PolicyType, + example: PolicyType.DRAFT + }) + @IsOptional() + @IsString() + status?: PolicyType; + + @ApiProperty({ + type: 'string', + example: Examples.DID + }) + @IsOptional() + @IsString() + creator?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DID + }) + @IsOptional() + @IsString() + owner?: string; + + @ApiProperty({ + type: 'string', + example: Examples.ACCOUNT_ID + }) + @IsOptional() + @IsString() + topicId?: string; + + @ApiProperty({ + type: 'string', + example: Examples.MESSAGE_ID + }) + @IsOptional() + @IsString() + messageId?: string; + + @ApiProperty({ + type: 'string', + example: '1.0.0' + }) + @IsOptional() + @IsString() + codeVersion?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DATE + }) + @IsOptional() + @IsString() + createDate?: string; + + @ApiProperty({ + type: 'string', + example: '1.0.0' + }) + @IsOptional() + @IsString() + version?: string; + + @ApiProperty({ + type: 'object', + }) + @IsOptional() + @IsObject() + config?: any; + + @ApiProperty({ + type: 'string', + example: 'Installer' + }) + @IsOptional() + @IsString() + userRole?: string; + + @ApiProperty({ + type: 'string', + isArray: true, + example: ['Installer'] + }) + @IsOptional() + @IsArray() + userRoles?: string[]; + + @ApiProperty({ + type: 'object', + example: { + uuid: Examples.UUID, + role: 'Installer', + groupLabel: 'Label', + groupName: 'Name', + active: true + } + }) + @IsOptional() + @IsObject() + userGroup?: any; + + @ApiProperty({ + type: 'object', + isArray: true, + example: [{ + uuid: Examples.UUID, + role: 'Installer', + groupLabel: 'Label', + groupName: 'Name', + active: true + }] + }) + @IsOptional() + @IsArray() + userGroups?: any[]; + + @ApiProperty({ + type: 'string', + isArray: true, + example: ['Registrant'] + }) + @IsOptional() + @IsArray() + policyRoles?: string[]; + + @ApiProperty({ + type: 'object', + isArray: true, + example: [{ + role: 'Registrant', + steps: [{ + block: 'Block tag', + level: 1, + name: 'Step name' + }] + }] + }) + @IsOptional() + @IsArray() + policyNavigation?: any[]; + + @ApiProperty({ + type: 'object', + isArray: true, + example: [{ + name: 'Project', + description: 'Project', + memoObj: 'topic', + static: false, + type: 'any' + }] + }) + @IsOptional() + @IsArray() + policyTopics?: any[]; + + @ApiProperty({ + type: 'object', + isArray: true, + example: [{ + tokenName: 'Token name', + tokenSymbol: 'Token symbol', + tokenType: 'non-fungible', + decimals: '', + changeSupply: true, + enableAdmin: true, + enableFreeze: true, + enableKYC: true, + enableWipe: true, + templateTokenTag: 'token_template_0' + }] + }) + @IsOptional() + @IsArray() + policyTokens?: any[]; + + @ApiProperty({ + type: 'object', + isArray: true, + example: [{ + name: 'Group name', + creator: 'Registrant', + groupAccessType: 'Private', + groupRelationshipType: 'Multiple', + members: ['Registrant'] + }] + }) + @IsOptional() + @IsArray() + policyGroups?: any[]; + + @ApiProperty({ + type: 'string', + isArray: true + }) + @IsOptional() + @IsArray() + categories?: string[]; + + @ApiProperty({ + type: 'string', + example: Examples.UUID + }) + @IsOptional() + @IsString() + projectSchema?: string; +} + +@ApiExtraModels(PolicyDTO) +export class PolicyPreviewDTO { + @ApiProperty({ + type: () => PolicyDTO, + required: true + }) + @IsObject() + module: PolicyDTO; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.MESSAGE_ID + }) + @IsString() + messageId: string; + + @ApiProperty({ + type: 'object', + isArray: true + }) + @IsOptional() + @IsArray() + schemas?: any[]; + + @ApiProperty({ + type: 'object', + isArray: true + }) + @IsOptional() + @IsArray() + tags?: any[]; + + @ApiProperty({ + type: 'string', + example: Examples.ACCOUNT_ID + }) + @IsOptional() + @IsString() + moduleTopicId?: string; +} + +@ApiExtraModels(PolicyDTO) +export class PolicyValidationDTO { + @ApiProperty({ + type: () => PolicyDTO, + required: true + }) + @IsObject() + policy: PolicyDTO; + + @ApiProperty({ + type: () => ValidationErrorsDTO, + required: true + }) + @IsObject() + results: ValidationErrorsDTO; +} + +@ApiExtraModels(PolicyDTO) +export class PoliciesValidationDTO { + @ApiProperty({ + type: () => PolicyDTO, + isArray: true, + required: true + }) + @IsArray() + policies: PolicyDTO[]; + + @ApiProperty({ + type: 'string', + required: true + }) + @IsBoolean() + isValid: boolean; + + @ApiProperty({ + type: () => ValidationErrorsDTO, + required: true + }) + @IsObject() + errors: ValidationErrorsDTO; +} + +export class PolicyCategoryDTO { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + id?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Large-Scale' + }) + @IsString() + name: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'PROJECT_SCALE' + }) + @IsString() + type: string; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/policies.ts b/api-gateway/src/middlewares/validation/schemas/policies.ts index f8b8c5eacf..5c208f5493 100644 --- a/api-gateway/src/middlewares/validation/schemas/policies.ts +++ b/api-gateway/src/middlewares/validation/schemas/policies.ts @@ -1,16 +1,5 @@ import { ApiProperty } from '@nestjs/swagger'; -export class PolicyCategoryDTO { - @ApiProperty() - id: string; - - @ApiProperty() - name: string; - - @ApiProperty() - type: string; -} - /** * Migration config policies DTO */ diff --git a/api-gateway/src/middlewares/validation/schemas/profiles.dto.ts b/api-gateway/src/middlewares/validation/schemas/profiles.dto.ts new file mode 100644 index 0000000000..3d75e4b930 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/profiles.dto.ts @@ -0,0 +1,126 @@ +import { Examples } from '#middlewares'; +import { Permissions, UserRole, IUser } from '@guardian/interfaces'; +import { ApiProperty } from '@nestjs/swagger'; +import { IsArray, IsBoolean, IsObject, IsOptional, IsString } from 'class-validator'; + +export class UserDTO implements IUser { + @ApiProperty({ + type: 'string', + required: true, + example: 'username' + }) + @IsString() + username: string; + + @ApiProperty({ + type: 'string', + required: true, + enum: UserRole, + example: UserRole.USER + }) + @IsString() + role: UserRole; + + @ApiProperty({ + type: 'string', + required: false, + isArray: true, + example: [{ + + }] + }) + @IsArray() + permissionsGroup: any[]; + + @ApiProperty({ + type: 'string', + required: true, + isArray: true, + example: [Permissions.POLICIES_POLICY_READ] + }) + @IsArray() + permissions: string[]; + + @ApiProperty({ + type: 'string', + required: false, + example: Examples.DID + }) + @IsOptional() + @IsString() + did?: string; + + @ApiProperty({ + type: 'string', + required: false, + example: Examples.DID + }) + @IsOptional() + @IsString() + parent?: string; + + @ApiProperty({ + type: 'string', + required: false, + example: Examples.ACCOUNT_ID + }) + @IsOptional() + @IsString() + hederaAccountId?: string; +} + +export class ProfileDTO extends UserDTO { + @ApiProperty({ + type: 'boolean', + required: false, + example: true + }) + @IsOptional() + @IsBoolean() + confirmed?: boolean; + + @ApiProperty({ + type: 'boolean', + required: false, + example: true + }) + @IsOptional() + @IsBoolean() + failed?: boolean; + + @ApiProperty({ + type: 'string', + required: false, + example: Examples.ACCOUNT_ID + }) + @IsOptional() + @IsString() + topicId?: string; + + @ApiProperty({ + type: 'string', + required: false, + example: Examples.ACCOUNT_ID + }) + @IsOptional() + @IsString() + parentTopicId?: string; + + @ApiProperty({ + type: 'object', + nullable: true, + required: false + }) + @IsOptional() + @IsObject() + didDocument?: any; + + @ApiProperty({ + type: 'object', + nullable: true, + required: false + }) + @IsOptional() + @IsObject() + vcDocument?: any; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/profiles.ts b/api-gateway/src/middlewares/validation/schemas/profiles.ts index 5cdc8e7a20..a8f5b093e9 100644 --- a/api-gateway/src/middlewares/validation/schemas/profiles.ts +++ b/api-gateway/src/middlewares/validation/schemas/profiles.ts @@ -86,41 +86,6 @@ export class DidKeyStatusDTO { valid: boolean; } -export class ProfileDTO { - @ApiProperty({ type: 'string', nullable: false, required: true }) - username: string; - - @ApiProperty({ type: 'string', nullable: false, required: true }) - role: string; - - @ApiProperty({ type: 'string', nullable: true, required: false }) - did?: string; - - @ApiProperty({ type: 'string', nullable: true, required: false }) - parent?: string; - - @ApiProperty({ type: 'string', nullable: true, required: false }) - hederaAccountId?: string; - - @ApiProperty({ type: 'boolean', nullable: true, required: false }) - confirmed?: boolean; - - @ApiProperty({ type: 'boolean', nullable: true, required: false }) - failed?: boolean; - - @ApiProperty({ type: 'string', nullable: true, required: false }) - topicId?: string; - - @ApiProperty({ type: 'string', nullable: true, required: false }) - parentTopicId?: string; - - @ApiProperty({ type: 'object', nullable: true, required: false }) - didDocument?: any; - - @ApiProperty({ type: 'object', nullable: true, required: false }) - vcDocument?: any; -} - export class CredentialsDTO { @ApiProperty({ type: 'string', nullable: false, required: true }) entity: string; diff --git a/api-gateway/src/middlewares/validation/schemas/schemas.dto.ts b/api-gateway/src/middlewares/validation/schemas/schemas.dto.ts new file mode 100644 index 0000000000..8bb84303f7 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/schemas.dto.ts @@ -0,0 +1,231 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsIn, IsNotEmpty, IsObject, IsOptional, IsString } from 'class-validator'; +import { SchemaCategory, SchemaEntity, SchemaStatus, UserRole } from '@guardian/interfaces'; +import { Examples } from '../examples.js'; + +export class SchemaDTO { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + @IsOptional() + @IsString() + id?: string; + + @ApiProperty({ + type: 'string', + example: Examples.UUID + }) + @IsOptional() + @IsString() + uuid?: string; + + @ApiProperty({ + type: 'string', + example: 'Schema name' + }) + @IsOptional() + @IsString() + name?: string; + + @ApiProperty({ + type: 'string', + example: 'Description' + }) + @IsOptional() + @IsString() + description?: string; + + @ApiProperty({ + type: 'string', + enum: SchemaEntity, + example: SchemaEntity.POLICY + }) + @IsOptional() + @IsString() + entity?: SchemaEntity; + + @ApiProperty({ + type: 'string', + example: Examples.UUID + }) + @IsOptional() + @IsString() + iri?: string; + + @ApiProperty({ + type: 'string', + enum: SchemaStatus, + example: SchemaStatus.DRAFT + }) + @IsOptional() + @IsString() + status?: SchemaStatus; + + @ApiProperty({ + type: 'string', + example: Examples.ACCOUNT_ID + }) + @IsOptional() + @IsString() + topicId?: string; + + @ApiProperty({ + type: 'string', + example: '1.0.0' + }) + @IsOptional() + @IsString() + version?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DID + }) + @IsOptional() + @IsString() + owner?: string; + + @ApiProperty({ + type: 'string', + example: Examples.MESSAGE_ID + }) + @IsOptional() + @IsString() + messageId?: string; + + @ApiProperty({ + type: 'string', + enum: SchemaCategory, + example: SchemaCategory.POLICY + }) + @IsOptional() + @IsString() + category?: SchemaCategory; + + @ApiProperty({ + type: 'string', + example: Examples.IPFS + }) + @IsOptional() + @IsString() + documentURL?: string; + + @ApiProperty({ + type: 'string', + example: Examples.IPFS + }) + @IsOptional() + @IsString() + contextURL?: string; + + @ApiProperty({ + type: 'object', + }) + @IsOptional() + @IsObject() + document?: any; + + @ApiProperty({ + type: 'object', + }) + @IsOptional() + @IsObject() + context?: any; +} + +export class SystemSchemaDTO { + @ApiProperty({ + type: 'string', + example: 'Schema name' + }) + @IsString() + @IsNotEmpty() + name: string; + + @ApiProperty({ + type: 'string', + enum: [UserRole.STANDARD_REGISTRY, UserRole.USER], + example: SchemaEntity.STANDARD_REGISTRY + }) + @IsString() + @IsNotEmpty() + @IsIn([UserRole.STANDARD_REGISTRY, UserRole.USER]) + entity: string; + + [key: string]: any; +} + +export class ExportSchemaDTO { + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DB_ID + }) + @IsString() + @IsNotEmpty() + id: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Schema name' + }) + @IsString() + @IsNotEmpty() + name: string; + + @ApiProperty({ + type: 'string', + example: 'Description' + }) + @IsOptional() + @IsString() + description?: string; + + @ApiProperty({ + type: 'string', + example: '1.0.0' + }) + @IsOptional() + @IsString() + version?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DID + }) + @IsOptional() + @IsString() + owner?: string; + + @ApiProperty({ + type: 'string', + example: Examples.MESSAGE_ID + }) + @IsOptional() + @IsString() + messageId?: string; +} + +export class VersionSchemaDTO { + @ApiProperty({ + type: 'string', + required: true, + example: '1.0.0' + }) + @IsString() + @IsNotEmpty() + version: string; +} + +export class MessageSchemaDTO { + @ApiProperty({ + type: 'string', + required: true, + example: Examples.MESSAGE_ID + }) + @IsString() + @IsNotEmpty() + messageId: string; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/schemas.ts b/api-gateway/src/middlewares/validation/schemas/schemas.ts deleted file mode 100644 index 6a551612ea..0000000000 --- a/api-gateway/src/middlewares/validation/schemas/schemas.ts +++ /dev/null @@ -1,138 +0,0 @@ -import * as yup from 'yup'; -import fieldsValidation from '../fields-validation.js' -import { ApiProperty } from '@nestjs/swagger'; -import { IsIn, IsNotEmpty, IsString } from 'class-validator'; -import { UserRole } from '@guardian/interfaces'; - -export const schemaSchema = () => { - const { messageId } = fieldsValidation - return yup.object({ - body: yup.object({ - messageId - }), - }); -} - -export const systemEntitySchema = () => { - const { name, entity } = fieldsValidation - return yup.object({ - body: yup.object({ - name, entity - }), - }); -} - -export class SystemSchemaDTO { - @ApiProperty() - @IsString() - @IsNotEmpty() - name: string; - - @ApiProperty() - @IsString() - @IsNotEmpty() - @IsIn([UserRole.STANDARD_REGISTRY, UserRole.USER]) - entity: string; - - [key: string]: any -} - -export class SchemaDTO { - @ApiProperty() - @IsString() - @IsNotEmpty() - id: string; - - @ApiProperty() - @IsString() - @IsNotEmpty() - name: string; - - @ApiProperty() - @IsString() - description: string; - - @ApiProperty() - @IsString() - @IsNotEmpty() - entity: string; - - @ApiProperty() - @IsString() - @IsNotEmpty() - document: string; - - @ApiProperty() - @IsString() - uuid: string; - - @ApiProperty() - @IsString() - iri: string; - - @ApiProperty() - @IsString() - hash: string; - - @ApiProperty() - @IsString() - status: string; - - @ApiProperty() - @IsString() - topicId: string; - - @ApiProperty() - @IsString() - version: string; - - @ApiProperty() - @IsString() - owner: string; - - @ApiProperty() - @IsString() - messageId: string; -} - -export class ExportSchemaDTO { - @ApiProperty() - @IsString() - @IsNotEmpty() - id: string; - - @ApiProperty() - @IsString() - @IsNotEmpty() - name: string; - - @ApiProperty() - @IsString() - description: string; - - @ApiProperty() - @IsString() - version: string; - - @ApiProperty() - @IsString() - owner: string; - - @ApiProperty() - @IsString() - messageId: string; -} - -export class VersionSchemaDTO { - @ApiProperty() - @IsString() - @IsNotEmpty() - version: string; -} - -export class MessageSchemaDTO { - @ApiProperty() - @IsString() - @IsNotEmpty() - messageId: string; -} diff --git a/api-gateway/src/middlewares/validation/schemas/settings.ts b/api-gateway/src/middlewares/validation/schemas/settings.ts index c008922b00..176ed74bbd 100644 --- a/api-gateway/src/middlewares/validation/schemas/settings.ts +++ b/api-gateway/src/middlewares/validation/schemas/settings.ts @@ -1,10 +1,10 @@ -import fieldsValidation from '../../../middlewares/validation/fields-validation.js'; +import fieldsValidation from '../../validation/fields-validation.js'; import * as yup from 'yup'; import { ApiProperty } from '@nestjs/swagger'; import { IsNotEmpty, IsString } from 'class-validator'; export const updateSettings = () => { - const {ipfsStorageApiKey, operatorId, operatorKey} = fieldsValidation; + const { ipfsStorageApiKey, operatorId, operatorKey } = fieldsValidation; return yup.object({ body: yup.object({ ipfsStorageApiKey, diff --git a/api-gateway/src/middlewares/validation/schemas/tag.dto.ts b/api-gateway/src/middlewares/validation/schemas/tag.dto.ts new file mode 100644 index 0000000000..23c6bb1ba4 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/tag.dto.ts @@ -0,0 +1,182 @@ +import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; +import { Examples } from '../examples.js'; + +export class TagDTO { + @ApiProperty({ + type: 'string', + example: Examples.UUID + }) + uuid?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Tag label' + }) + name: string; + + @ApiProperty({ + type: 'string', + example: 'Description' + }) + description?: string; + + @ApiProperty({ + type: 'string', + example: 'DID' + }) + owner?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DATE + }) + date?: string; + + @ApiProperty({ + type: 'string', + required: true, + enum: [ + 'Schema', + 'Policy', + 'Token', + 'Module', + 'Contract', + 'PolicyDocument' + ], + example: 'PolicyDocument' + }) + entity: string; + + @ApiProperty({ + type: 'string', + enum: [ + 'Draft', + 'Published', + 'History' + ], + example: 'Published' + }) + status?: string; + + @ApiProperty({ + type: 'string', + enum: [ + 'Create', + 'Delete' + ], + example: 'Create' + }) + operation?: string; + + @ApiProperty({ + type: 'string', + example: Examples.ACCOUNT_ID + }) + topicId?: string; + + @ApiProperty({ + type: 'string', + example: Examples.MESSAGE_ID + }) + messageId?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + policyId?: string; + + @ApiProperty({ + type: 'string', + example: Examples.IPFS + }) + uri?: string; + + @ApiProperty({ + type: 'string', + example: Examples.MESSAGE_ID + }) + target?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DB_ID + }) + localTarget: string; + + @ApiProperty({ + type: 'object' + }) + document?: any; +} + +@ApiExtraModels(TagDTO) +export class TagMapDTO { + @ApiProperty({ + type: 'string', + required: true, + enum: [ + 'Schema', + 'Policy', + 'Token', + 'Module', + 'Contract', + 'PolicyDocument' + ], + example: 'PolicyDocument' + }) + entity: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.MESSAGE_ID + }) + target: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DATE + }) + refreshDate: string; + + @ApiProperty({ + type: () => TagDTO, + required: true, + isArray: true, + }) + tags: TagDTO[]; +} + +export class TagFilterDTO { + @ApiProperty({ + type: 'string', + required: true, + enum: [ + 'Schema', + 'Policy', + 'Token', + 'Module', + 'Contract', + 'PolicyDocument' + ], + example: 'PolicyDocument' + }) + entity: string; + + @ApiProperty({ + type: 'string', + example: Examples.MESSAGE_ID + }) + target?: string; + + @ApiProperty({ + type: 'string', + isArray: true, + example: Examples.MESSAGE_ID + }) + targets?: string[]; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/task.dto.ts b/api-gateway/src/middlewares/validation/schemas/task.dto.ts new file mode 100644 index 0000000000..f90f3e9df8 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/task.dto.ts @@ -0,0 +1,88 @@ +import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; +import { Examples } from '../examples.js'; + +export class TaskDTO { + @ApiProperty({ + type: 'string', + description: 'Task Id', + example: Examples.UUID + }) + taskId: string; + + @ApiProperty({ + type: 'number', + description: 'Expected count of task phases', + example: 0 + }) + expectation: number; +} + +export class StatusDTO { + @ApiProperty({ + type: 'string', + description: 'Text', + }) + message: string; + + @ApiProperty({ + type: 'string', + description: 'Type', + enum: [ + 'Processing', + 'Completed', + 'Info' + ], + example: 'Info' + }) + type: string; +} + +@ApiExtraModels(StatusDTO) +export class TaskStatusDTO { + @ApiProperty({ + type: 'string', + description: 'Task type', + example: 'Create policy' + }) + action: string; + + @ApiProperty({ + type: 'string', + description: 'User Id', + example: Examples.DID + }) + userId: string; + + @ApiProperty({ + type: 'number', + description: 'Expected count of task phases', + example: 0 + }) + expectation: number; + + @ApiProperty({ + type: 'string', + description: 'Task Id', + example: Examples.UUID + }) + taskId: string; + + @ApiProperty({ + type: 'string', + description: 'Date', + example: Examples.DATE + }) + date: string; + + @ApiProperty({ + type: () => StatusDTO, + isArray: true, + }) + statuses: StatusDTO[]; + + @ApiProperty({ type: 'object' }) + result: any; + + @ApiProperty({ type: 'object' }) + error: any; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/theme.dto.ts b/api-gateway/src/middlewares/validation/schemas/theme.dto.ts new file mode 100644 index 0000000000..583e312378 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/theme.dto.ts @@ -0,0 +1,110 @@ +import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; +import { Examples } from '../examples.js'; + +export class ThemeRoleDTO { + @ApiProperty({ + type: 'string', + example: 'Description' + }) + description?: string; + + @ApiProperty({ + type: 'string', + description: 'Text color', + pattern: '(^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$)', + required: true, + example: Examples.COLOR + }) + text: string; + + @ApiProperty({ + type: 'string', + description: 'Background color', + pattern: '(^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$)', + required: true, + example: Examples.COLOR + }) + background: string; + + @ApiProperty({ + type: 'string', + description: 'Border color', + pattern: '(^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$)', + required: true, + example: Examples.COLOR + }) + border: string; + + @ApiProperty({ + type: 'string', + description: 'Object shape', + enum: ['0', '1', '2', '3', '4', '5'], + required: true, + example: '0' + }) + shape: string; + + @ApiProperty({ + type: 'string', + description: 'Border width', + enum: ['0px', '1px', '2px', '3px', '4px', '5px', '6px', '7px'], + required: true, + example: '2px' + }) + borderWidth: string; + + @ApiProperty({ + type: 'string', + description: 'Filter by type', + enum: ['type', 'api', 'role'], + required: true, + example: 'type' + }) + filterType: string; + + @ApiProperty({ + required: true, + oneOf: [ + { + type: 'string', + }, + { + type: 'array', + items: { + type: 'string', + } + }, + ], + }) + filterValue: string | string[] +} + +@ApiExtraModels(ThemeRoleDTO) +export class ThemeDTO { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + id?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.UUID + }) + uuid: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Theme name' + }) + name: string; + + @ApiProperty({ + type: () => ThemeRoleDTO, + required: true, + isArray: true, + }) + rules: ThemeRoleDTO[]; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/token.dto.ts b/api-gateway/src/middlewares/validation/schemas/token.dto.ts new file mode 100644 index 0000000000..3f6ca80cc6 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/token.dto.ts @@ -0,0 +1,195 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { Examples } from '../examples.js'; + +export class TokenDTO { + @ApiProperty({ + type: 'string', + example: Examples.ACCOUNT_ID + }) + tokenId?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Token name' + }) + tokenName?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Token symbol' + }) + tokenSymbol?: string; + + @ApiProperty({ + type: 'string', + enum: ['fungible', 'non-fungible'], + required: true, + example: 'non-fungible' + }) + tokenType?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: '0' + }) + initialSupply?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: '0' + }) + decimals?: string; + + @ApiProperty({ + type: 'boolean', + description: 'Add Supply key', + required: true, + example: true + }) + changeSupply?: boolean; + + @ApiProperty({ + type: 'boolean', + description: 'Add Admin key', + required: true, + example: true + }) + enableAdmin?: boolean; + + @ApiProperty({ + type: 'boolean', + description: 'Add Freeze key', + required: true, + example: true + }) + enableFreeze?: boolean; + + @ApiProperty({ + type: 'boolean', + description: 'Add KYC key', + required: true, + example: true + }) + enableKYC?: boolean; + + @ApiProperty({ + type: 'boolean', + description: 'Add Wipe key', + required: true, + example: true + }) + enableWipe?: boolean; +} + +export class TokenInfoDTO { + @ApiProperty({ + type: 'string', + required: true, + example: Examples.DB_ID + }) + id: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.ACCOUNT_ID + }) + tokenId?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Token name' + }) + tokenName?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Token symbol' + }) + tokenSymbol?: string; + + @ApiProperty({ + type: 'string', + enum: ['fungible', 'non-fungible'], + required: true, + example: 'non-fungible' + }) + tokenType?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: '0' + }) + decimals?: string; + + @ApiProperty({ + type: 'boolean', + description: '', + required: true, + example: true + }) + associated: boolean; + + @ApiProperty({ + type: 'boolean', + description: '', + required: true, + example: true + }) + frozen: boolean; + + @ApiProperty({ + type: 'boolean', + description: '', + required: true, + example: true + }) + kyc: boolean; + + @ApiProperty({ + type: 'string', + description: 'User balance', + required: true, + example: '0' + }) + balance: string; + + @ApiProperty({ + type: 'boolean', + description: 'There is an Admin key', + required: true, + example: true + }) + enableAdmin?: boolean; + + @ApiProperty({ + type: 'boolean', + description: 'There is an Freeze key', + required: true, + example: true + }) + enableFreeze?: boolean; + + @ApiProperty({ + type: 'boolean', + description: 'There is an KYC key', + required: true, + example: true + }) + enableKYC?: boolean; + + @ApiProperty({ + type: 'boolean', + description: 'There is an Wipe key', + required: true, + example: true + }) + enableWipe?: boolean; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/schemas/tool.dto.ts b/api-gateway/src/middlewares/validation/schemas/tool.dto.ts new file mode 100644 index 0000000000..2d934af4d4 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/tool.dto.ts @@ -0,0 +1,124 @@ +import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; +import { Examples } from '../examples.js'; +import { BlockDTO, ValidationErrorsDTO } from './blocks.js'; + +@ApiExtraModels(BlockDTO) +export class ToolDTO { + @ApiProperty({ + type: 'string', + example: Examples.DB_ID + }) + id?: string; + + @ApiProperty({ + type: 'string', + required: true, + example: Examples.UUID + }) + uuid: string; + + @ApiProperty({ + type: 'string', + required: true, + example: 'Tool name' + }) + name: string; + + @ApiProperty({ + type: 'string', + example: 'Description' + }) + description?: string; + + @ApiProperty({ + type: 'string', + enum: [ + 'DRAFT', + 'PUBLISHED', + 'PUBLISH_ERROR' + ], + example: 'NEW' + }) + status?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DID + }) + creator?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DID + }) + owner?: string; + + @ApiProperty({ + type: 'string', + example: Examples.ACCOUNT_ID + }) + topicId?: string; + + @ApiProperty({ + type: 'string', + example: Examples.MESSAGE_ID + }) + messageId?: string; + + @ApiProperty({ + type: 'string', + example: '1.0.0' + }) + codeVersion?: string; + + @ApiProperty({ + type: 'string', + example: Examples.DATE + }) + createDate?: string; + + @ApiProperty({ + type: () => BlockDTO, + required: true, + }) + config: BlockDTO; +} + +@ApiExtraModels(ToolDTO) +export class ToolPreviewDTO { + @ApiProperty({ + type: () => ToolDTO + }) + tool: ToolDTO; + + @ApiProperty({ + type: 'object', + isArray: true, + }) + schemas?: any[]; + + @ApiProperty({ + type: 'object', + isArray: true, + }) + tags?: any[]; + + @ApiProperty({ + type: () => ToolDTO, + isArray: true + }) + tools: ToolDTO[]; +} + +@ApiExtraModels(ToolDTO, ValidationErrorsDTO) +export class ToolValidationDTO { + @ApiProperty({ + type: () => ToolDTO + }) + tool: ToolDTO; + + @ApiProperty({ + type: () => ValidationErrorsDTO + }) + results: ValidationErrorsDTO; +} diff --git a/api-gateway/src/middlewares/validation/schemas/tool.ts b/api-gateway/src/middlewares/validation/schemas/tool.ts deleted file mode 100644 index d921811a88..0000000000 --- a/api-gateway/src/middlewares/validation/schemas/tool.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { ApiProperty } from '@nestjs/swagger'; -import { IsNotEmpty, IsObject, IsString } from 'class-validator'; - -export class ToolDTO { - @ApiProperty() - @IsString() - @IsNotEmpty() - id: string; - - @ApiProperty() - @IsString() - uuid: string; - - @ApiProperty() - @IsString() - @IsNotEmpty() - name: string; - - @ApiProperty() - @IsString() - description: string; - - @ApiProperty() - @IsObject() - config: any; - - @ApiProperty() - @IsString() - status: string; - - @ApiProperty() - @IsString() - creator: string; - - @ApiProperty() - @IsString() - owner: string; - - @ApiProperty() - @IsString() - topicId: string; - - @ApiProperty() - @IsString() - messageId: string; - - @ApiProperty() - @IsString() - codeVersion: string; - - @ApiProperty() - @IsString() - createDate: string; -} diff --git a/api-gateway/src/middlewares/validation/schemas/wizard.dto.ts b/api-gateway/src/middlewares/validation/schemas/wizard.dto.ts new file mode 100644 index 0000000000..c5fa4ce5f1 --- /dev/null +++ b/api-gateway/src/middlewares/validation/schemas/wizard.dto.ts @@ -0,0 +1,169 @@ +import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; +import { PolicyDTO } from './policies.dto.js'; + +export class WizardConfigDTO { + @ApiProperty({ + type: 'string', + required: true, + isArray: true, + }) + roles: string[]; + + @ApiProperty({ + type: 'string', + properties: { + name: { + type: 'string' + }, + description: { + type: 'string' + }, + topicDescription: { + type: 'string' + }, + policyTag: { + type: 'string' + } + }, + required: true, + }) + policy: any; + + @ApiProperty({ + type: 'string', + properties: { + name: { + type: 'string' + }, + iri: { + type: 'string' + }, + isApproveEnable: { + type: 'boolean' + }, + isMintSchema: { + type: 'boolean' + }, + mintOptions: { + type: 'object', + properties: { + tokenId: { + type: 'string' + }, + rule: { + type: 'string' + } + } + }, + dependencySchemaIri: { + type: 'string' + }, + relationshipsSchemaIri: { + type: 'string' + }, + initialRolesFor: { + type: 'array', + items: { + type: 'string' + } + }, + rolesConfig: { + type: 'array', + items: { + type: 'object', + properties: { + role: { + type: 'string' + }, + isApprover: { + type: 'boolean' + }, + isCreator: { + type: 'boolean' + }, + gridColumns: { + type: 'array', + items: { + type: 'object', + properties: { + field: { + type: 'string' + }, + title: { + type: 'string' + } + } + } + } + } + } + } + }, + required: true, + isArray: true + }) + schemas: any[]; + + @ApiProperty({ + type: 'string', + properties: { + role: { + type: 'string' + }, + mintSchemaIri: { + type: 'string' + }, + viewOnlyOwnDocuments: { + type: 'boolean' + } + }, + required: true, + isArray: true + }) + trustChain: any[]; +} + +@ApiExtraModels(WizardConfigDTO) +export class WizardConfigAsyncDTO { + @ApiProperty({ + type: 'boolean', + required: true, + }) + saveState: boolean; + + @ApiProperty({ + type: () => WizardConfigDTO, + required: true, + }) + wizardConfig: WizardConfigDTO; +} + +@ApiExtraModels(WizardConfigDTO) +export class WizardResultDTO { + @ApiProperty({ + type: 'string', + required: true, + }) + policyId: string; + + @ApiProperty({ + type: () => WizardConfigDTO, + required: true, + }) + wizardConfig: WizardConfigDTO; +} + +@ApiExtraModels(PolicyDTO) +export class WizardPreviewDTO { + @ApiProperty({ + type: () => PolicyDTO, + required: true, + }) + policyConfig: PolicyDTO; + + @ApiProperty({ + type: () => WizardConfigDTO, + required: true, + }) + wizardConfig: WizardConfigDTO; +} \ No newline at end of file diff --git a/api-gateway/src/middlewares/validation/string-or-number.ts b/api-gateway/src/middlewares/validation/string-or-number.ts new file mode 100644 index 0000000000..151bb2e13c --- /dev/null +++ b/api-gateway/src/middlewares/validation/string-or-number.ts @@ -0,0 +1,12 @@ +import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator'; + +@ValidatorConstraint({ name: 'string-or-number', async: false }) +export class IsNumberOrString implements ValidatorConstraintInterface { + validate(text: any, args: ValidationArguments) { + return typeof text === 'number' || typeof text === 'string'; + } + + defaultMessage(args: ValidationArguments) { + return '($value) must be number or string'; + } +} \ No newline at end of file diff --git a/api-gateway/src/old-descriptions.ts b/api-gateway/src/old-descriptions.ts index be8de5f8f7..fc3569ca2f 100644 --- a/api-gateway/src/old-descriptions.ts +++ b/api-gateway/src/old-descriptions.ts @@ -8,7 +8,7 @@ export const SwaggerPaths = { 'description': 'Returns all schemas.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns all schemas.', @@ -91,7 +91,7 @@ export const SwaggerPaths = { 'description': 'Returns schema by schema ID.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns schema by schema ID.', @@ -161,7 +161,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Create new schema.', @@ -205,7 +205,7 @@ export const SwaggerPaths = { 'description': 'Returns all schemas by topicId.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns all schemas by topicId.', @@ -303,7 +303,7 @@ export const SwaggerPaths = { 'description': 'Creates new schema. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Create new schema.', @@ -384,7 +384,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Publishes the schema.', @@ -445,7 +445,7 @@ export const SwaggerPaths = { 'description': 'Publishes the schema with the provided (internal) schema ID onto IPFS, sends a message featuring IPFS CID into the corresponding Hedera topic. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Publishes the schema with the provided (internal) schema ID onto IPFS, sends a message featuring IPFS CID into the corresponding Hedera topic.', @@ -525,7 +525,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Updates the schema.', @@ -590,7 +590,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Deletes the schema.', @@ -652,7 +652,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new schema from a zip file.', @@ -709,7 +709,7 @@ export const SwaggerPaths = { 'description': 'Imports new schema from a zip file into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new schema from a zip file.', @@ -797,7 +797,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new schema from IPFS.', @@ -858,7 +858,7 @@ export const SwaggerPaths = { 'description': 'Imports new schema from IPFS into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new schema from IPFS.', @@ -933,7 +933,7 @@ export const SwaggerPaths = { 'description': 'Previews the schema from IPFS without loading it into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Schema preview from IPFS.', @@ -994,7 +994,7 @@ export const SwaggerPaths = { 'description': 'Previews the schema from IPFS without loading it into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Schema preview from IPFS.', @@ -1052,7 +1052,7 @@ export const SwaggerPaths = { 'description': 'Previews the schema from a zip file. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Schema preview from a zip file.', @@ -1109,7 +1109,7 @@ export const SwaggerPaths = { 'description': 'Returns Hedera message IDs of the published schemas, these messages contain IPFS CIDs of these schema files. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'List Hedera message IDs of published schemas.', @@ -1162,7 +1162,7 @@ export const SwaggerPaths = { 'description': 'Returns schema files for the schemas. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return zip file with schemas.', @@ -1219,7 +1219,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns schema by type.', @@ -1272,7 +1272,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates new system schema.', @@ -1316,7 +1316,7 @@ export const SwaggerPaths = { 'description': 'Returns all system schemas by username. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns all system schemas by username.', @@ -1419,7 +1419,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Updates the schema.', @@ -1484,7 +1484,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Deletes the schema.', @@ -1540,7 +1540,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Publishes the schema.', @@ -1620,7 +1620,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns schema by schema type.', @@ -1662,7 +1662,7 @@ export const SwaggerPaths = { 'description': 'Returns all tokens. For the Standard Registry role it returns only the list of tokens, for other users it also returns token balances as well as the KYC, Freeze, and Association statuses. Not allowed for the Auditor role.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return a list of tokens.', @@ -1720,7 +1720,7 @@ export const SwaggerPaths = { 'description': 'Creates a new token. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates a new token.', @@ -1801,7 +1801,7 @@ export const SwaggerPaths = { 'description': 'Creates a new token. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates a new token.', @@ -1854,7 +1854,7 @@ export const SwaggerPaths = { 'description': 'Returns user information for the selected token. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'parameters': [ @@ -1936,7 +1936,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Associates the user with the provided Hedera token.', @@ -1971,7 +1971,7 @@ export const SwaggerPaths = { 'description': 'Associates the user with the provided Hedera token. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Associates the user with the provided Hedera token.', @@ -2035,7 +2035,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Associate the user with the provided Hedera token.', @@ -2070,7 +2070,7 @@ export const SwaggerPaths = { 'description': 'Disassociates the user with the provided Hedera token. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Disassociates the user with the provided Hedera token.', @@ -2143,7 +2143,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Sets the KYC flag for the user.', @@ -2195,7 +2195,7 @@ export const SwaggerPaths = { 'description': 'Sets the KYC flag for the user. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Sets the KYC flag for the user.', @@ -2277,7 +2277,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Unsets the KYC flag for the user.', @@ -2329,7 +2329,7 @@ export const SwaggerPaths = { 'description': 'Unsets the KYC flag for the user. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Unsets the KYC flag for the user.', @@ -2411,7 +2411,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Freeze transfers of the specified token for the user.', @@ -2463,7 +2463,7 @@ export const SwaggerPaths = { 'description': 'Freezes transfers of the specified token for the user. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Freeze transfers of the specified token for the user.', @@ -2545,7 +2545,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Unfreezes transfers of the specified token for the user.', @@ -2597,7 +2597,7 @@ export const SwaggerPaths = { 'description': 'Unfreezes transfers of the specified token for the user. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Unfreezes transfers of the specified token for the user.', @@ -2659,7 +2659,7 @@ export const SwaggerPaths = { 'description': 'Requests all VP documents. Only users with the Auditor role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns a list of all VP documents.', @@ -2769,7 +2769,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns a trustchain for a VP document.', @@ -2811,7 +2811,7 @@ export const SwaggerPaths = { 'description': 'Returns all policies. Only users with the Standard Registry and Installer role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return a list of all policies.', @@ -2907,7 +2907,7 @@ export const SwaggerPaths = { 'description': 'Creates a new policy. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates a new policy.', @@ -2953,7 +2953,7 @@ export const SwaggerPaths = { 'description': 'Creates a new policy. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates a new policy.', @@ -3018,7 +3018,7 @@ export const SwaggerPaths = { 'summary': 'Retrieves policy configuration.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3095,7 +3095,7 @@ export const SwaggerPaths = { }, 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3164,7 +3164,7 @@ export const SwaggerPaths = { 'summary': 'Publishes the policy onto IPFS.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3205,7 +3205,7 @@ export const SwaggerPaths = { 'description': 'Publishes the policy with the specified (internal) policy ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera topic. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Publishes the policy with the specified (internal) policy ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera topic.', @@ -3274,7 +3274,7 @@ export const SwaggerPaths = { 'description': 'Validates selected policy. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Validates policy.', @@ -3339,7 +3339,7 @@ export const SwaggerPaths = { 'summary': 'Returns a list of groups the user is a member of.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3429,7 +3429,7 @@ export const SwaggerPaths = { }, 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3475,7 +3475,7 @@ export const SwaggerPaths = { 'summary': 'Retrieves data for the policy root block.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3537,7 +3537,7 @@ export const SwaggerPaths = { 'summary': 'Requests block data.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3608,7 +3608,7 @@ export const SwaggerPaths = { }, 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3663,7 +3663,7 @@ export const SwaggerPaths = { 'summary': 'Requests block ID from a policy by tag.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -3720,7 +3720,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return Heder message ID for the specified published policy.', @@ -3773,7 +3773,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return policy and its artifacts in a zip file format for the specified policy.', @@ -3831,7 +3831,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new policy from IPFS.', @@ -3892,7 +3892,7 @@ export const SwaggerPaths = { 'description': 'Imports new policy and all associated artifacts from IPFS into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new policy and all associated artifacts from IPFS into the local DB.', @@ -3966,7 +3966,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new policy from a zip file.', @@ -4023,7 +4023,7 @@ export const SwaggerPaths = { 'description': 'Imports new policy and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new policy and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB.', @@ -4078,7 +4078,7 @@ export const SwaggerPaths = { 'summary': 'Policy preview from IPFS.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -4135,7 +4135,7 @@ export const SwaggerPaths = { 'description': 'Previews the policy from IPFS without loading it into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Previews the policy from IPFS without loading it into the local DB.', @@ -4194,7 +4194,7 @@ export const SwaggerPaths = { 'summary': 'Policy preview from a zip file.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -4247,7 +4247,7 @@ export const SwaggerPaths = { 'description': 'Run policy without making any persistent changes or executing transaction. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Dry Run policy.', @@ -4300,7 +4300,7 @@ export const SwaggerPaths = { 'description': 'Return policy to editing. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return policy to editing.', @@ -4353,7 +4353,7 @@ export const SwaggerPaths = { 'description': 'Returns all virtual users. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns all virtual users.', @@ -4417,7 +4417,7 @@ export const SwaggerPaths = { 'description': 'Create a new virtual account. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Create a new virtual account.', @@ -4481,7 +4481,7 @@ export const SwaggerPaths = { 'description': 'Logs virtual user into the system. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Logs virtual user into the system.', @@ -4561,7 +4561,7 @@ export const SwaggerPaths = { 'description': 'Restarts the execution of the policy. Clear data in database. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Restarts the execution of the policy.', @@ -4607,7 +4607,7 @@ export const SwaggerPaths = { 'description': 'Returns lists of virtual transactions. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns lists of virtual transactions.', @@ -4674,7 +4674,7 @@ export const SwaggerPaths = { 'description': 'Returns lists of virtual artifacts. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns lists of virtual artifacts.', @@ -4741,7 +4741,7 @@ export const SwaggerPaths = { 'description': 'Returns lists of virtual artifacts. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns lists of virtual artifacts.', @@ -4808,7 +4808,7 @@ export const SwaggerPaths = { 'description': 'Sends data to the specified block.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Sends data to the specified block.', @@ -4879,7 +4879,7 @@ export const SwaggerPaths = { 'description': 'Requests block data by tag. Only users with a role that described in block are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Requests block data.', @@ -4941,7 +4941,7 @@ export const SwaggerPaths = { 'description': 'Creates a link between the current policy and the main policy. Or creates a group making the current policy the main one.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates Multi policy config.', @@ -5015,7 +5015,7 @@ export const SwaggerPaths = { 'description': 'Requests Multi policy config.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Requests Multi policy config.', @@ -5103,7 +5103,7 @@ export const SwaggerPaths = { 'description': 'Generates a new Hedera account with a random private key.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -5144,7 +5144,7 @@ export const SwaggerPaths = { 'description': 'Generates a new Hedera account with a random private key.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Generates a new Hedera account with a random private key.', @@ -5198,7 +5198,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -5250,7 +5250,7 @@ export const SwaggerPaths = { }, 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -5289,7 +5289,7 @@ export const SwaggerPaths = { 'description': 'Returns current settings. For users with the Standard Registry role only.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns current settings.', @@ -5329,7 +5329,7 @@ export const SwaggerPaths = { 'description': 'Set settings. For users with the Standard Registry role only.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Set settings.', @@ -5364,7 +5364,7 @@ export const SwaggerPaths = { 'description': 'Returns current environment name.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns current environment name.', @@ -5401,7 +5401,7 @@ export const SwaggerPaths = { 'description': 'Returns logs. For users with the Standard Registry role only.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -5482,7 +5482,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns logs attributes.', @@ -5527,7 +5527,7 @@ export const SwaggerPaths = { 'description': 'Returns task statuses by Id.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns task statuses.', @@ -5580,7 +5580,7 @@ export const SwaggerPaths = { 'description': 'Returns all artifacts.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns all artifacts.', @@ -5671,7 +5671,7 @@ export const SwaggerPaths = { 'description': 'Upload artifact. For users with the Standard Registry role only.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -5745,7 +5745,7 @@ export const SwaggerPaths = { 'description': 'Delete artifact.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Delete artifact.', @@ -5799,7 +5799,7 @@ export const SwaggerPaths = { 'description': 'Returns all artifacts.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns all artifacts.', @@ -5891,7 +5891,7 @@ export const SwaggerPaths = { 'description': 'Upload artifact. For users with the Standard Registry role only.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -5966,7 +5966,7 @@ export const SwaggerPaths = { 'description': 'Delete artifact.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Delete artifact.', @@ -6019,7 +6019,7 @@ export const SwaggerPaths = { 'description': 'Returns all modules. Only users with the Standard Registry and Installer role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return a list of all modules.', @@ -6097,7 +6097,7 @@ export const SwaggerPaths = { 'description': 'Creates a new module. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates a new module.', @@ -6143,7 +6143,7 @@ export const SwaggerPaths = { 'description': 'Returns modules menu. Only users with the Standard Registry and Installer role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return a list of modules.', @@ -6200,7 +6200,7 @@ export const SwaggerPaths = { 'summary': 'Retrieves module configuration.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -6262,7 +6262,7 @@ export const SwaggerPaths = { }, 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -6312,7 +6312,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Deletes the module.', @@ -6366,7 +6366,7 @@ export const SwaggerPaths = { 'summary': 'Publishes the module onto IPFS.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -6418,7 +6418,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return Heder message ID for the specified published module.', @@ -6471,7 +6471,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return module and its artifacts in a zip file format for the specified module.', @@ -6506,7 +6506,7 @@ export const SwaggerPaths = { 'description': 'Imports new module and all associated artifacts from IPFS into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new module from IPFS.', @@ -6564,7 +6564,7 @@ export const SwaggerPaths = { 'description': 'Imports new module and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new module from a zip file.', @@ -6619,7 +6619,7 @@ export const SwaggerPaths = { 'summary': 'Module preview from IPFS.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -6677,7 +6677,7 @@ export const SwaggerPaths = { 'summary': 'Module preview from a zip file.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -6730,7 +6730,7 @@ export const SwaggerPaths = { 'description': 'Validates selected module. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Validates module.', @@ -6783,7 +6783,7 @@ export const SwaggerPaths = { 'description': 'Returns map api key.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns map api key.', @@ -6822,7 +6822,7 @@ export const SwaggerPaths = { 'description': 'Creates new tag.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates new tag.', @@ -6885,7 +6885,7 @@ export const SwaggerPaths = { 'description': 'Search tags.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -7013,7 +7013,7 @@ export const SwaggerPaths = { 'description': 'Delete tag.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Delete tag.', @@ -7067,7 +7067,7 @@ export const SwaggerPaths = { 'description': 'synchronization.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'requestBody': { @@ -7142,7 +7142,7 @@ export const SwaggerPaths = { 'description': 'Returns all schema.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns all schemas.', @@ -7223,7 +7223,7 @@ export const SwaggerPaths = { 'description': 'Creates new schema. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates new schema.', @@ -7276,7 +7276,7 @@ export const SwaggerPaths = { 'description': 'Deletes the schema with the provided schema ID. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Delete the schema.', @@ -7338,7 +7338,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Updates the schema.', @@ -7405,7 +7405,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Publishes the schema.', @@ -7450,7 +7450,7 @@ export const SwaggerPaths = { 'description': 'Return a list of all published schemas.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return a list of all published schemas.', @@ -7495,7 +7495,7 @@ export const SwaggerPaths = { 'description': 'Returns all themes.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Return a list of all themes.', @@ -7538,7 +7538,7 @@ export const SwaggerPaths = { 'description': 'Creates a new theme.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates a new theme.', @@ -7607,7 +7607,7 @@ export const SwaggerPaths = { }, 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'responses': { @@ -7657,7 +7657,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Deletes the theme.', @@ -7710,7 +7710,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Returns a zip file containing the theme.', @@ -7745,7 +7745,7 @@ export const SwaggerPaths = { 'description': 'Imports new theme from the provided zip file into the local DB.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Imports new theme from a zip file.', @@ -7799,7 +7799,7 @@ export const SwaggerPaths = { 'description': 'Creates a new policy by wizard. Only users with the Standard Registry role are allowed to make the request.', 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Creates a new policy.', @@ -7871,7 +7871,7 @@ export const SwaggerPaths = { ], 'security': [ { - 'bearerAuth': [] + 'bearer': [] } ], 'summary': 'Get policy config.', diff --git a/api-gateway/tsconfig.json b/api-gateway/tsconfig.json index 66cdbc5a22..fbc4b19101 100644 --- a/api-gateway/tsconfig.json +++ b/api-gateway/tsconfig.json @@ -1,28 +1,39 @@ { - "compileOnSave": true, - "compilerOptions": { - "baseUrl": "./src", - "declaration": true, - "emitDecoratorMetadata": true, - "esModuleInterop": true, - "experimentalDecorators": true, - "inlineSourceMap": true, - "skipLibCheck": true, - "lib": [ - "es5", - "es6" + "compileOnSave": true, + "compilerOptions": { + "baseUrl": "./src", + "declaration": true, + "emitDecoratorMetadata": true, + "esModuleInterop": true, + "experimentalDecorators": true, + "inlineSourceMap": true, + "skipLibCheck": true, + "lib": [ + "es5", + "es6" + ], + "module": "ESNext", + "moduleResolution": "node", + "outDir": "dist/", + "target": "es2022", + "paths": { + "#middlewares": [ + "middlewares/index.js" + ], + "#helpers": [ + "helpers/index.js" + ], + "#auth": [ + "auth/index.js" + ] + } + }, + "exclude": [ + "node_modules", + "public", + "dist" ], - "module": "ESNext", - "moduleResolution": "node", - "outDir": "dist/", - "target": "es2022" - }, - "exclude": [ - "node_modules", - "public", - "dist" - ], - "include": [ - "src/**/*" - ] -} + "include": [ + "src/**/*" + ] +} \ No newline at end of file diff --git a/api-gateway/tsconfig.production.json b/api-gateway/tsconfig.production.json index 2411af62cd..6c2d748783 100644 --- a/api-gateway/tsconfig.production.json +++ b/api-gateway/tsconfig.production.json @@ -1,28 +1,39 @@ { - "compileOnSave": true, - "compilerOptions": { - "baseUrl": "./src", - "declaration": true, - "emitDecoratorMetadata": true, - "esModuleInterop": true, - "experimentalDecorators": true, - "inlineSourceMap": false, - "skipLibCheck": true, - "lib": [ - "es5", - "es6" + "compileOnSave": true, + "compilerOptions": { + "baseUrl": "./src", + "declaration": true, + "emitDecoratorMetadata": true, + "esModuleInterop": true, + "experimentalDecorators": true, + "inlineSourceMap": false, + "skipLibCheck": true, + "lib": [ + "es5", + "es6" + ], + "module": "ESNext", + "moduleResolution": "node", + "outDir": "dist/", + "target": "es2022", + "paths": { + "#middlewares": [ + "middlewares/index.js" + ], + "#helpers": [ + "helpers/index.js" + ], + "#auth": [ + "auth/index.js" + ] + } + }, + "exclude": [ + "node_modules", + "public", + "dist" ], - "module": "ESNext", - "moduleResolution": "node", - "outDir": "dist/", - "target": "es2022" - }, - "exclude": [ - "node_modules", - "public", - "dist" - ], - "include": [ - "src/**/*" - ] -} + "include": [ + "src/**/*" + ] +} \ No newline at end of file diff --git a/api-tests/package.json b/api-tests/package.json index 332689805f..f77de614ac 100644 --- a/api-tests/package.json +++ b/api-tests/package.json @@ -1,6 +1,6 @@ { "name": "api-tests", - "version": "2.24.1", + "version": "2.25.0", "description": "API Tests", "main": "index.js", "type": "module", diff --git a/application-events/package.json b/application-events/package.json index 84201d63a7..7da1e51b83 100644 --- a/application-events/package.json +++ b/application-events/package.json @@ -23,18 +23,13 @@ "dependencies": { "@guardian/common": "^2.13.0", "@guardian/interfaces": "^2.13.0", - "@mikro-orm/core": "^6.1.11", - "@mikro-orm/mongodb": "^6.1.11", - "@mikro-orm/reflection": "^6.1.11", "@types/express": "^4.17.17", - "@types/mongoose": "^5.11.97", "@types/morgan": "^1.9.4", "axios": "^1.3.4", "dotenv": "^16.0.0", "express": "^4.17.3", "http-errors": "^2.0.0", "js-yaml": "^4.1.0", - "mikro-orm": "^6.1.11", "mongodb": "6.5.0", "mongoose": "^6.10.0", "morgan": "^1.10.0", diff --git a/application-events/src/routes/webooks.ts b/application-events/src/routes/webooks.ts index f290028d52..c63e5319c9 100644 --- a/application-events/src/routes/webooks.ts +++ b/application-events/src/routes/webooks.ts @@ -10,65 +10,65 @@ const dbConnection = new MongodbAdapter(); const webhookService = new WebhookService(dbConnection); webhookRoutes.post('/api/webhooks', validate(storeWebhookSchema()), async (req: Request, res: Response, next: NextFunction) => { - try { - const webhook = new Webhook(); - webhook.url = req.body?.url; - webhook.events = req.body?.events || []; - await webhookService.saveWebhook(webhook); - return res.status(201).send({ id: webhook._id }); - } catch (e) { - return next(e); - } + try { + const webhook = new Webhook(); + webhook.url = req.body?.url; + webhook.events = req.body?.events || []; + await webhookService.saveWebhook(webhook); + return res.status(201).send({ id: webhook._id }); + } catch (e) { + return next(e); + } }); webhookRoutes.get('/api/webhooks', async (req: Request, res: Response, next: NextFunction) => { - try { - const webhooks = await webhookService.getWebhooks(); - return res.json(webhooks); - } catch (e) { - return next(e); - } + try { + const webhooks = await webhookService.getWebhooks(); + return res.json(webhooks); + } catch (e) { + return next(e); + } }); webhookRoutes.delete('/api/webhooks/:id', async (req: Request, res: Response, next: NextFunction) => { - const { id } = req.params; - try { - await webhookService.removeWebhook(id); - return res.sendStatus(204); - } catch (err: any) { - return next(err); - } + const { id } = req.params; + try { + await webhookService.removeWebhook(id); + return res.sendStatus(204); + } catch (err: any) { + return next(err); + } }); webhookRoutes.get('/api/webhooks/:id', async (req: Request, res: Response, next: NextFunction) => { - const { id } = req.params; - try { - const webhook = await webhookService.findWebhook(id); - if (!webhook) { - return res.status(404).send('Webhook not found'); + const { id } = req.params; + try { + const webhook = await webhookService.findWebhook(id); + if (!webhook) { + return res.status(404).send('Webhook not found'); + } + return res.json(webhook); + } catch (err: any) { + return next(err); } - return res.json(webhook); - } catch (err: any) { - return next(err); - } }); webhookRoutes.put('/api/webhooks/:id', validate(updateWebhookSchema()), async ( - req: Request, res: Response, next: NextFunction + req: Request, res: Response, next: NextFunction ) => { - const { id } = req.params; - try { - const webhook = await webhookService.findWebhook(id); - if (!webhook) { - return res.status(404).send('Webhook not found'); + const { id } = req.params; + try { + const webhook = await webhookService.findWebhook(id); + if (!webhook) { + return res.status(404).send('Webhook not found'); + } + webhook.url = req.body?.url; + webhook.events = req.body?.events; + await webhookService.saveWebhook(webhook); + return res.sendStatus(204); + } catch (err: any) { + return next(err); } - webhook.url = req.body?.url; - webhook.events = req.body?.events; - await webhookService.saveWebhook(webhook); - return res.sendStatus(204); - } catch (err: any) { - return next(err); - } }); export default webhookRoutes diff --git a/auth-service/package.json b/auth-service/package.json index 7f9ae5bbf0..427fcbce40 100644 --- a/auth-service/package.json +++ b/auth-service/package.json @@ -10,11 +10,11 @@ "image-size": "1.0.2" }, "dependencies": { - "@guardian/common": "^2.24.1", - "@guardian/interfaces": "^2.24.1", + "@guardian/common": "^2.25.0", + "@guardian/interfaces": "^2.25.0", "@meeco/cryppo": "^2.0.2", - "@mikro-orm/core": "^6.1.11", - "@mikro-orm/mongodb": "^6.1.11", + "@mikro-orm/core": "6.2.2", + "@mikro-orm/mongodb": "6.2.2", "@nestjs/common": "^9.4.1", "@nestjs/core": "^9.4.1", "@nestjs/microservices": "^9.4.1", @@ -75,5 +75,5 @@ "test": "mocha tests/**/*.test.js --reporter mocha-junit-reporter --reporter-options mochaFile=../test_results/ui-service.xml" }, "type": "module", - "version": "2.24.1" + "version": "2.25.0" } diff --git a/auth-service/src/api/account-service.ts b/auth-service/src/api/account-service.ts index 5152232042..d8cfc4db56 100644 --- a/auth-service/src/api/account-service.ts +++ b/auth-service/src/api/account-service.ts @@ -2,11 +2,14 @@ import { IAuthUser } from './auth.interface.js'; import pkg from 'jsonwebtoken'; import { User } from '../entity/user.js'; +import { DynamicRole } from '../entity/dynamic-role.js'; import * as util from 'util'; import crypto from 'crypto'; import { DataBaseHelper, Logger, MessageError, MessageResponse, NatsService, ProviderAuthUser, SecretManager, Singleton } from '@guardian/common'; import { + AuditDefaultPermission, AuthEvents, + OldRoles, GenerateUUIDv4, IGenerateTokenMessage, IGenerateTokenResponse, @@ -23,11 +26,68 @@ import { IStandardRegistryUserResponse, IUpdateUserMessage, IUser, + SRDefaultPermission, + UserDefaultPermission, UserRole } from '@guardian/interfaces'; +import { USER_REQUIRED_PROPS } from '../constants/index.js'; const { sign, verify } = pkg; +export function setDefaultPermissions(user: User): User { + if (user) { + if (user.role === UserRole.STANDARD_REGISTRY) { + user.permissions = SRDefaultPermission; + } else if (user.role === UserRole.AUDITOR) { + user.permissions = AuditDefaultPermission; + } else if (user.role === UserRole.USER) { + if (user.permissionsGroup && user.permissionsGroup.length) { + user.permissions = [ + ...UserDefaultPermission, + ...user.permissions + ]; + } else { + user.permissions = OldRoles; + } + } else { + user.permissions = UserDefaultPermission; + } + } + return user; +} + +export async function createNewUser( + username: string, + password: string, + role: UserRole, + walletToken: string, + parent: string, + did: string, + provider: string, + providerId: string +): Promise { + const defaultRole = await new DataBaseHelper(DynamicRole).findOne({ + owner: null, + default: true, + readonly: true + }); + const permissionsGroup = defaultRole ? [defaultRole.id] : []; + const permissions = defaultRole ? defaultRole.permissions : []; + const user = (new DataBaseHelper(User)).create({ + username, + password, + role, + walletToken, + parent, + did, + provider, + providerId, + permissionsGroup, + permissions + }); + return await (new DataBaseHelper(User)).save(user); +} + /** * Account service */ @@ -49,183 +109,158 @@ export class AccountService extends NatsService { * Register listeners */ registerListeners(): void { - this.getMessages(AuthEvents.GET_USER_BY_TOKEN, async (msg) => { + + /** + * Get user by access token + * @param token - access token + */ + this.getMessages(AuthEvents.GET_USER_BY_TOKEN, async (msg: any) => { const { token } = msg; const secretManager = SecretManager.New(); - - const {ACCESS_TOKEN_SECRET} = await secretManager.getSecrets('secretkey/auth') - + const { ACCESS_TOKEN_SECRET } = await secretManager.getSecrets('secretkey/auth') try { const decryptedToken = await util.promisify(verify)(token, ACCESS_TOKEN_SECRET, {}); if (Date.now() > decryptedToken.expireAt) { throw new Error('Token expired'); } + const user = await new DataBaseHelper(User).findOne({ username: decryptedToken.username }); - return new MessageResponse(user); + + const userRequiredProps = {} + + for (const prop of Object.values(USER_REQUIRED_PROPS)) { + userRequiredProps[prop] = user[prop]; + } + + return new MessageResponse(setDefaultPermissions(user)); } catch (error) { return new MessageError(error); } }); - this.getMessages(AuthEvents.REGISTER_NEW_USER, async (msg) => { + /** + * Get user by DID + * @param did - DID + */ + this.getMessages(AuthEvents.GET_USER_BY_ID, async (msg: any) => { + const { did } = msg; try { - const userRepository = new DataBaseHelper(User); - - const { username, password, role } = msg; - const passwordDigest = crypto.createHash('sha256').update(password).digest('hex'); - - const checkUserName = await userRepository.count({ username }); - if (checkUserName) { - return new MessageError('An account with the same name already exists.'); - } - - const user = userRepository.create({ - username, - password: passwordDigest, - role, - // walletToken: crypto.createHash('sha1').update(Math.random().toString()).digest('hex'), - walletToken: '', - parent: null, - did: null - }); - return new MessageResponse(await userRepository.save(user)); - + const user = await new DataBaseHelper(User).findOne({ did }) + return new MessageResponse(setDefaultPermissions(user)); } catch (error) { new Logger().error(error, ['AUTH_SERVICE']); - return new MessageError(error) + return new MessageError(error); } }); - this.getMessages(AuthEvents.GENERATE_NEW_TOKEN_BASED_ON_USER_PROVIDER, - async (msg: ProviderAuthUser) => { + /** + * Get user by username + * @param username - username + */ + this.getMessages(AuthEvents.GET_USER, async (msg: any) => { + const { username } = msg; try { - const userRepository = new DataBaseHelper(User); - let user = await userRepository.findOne({ - username: msg.username - }); - - if (!user) { - user = userRepository.create({ - username: msg.username, - password: null, - role: msg.role, - // walletToken: crypto.createHash('sha1').update(Math.random().toString()).digest('hex'), - walletToken: '', - parent: null, - did: null, - provider: msg.provider, - providerId: msg.providerId - }); - await userRepository.save(user); - } - const secretManager = SecretManager.New(); - const { ACCESS_TOKEN_SECRET } = await secretManager.getSecrets('secretkey/auth') - const accessToken = sign({ - username: user.username, - did: user.did, - role: user.role - }, ACCESS_TOKEN_SECRET); - return new MessageResponse({ - username: user.username, - did: user.did, - role: user.role, - accessToken - }) + const user = await new DataBaseHelper(User).findOne({ username }) + return new MessageResponse(setDefaultPermissions(user)); } catch (error) { new Logger().error(error, ['AUTH_SERVICE']); - return new MessageError(error) + return new MessageError(error); } }); - this.getMessages(AuthEvents.GENERATE_NEW_TOKEN, async (msg) => { + /** + * Get user by Hedera Account + * @param account - Hedera Account ID + */ + this.getMessages(AuthEvents.GET_USER_BY_ACCOUNT, async (msg: any) => { + const { account } = msg; try { - const { username, password } = msg; - const passwordDigest = crypto.createHash('sha256').update(password).digest('hex'); - - const secretManager = SecretManager.New(); - - const {ACCESS_TOKEN_SECRET} = await secretManager.getSecrets('secretkey/auth'); - - const REFRESH_TOKEN_UPDATE_INTERVAL = process.env.REFRESH_TOKEN_UPDATE_INTERVAL || '31536000000' // 1 year - - const user = await new DataBaseHelper(User).findOne({ username }); - if (user && passwordDigest === user.password) { - const tokenId = GenerateUUIDv4(); - const refreshToken = sign({ - id: tokenId, - name: user.username, - expireAt: Date.now() + parseInt(REFRESH_TOKEN_UPDATE_INTERVAL, 10) - }, ACCESS_TOKEN_SECRET); - user.refreshToken = tokenId; - await new DataBaseHelper(User).save(user); - return new MessageResponse({ - username: user.username, - did: user.did, - role: user.role, - refreshToken - }) - } else { - return new MessageError('Unauthorized request', 401); - } - + const user = await new DataBaseHelper(User).findOne({ hederaAccountId: account }) + return new MessageResponse(setDefaultPermissions(user)); } catch (error) { new Logger().error(error, ['AUTH_SERVICE']); return new MessageError(error); } }); - this.getMessages(AuthEvents.GENERATE_NEW_ACCESS_TOKEN, async (msg) => { - const {refreshToken} = msg; - const secretManager = SecretManager.New(); - - const {ACCESS_TOKEN_SECRET} = await secretManager.getSecrets('secretkey/auth') - - const decryptedToken = await util.promisify(verify)(refreshToken, ACCESS_TOKEN_SECRET, {}); - if (Date.now() > decryptedToken.expireAt) { - return new MessageResponse({}) + /** + * Get user by provider + * @param provider - Provider + * @param providerId - Provider ID + */ + this.getMessages(AuthEvents.GET_USER_BY_PROVIDER_USER_DATA, async (msg: any) => { + const { providerId, provider } = msg; + try { + const user = await new DataBaseHelper(User).findOne({ providerId, provider }) + return new MessageResponse(setDefaultPermissions(user)); + } catch (error) { + new Logger().error(error, ['AUTH_SERVICE']); + return new MessageError(error); } + }); - const user = await new DataBaseHelper(User).findOne({refreshToken: decryptedToken.id, username: decryptedToken.name}); - if (!user) { - return new MessageResponse({}) + /** + * Get user by parent + * @param did - Parent DID + */ + this.getMessages(AuthEvents.GET_USERS_BY_SR_ID, async (msg) => { + try { + const { did } = msg; + return new MessageResponse(await new DataBaseHelper(User).find({ parent: did })); + } catch (error) { + new Logger().error(error, ['AUTH_SERVICE']); + return new MessageError(error); } + }); - const ACCESS_TOKEN_UPDATE_INTERVAL = process.env.ACCESS_TOKEN_UPDATE_INTERVAL || '60000' - - const accessToken = sign({ - username: user.username, - did: user.did, - role: user.role, - expireAt: Date.now() + parseInt(ACCESS_TOKEN_UPDATE_INTERVAL, 10) - }, ACCESS_TOKEN_SECRET); - - return new MessageResponse({accessToken}); + /** + * Get users by DIDs + * @param dids - DIDs + */ + this.getMessages(AuthEvents.GET_USERS_BY_ID, async (msg: any) => { + const { dids } = msg; + try { + return new MessageResponse(await new DataBaseHelper(User).find({ where: { did: { $in: dids } } })); + } catch (error) { + new Logger().error(error, ['AUTH_SERVICE']); + return new MessageError(error); + } }); - this.getMessages(AuthEvents.GET_ALL_USER_ACCOUNTS, async (_) => { + /** + * Get users by Role (Category) + * @param role - Role (Category) + */ + this.getMessages(AuthEvents.GET_USERS_BY_ROLE, async (msg: any) => { + const { role } = msg; try { - const userAccounts = (await new DataBaseHelper(User).find({ role: UserRole.USER })).map((e) => ({ - username: e.username, - parent: e.parent, - did: e.did - })); - return new MessageResponse(userAccounts); + return new MessageResponse(await new DataBaseHelper(User).find({ role })); } catch (error) { new Logger().error(error, ['AUTH_SERVICE']); return new MessageError(error); } }); - this.getMessages(AuthEvents.GET_USERS_BY_SR_ID, async (msg) => { + /** + * Get All 'User' + */ + this.getMessages(AuthEvents.GET_ALL_USER_ACCOUNTS, async (_: any) => { try { - const { did } = msg; - return new MessageResponse(await new DataBaseHelper(User).find({ parent: did })); + const userAccounts = (await new DataBaseHelper(User).find({ role: UserRole.USER })).map((e) => ({ + username: e.username, + parent: e.parent, + did: e.did + })); + return new MessageResponse(userAccounts); } catch (error) { new Logger().error(error, ['AUTH_SERVICE']); return new MessageError(error); } }); + /** + * Get All 'Standard Registry' + */ this.getMessages(AuthEvents.GET_ALL_STANDARD_REGISTRY_ACCOUNTS, async (_) => { try { const userAccounts = (await new DataBaseHelper(User).find({ role: UserRole.STANDARD_REGISTRY })).map((e) => ({ @@ -239,6 +274,9 @@ export class AccountService extends NatsService { } }); + /** + * Get All + */ this.getMessages(AuthEvents.GET_ALL_USER_ACCOUNTS_DEMO, async (_) => { try { const userAccounts = (await new DataBaseHelper(User).findAll()).map((e) => ({ @@ -254,73 +292,133 @@ export class AccountService extends NatsService { } }); - this.getMessages(AuthEvents.GET_USER, async (msg) => { - const { username } = msg; + this.getMessages(AuthEvents.REGISTER_NEW_USER, async (msg) => { try { - return new MessageResponse(await new DataBaseHelper(User).findOne({ username })); - } catch (error) { - new Logger().error(error, ['AUTH_SERVICE']); - return new MessageError(error); - } - }); + const userRepository = new DataBaseHelper(User); - this.getMessages(AuthEvents.GET_USER_BY_PROVIDER_USER_DATA, async (msg) => { - const { providerId, provider } = msg; + const { username, password, role } = msg; + const passwordDigest = crypto.createHash('sha256').update(password).digest('hex'); + + const checkUserName = await userRepository.count({ username }); + if (checkUserName) { + return new MessageError('An account with the same name already exists.'); + } + const user = await createNewUser( + username, + passwordDigest, + role, + '', + null, + null, + null, + null, + ); + return new MessageResponse(user); - try { - return new MessageResponse(await new DataBaseHelper(User).findOne({ providerId, provider })); } catch (error) { new Logger().error(error, ['AUTH_SERVICE']); - return new MessageError(error); + return new MessageError(error) } }); - this.getMessages(AuthEvents.GET_USER_BY_ID, async (msg) => { - const { did } = msg; + this.getMessages(AuthEvents.GENERATE_NEW_TOKEN_BASED_ON_USER_PROVIDER, + async (msg: ProviderAuthUser) => { + try { + let user = await (new DataBaseHelper(User)).findOne({ username: msg.username }); + if (!user) { + user = await createNewUser( + msg.username, + null, + msg.role, + '', + null, + null, + msg.provider, + msg.providerId + ) + } + const secretManager = SecretManager.New(); + const { ACCESS_TOKEN_SECRET } = await secretManager.getSecrets('secretkey/auth') + const accessToken = sign({ + username: user.username, + did: user.did, + role: user.role + }, ACCESS_TOKEN_SECRET); + return new MessageResponse({ + username: user.username, + did: user.did, + role: user.role, + accessToken + }) + } catch (error) { + new Logger().error(error, ['AUTH_SERVICE']); + return new MessageError(error) + } + }); + this.getMessages(AuthEvents.GENERATE_NEW_TOKEN, async (msg) => { try { - return new MessageResponse(await new DataBaseHelper(User).findOne({ did })); - } catch (error) { - new Logger().error(error, ['AUTH_SERVICE']); - return new MessageError(error); - } - }); + const { username, password } = msg; + const passwordDigest = crypto.createHash('sha256').update(password).digest('hex'); - this.getMessages(AuthEvents.GET_USER_BY_ACCOUNT, async (msg) => { - const { account } = msg; + const secretManager = SecretManager.New(); - try { - return new MessageResponse(await new DataBaseHelper(User).findOne({ hederaAccountId: account })); - } catch (error) { - new Logger().error(error, ['AUTH_SERVICE']); - return new MessageError(error); - } - }); + const { ACCESS_TOKEN_SECRET } = await secretManager.getSecrets('secretkey/auth'); - this.getMessages(AuthEvents.GET_USERS_BY_ID, async (msg) => { - const { dids } = msg; + const REFRESH_TOKEN_UPDATE_INTERVAL = process.env.REFRESH_TOKEN_UPDATE_INTERVAL || '31536000000' // 1 year + + const user = await new DataBaseHelper(User).findOne({ username }); + if (user && passwordDigest === user.password) { + const tokenId = GenerateUUIDv4(); + const refreshToken = sign({ + id: tokenId, + name: user.username, + expireAt: Date.now() + parseInt(REFRESH_TOKEN_UPDATE_INTERVAL, 10) + }, ACCESS_TOKEN_SECRET); + user.refreshToken = tokenId; + await new DataBaseHelper(User).save(user); + return new MessageResponse({ + username: user.username, + did: user.did, + role: user.role, + refreshToken + }) + } else { + return new MessageError('Unauthorized request', 401); + } - try { - return new MessageResponse(await new DataBaseHelper(User).find({ - where: { - did: { $in: dids } - } - })); } catch (error) { new Logger().error(error, ['AUTH_SERVICE']); return new MessageError(error); } }); - this.getMessages(AuthEvents.GET_USERS_BY_ROLE, async (msg) => { - const { role } = msg; + this.getMessages(AuthEvents.GENERATE_NEW_ACCESS_TOKEN, async (msg) => { + const { refreshToken } = msg; + const secretManager = SecretManager.New(); - try { - return new MessageResponse(await new DataBaseHelper(User).find({ role })); - } catch (error) { - new Logger().error(error, ['AUTH_SERVICE']); - return new MessageError(error); + const { ACCESS_TOKEN_SECRET } = await secretManager.getSecrets('secretkey/auth') + + const decryptedToken = await util.promisify(verify)(refreshToken, ACCESS_TOKEN_SECRET, {}); + if (Date.now() > decryptedToken.expireAt) { + return new MessageResponse({}) + } + + const user = await new DataBaseHelper(User).findOne({ refreshToken: decryptedToken.id, username: decryptedToken.name }); + if (!user) { + return new MessageResponse({}) } + + const ACCESS_TOKEN_UPDATE_INTERVAL = process.env.ACCESS_TOKEN_UPDATE_INTERVAL || '60000' + + const accessToken = sign({ + username: user.username, + did: user.did, + role: user.role, + expireAt: Date.now() + parseInt(ACCESS_TOKEN_UPDATE_INTERVAL, 10) + }, ACCESS_TOKEN_SECRET); + + return new MessageResponse({ accessToken }); }); this.getMessages(AuthEvents.UPDATE_USER, async (msg) => { @@ -344,5 +442,52 @@ export class AccountService extends NatsService { return new MessageError(error); } }); + + this.getMessages(AuthEvents.GET_USER_ACCOUNTS, async (msg: any) => { + try { + if (!msg) { + return new MessageError('Invalid load users parameter'); + } + + const { filters, pageIndex, pageSize, parent } = msg; + const otherOptions: any = { + fields: [ + 'username', + 'did', + 'hederaAccountId', + 'role', + 'permissionsGroup', + 'permissions', + ] + }; + const _pageSize = parseInt(pageSize, 10); + const _pageIndex = parseInt(pageIndex, 10); + if (Number.isInteger(_pageSize) && Number.isInteger(_pageIndex)) { + otherOptions.orderBy = { createDate: 'DESC' }; + otherOptions.limit = _pageSize; + otherOptions.offset = _pageIndex * _pageSize; + } else { + otherOptions.orderBy = { createDate: 'DESC' }; + otherOptions.limit = 100; + } + const options: any = { parent }; + if (filters) { + if (filters.role) { + options['permissionsGroup.roleId'] = filters.role; + } + if (filters.username) { + options.username = { $regex: '.*' + filters.username + '.*' }; + } + if (filters.did) { + options.did = filters.did; + } + } + const [items, count] = await new DataBaseHelper(User).findAndCount(options, otherOptions); + return new MessageResponse({ items, count }); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); } } diff --git a/auth-service/src/api/auth.interface.ts b/auth-service/src/api/auth.interface.ts index 875749738a..2d9efe1aab 100644 --- a/auth-service/src/api/auth.interface.ts +++ b/auth-service/src/api/auth.interface.ts @@ -1,4 +1,4 @@ -import { UserRole } from '@guardian/interfaces'; +import { IGroup, UserRole } from '@guardian/interfaces'; /** * Authenticated user interface @@ -32,4 +32,12 @@ export interface IAuthUser { * login expire date */ expireAt?: number + /** + * Group name + */ + permissionsGroup?: IGroup[]; + /** + * Permissions + */ + permissions?: string[]; } diff --git a/auth-service/src/api/role-service.ts b/auth-service/src/api/role-service.ts new file mode 100644 index 0000000000..6d42ad3b72 --- /dev/null +++ b/auth-service/src/api/role-service.ts @@ -0,0 +1,655 @@ +import { + DataBaseHelper, + Logger, + MessageError, + MessageResponse, + NatsService, + Singleton +} from '@guardian/common'; +import { AuthEvents, DefaultRoles, GenerateUUIDv4, IGroup, IOwner, Permissions, PermissionsArray, UserRole } from '@guardian/interfaces'; +import { DynamicRole } from '../entity/dynamic-role.js'; +import { User } from '../entity/user.js'; + +const permissionList = PermissionsArray.filter((p) => !p.disabled).map((p) => { + return { + name: p.name, + category: p.category, + entity: p.entity, + action: p.action, + disabled: p.disabled, + dependOn: p.dependOn + } +}) + +const availableList = permissionList.reduce((map, p) => { + map.set(p.name, p); + return map; +}, new Map()); + +const allList = PermissionsArray.reduce((map, p) => { + map.set(p.name, p); + return map; +}, new Map()); + +class ListPermissions { + private readonly _list: Set; + + constructor() { + this._list = new Set(); + } + + public add(permission: string, system: boolean) { + if (this._list.has(permission)) { + return; + } + let config: any; + if (system) { + if (allList.has(permission)) { + config = allList.get(permission); + } else { + return; + } + } else { + if (availableList.has(permission)) { + config = availableList.get(permission); + } else { + return; + } + } + this._list.add(permission); + if (config.dependOn) { + for (const sub of config.dependOn) { + this.add(sub, true); + } + } + } + + public list(): string[] { + return Array.from(this._list); + } + + public static unique(permissions: string[]): string[] { + const list = new ListPermissions(); + for (const name of permissions) { + list.add(name, false); + } + return list.list(); + } +} + +export async function getDefaultRole(owner: string): Promise { + const defaultRole = await new DataBaseHelper(DynamicRole).findOne({ owner, default: true }); + if (defaultRole) { + return defaultRole; + } + return await new DataBaseHelper(DynamicRole).findOne({ owner: null, default: true, readonly: true }); +} + +/** + * Role service + */ +@Singleton +export class RoleService extends NatsService { + /** + * Message queue name + */ + public messageQueueName = 'auth-roles-queue'; + + /** + * Reply subject + * @private + */ + public replySubject = 'auth-roles-queue-reply-' + GenerateUUIDv4(); + + /** + * Register listeners + */ + registerListeners(): void { + /** + * Get permissions + * + * @returns {any[]} permissions + */ + this.getMessages(AuthEvents.GET_PERMISSIONS, async (_: any) => { + try { + return new MessageResponse(permissionList); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Get roles + * + * @param payload - filters + * + * @returns {any[]} roles + */ + this.getMessages(AuthEvents.GET_ROLES, + async (msg: { + name: string, + owner: string, + user: string, + onlyOwn: boolean, + pageIndex: string, + pageSize: string + }) => { + try { + if (!msg) { + return new MessageError('Invalid load roles parameter'); + } + + const { name, owner, user, onlyOwn, pageIndex, pageSize } = msg; + const otherOptions: any = {}; + const _pageSize = parseInt(pageSize, 10); + const _pageIndex = parseInt(pageIndex, 10); + if (Number.isInteger(_pageSize) && Number.isInteger(_pageIndex)) { + otherOptions.orderBy = { + owner: 'ASC', + createDate: 'DESC' + }; + otherOptions.limit = _pageSize; + otherOptions.offset = _pageIndex * _pageSize; + } else { + otherOptions.orderBy = { + owner: 'ASC', + createDate: 'DESC' + }; + otherOptions.limit = 100; + } + + const options: any = { + $or: [ + { owner }, + { + owner: null, + default: true, + readonly: true + } + ] + }; + if (name) { + options.name = { $regex: '.*' + name + '.*' }; + } + + if (onlyOwn) { + const target = await new DataBaseHelper(User).findOne({ did: user }); + if (target && target.permissionsGroup?.length) { + const ids = target.permissionsGroup.map((group) => group.roleId); + options.id = { $in: ids }; + } else { + return new MessageResponse({ items: [], count: 0 }); + } + } + + const [items, count] = await new DataBaseHelper(DynamicRole).findAndCount(options, otherOptions); + const defaultRole = await getDefaultRole(owner); + const defaultRoleId = defaultRole?.id; + for (const item of items) { + item.default = item.id === defaultRoleId; + } + + return new MessageResponse({ items, count }); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Create new role + * + * @param payload - role + * + * @returns {any} new role + */ + this.getMessages(AuthEvents.CREATE_ROLE, + async (msg: { role: DynamicRole, owner: IOwner }) => { + try { + if (!msg) { + throw new Error('Invalid create role parameters'); + } + const { role, owner } = msg; + + delete role._id; + delete role.id; + role.owner = owner.creator; + role.uuid = GenerateUUIDv4(); + role.permissions = ListPermissions.unique(role.permissions); + role.default = false; + role.readonly = false; + let item = new DataBaseHelper(DynamicRole).create(role); + item = await new DataBaseHelper(DynamicRole).save(item); + return new MessageResponse(item); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Update role + * + * @param payload - role + * + * @returns {any} role + */ + this.getMessages(AuthEvents.UPDATE_ROLE, + async (msg: { id: string, role: any, owner: IOwner }) => { + try { + if (!msg) { + return new MessageError('Invalid update role parameters'); + } + const { id, role, owner } = msg; + + const item = await new DataBaseHelper(DynamicRole).findOne({ + id, + owner: owner.creator + }); + + if (!item || item.owner !== owner.creator) { + throw new Error('Invalid role'); + } + + item.name = role.name; + item.description = role.description; + item.permissions = ListPermissions.unique(role.permissions); + const result = await new DataBaseHelper(DynamicRole).update(item); + return new MessageResponse(result); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Get role by Id + * + * @param {any} msg - filters + * + * @returns {any} role + */ + this.getMessages(AuthEvents.GET_ROLE, + async (msg: { id: string }) => { + try { + if (!msg) { + return new MessageError('Invalid get role parameters'); + } + const { id } = msg; + const item = await new DataBaseHelper(DynamicRole).findOne({ id }); + return new MessageResponse(item); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Delete role + * + * @param {any} msg - Delete role parameters + * + * @returns {boolean} - Operation success + */ + this.getMessages(AuthEvents.DELETE_ROLE, + async (msg: { id: string, owner: IOwner }) => { + try { + if (!msg) { + return new MessageError('Invalid delete role parameters'); + } + const { id, owner } = msg; + const item = await new DataBaseHelper(DynamicRole).findOne({ + id, + owner: owner.creator + }); + if (!item || item.owner !== owner.creator) { + throw new Error('Invalid role'); + } + await new DataBaseHelper(DynamicRole).remove(item); + return new MessageResponse(item); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Set default role + * + * @param {any} msg - default role parameters + * + * @returns {boolean} - Operation success + */ + this.getMessages(AuthEvents.SET_DEFAULT_ROLE, + async (msg: { id: string, owner: string }) => { + try { + if (!msg) { + return new MessageError('Invalid delete role parameters'); + } + const { id, owner } = msg; + const items = await new DataBaseHelper(DynamicRole).find({ owner }); + for (const item of items) { + item.default = item.id === id; + } + await new DataBaseHelper(DynamicRole).update(items); + const result = items.find((role) => role.default); + return new MessageResponse(result); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Set default role + * + * @param {any} msg - default role parameters + * + * @returns {boolean} - Operation success + */ + this.getMessages(AuthEvents.SET_DEFAULT_USER_ROLE, + async (msg: { username: string, owner: string }) => { + try { + if (!msg) { + return new MessageError('Invalid delete role parameters'); + } + const { username, owner } = msg; + const target = await new DataBaseHelper(User).findOne({ + username, + parent: owner + }) + if (!target) { + return new MessageError('User does not exist'); + } + const defaultRole = await getDefaultRole(owner); + if (defaultRole) { + target.permissionsGroup = [{ + uuid: defaultRole.uuid, + roleId: defaultRole.id, + roleName: defaultRole.name, + owner + }]; + target.permissions = defaultRole.permissions; + } else { + target.permissionsGroup = []; + target.permissions = []; + } + const result = await new DataBaseHelper(User).update(target); + return new MessageResponse(result); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Set default role + * + * @param {any} msg - default role parameters + * + * @returns {boolean} - Operation success + */ + this.getMessages(AuthEvents.CREATE_DEFAULT_USER_ROLE, + async (msg: { username: string }) => { + try { + if (!msg) { + return new MessageError('Invalid delete role parameters'); + } + const { username } = msg; + const user = await new DataBaseHelper(User).findOne({ username }) + if (!user) { + return new MessageError('User does not exist'); + } + const db = new DataBaseHelper(User); + if (user.role === UserRole.STANDARD_REGISTRY) { + await db.save(db.create({ + uuid: GenerateUUIDv4(), + name: 'Policy Approver', + description: '', + owner: user.did, + permissions: [ + Permissions.ANALYTIC_POLICY_READ, + Permissions.POLICIES_POLICY_READ, + Permissions.ANALYTIC_MODULE_READ, + Permissions.ANALYTIC_TOOL_READ, + Permissions.ANALYTIC_SCHEMA_READ, + Permissions.POLICIES_POLICY_REVIEW, + Permissions.SCHEMAS_SCHEMA_READ, + Permissions.MODULES_MODULE_READ, + Permissions.TOOLS_TOOL_READ, + Permissions.TOKENS_TOKEN_READ, + Permissions.ARTIFACTS_FILE_READ, + Permissions.SETTINGS_THEME_READ, + Permissions.SETTINGS_THEME_CREATE, + Permissions.SETTINGS_THEME_UPDATE, + Permissions.SETTINGS_THEME_DELETE, + Permissions.TAGS_TAG_READ, + Permissions.TAGS_TAG_CREATE, + Permissions.SUGGESTIONS_SUGGESTIONS_READ, + Permissions.ACCESS_POLICY_ASSIGNED + ], + default: false, + readonly: false + })) + await db.save(db.create({ + uuid: GenerateUUIDv4(), + name: 'Policy Manager', + description: '', + owner: user.did, + permissions: [ + Permissions.ANALYTIC_DOCUMENT_READ, + Permissions.POLICIES_POLICY_MANAGE, + Permissions.POLICIES_POLICY_READ, + Permissions.TOKENS_TOKEN_MANAGE, + Permissions.TOKENS_TOKEN_READ, + Permissions.ACCOUNTS_ACCOUNT_READ, + Permissions.TAGS_TAG_READ, + Permissions.TAGS_TAG_CREATE, + Permissions.ACCESS_POLICY_ASSIGNED_AND_PUBLISHED + ], + default: false, + readonly: false + })) + await db.save(db.create({ + uuid: GenerateUUIDv4(), + name: 'Policy User', + description: '', + owner: user.did, + permissions: DefaultRoles, + default: false, + readonly: false + })) + } + return new MessageResponse(true); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Update user role + * + * @param payload - user role + * + * @returns {any} user role + */ + this.getMessages(AuthEvents.UPDATE_USER_ROLE, + async (msg: { username: string, userRoles: string[], owner: IOwner }) => { + try { + if (!msg) { + return new MessageError('Invalid update user parameters'); + } + const { username, userRoles, owner } = msg; + + const target = await new DataBaseHelper(User).findOne({ + username, + parent: owner.creator + }); + if (!target) { + return new MessageError('User does not exist'); + } + + const roleMap = new Map(); + const permissions = new Set(); + const roles = await new DataBaseHelper(DynamicRole).find({ id: { $in: userRoles } }); + for (const role of roles) { + if ( + (role.owner && role.owner === owner.creator) || + (!role.owner && role.default) + ) { + roleMap.set(role.id, [owner.creator, role.name, role.uuid]); + for (const permission of role.permissions) { + permissions.add(permission); + } + } else { + throw new Error('Role does not exist'); + } + } + + if (target.permissionsGroup) { + for (const group of target.permissionsGroup) { + if (roleMap.has(group.roleId)) { + roleMap.set(group.roleId, [group.owner, group.roleName, group.uuid]); + } + } + } + + target.permissionsGroup = []; + for (const [roleId, [roleOwner, roleName, uuid]] of roleMap.entries()) { + target.permissionsGroup.push({ + uuid, + roleId, + roleName, + owner: roleOwner + }); + } + target.permissions = Array.from(permissions); + const result = await new DataBaseHelper(User).update(target); + return new MessageResponse(result); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Refresh user permissions + * + * @param {any} msg - filters + * + * @returns {any} users + */ + this.getMessages(AuthEvents.REFRESH_USER_PERMISSIONS, + async (msg: { id: string, owner: string }) => { + try { + const { owner } = msg; + const users = await new DataBaseHelper(User).find({ parent: owner }); + const roleMap = new Map(); + for (const user of users) { + const permissionsGroup: IGroup[] = []; + const permissions = new Set(); + if (user.permissionsGroup) { + for (const group of user.permissionsGroup) { + if (!roleMap.has(group.roleId)) { + const row = await new DataBaseHelper(DynamicRole).findOne({ id: group.roleId }); + roleMap.set(group.roleId, row); + } + const role = roleMap.get(group.roleId); + if (role) { + group.roleName = role.name; + permissionsGroup.push(group); + for (const permission of role.permissions) { + permissions.add(permission); + } + } + } + } + user.permissionsGroup = permissionsGroup; + user.permissions = Array.from(permissions); + await new DataBaseHelper(User).update(user); + } + return new MessageResponse(users); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + + /** + * Delegate user role + * + * @param payload - user role + * + * @returns {any} user role + */ + this.getMessages(AuthEvents.DELEGATE_USER_ROLE, + async (msg: { username: string, userRoles: string[], owner: IOwner }) => { + try { + if (!msg) { + return new MessageError('Invalid update user parameters'); + } + const { username, userRoles, owner } = msg; + + const user = await new DataBaseHelper(User).findOne({ + did: owner.creator + }); + const target = await new DataBaseHelper(User).findOne({ username }); + + if (!user || !target) { + return new MessageError('User does not exist'); + } + + //Old + const othersRoles = new Map(); + target.permissionsGroup = target.permissionsGroup || []; + for (const group of target.permissionsGroup) { + if (group.owner !== owner.creator) { + const role = await new DataBaseHelper(DynamicRole).findOne({ id: group.roleId }); + if (role) { + othersRoles.set(role.id, [group.owner, role]); + } + } + } + + //New + const ownRoles = user.permissionsGroup?.map((g) => g.roleId) || []; + const roles = await new DataBaseHelper(DynamicRole).find({ id: { $in: userRoles } }); + for (const role of roles) { + if (ownRoles.includes(role.id)) { + if (!othersRoles.has(role.id)) { + othersRoles.set(role.id, [owner.creator, role]); + } + } else { + throw new Error('Role does not exist'); + } + } + + const permissions = new Set(); + const permissionsGroup: IGroup[] = []; + for (const [roleOwner, role] of othersRoles.values()) { + if (role) { + permissionsGroup.push({ + uuid: role.uuid, + roleId: role.id, + roleName: role.name, + owner: roleOwner + }); + for (const permission of role.permissions) { + permissions.add(permission); + } + } + } + + target.permissionsGroup = permissionsGroup; + target.permissions = Array.from(permissions); + await new DataBaseHelper(User).update(target); + return new MessageResponse(target); + } catch (error) { + new Logger().error(error, ['GUARDIAN_SERVICE']); + return new MessageError(error); + } + }); + } +} \ No newline at end of file diff --git a/auth-service/src/app.ts b/auth-service/src/app.ts index 4c86c0a264..50e9354e5b 100644 --- a/auth-service/src/app.ts +++ b/auth-service/src/app.ts @@ -12,6 +12,7 @@ import { AppModule } from './app.module.js'; import { MicroserviceOptions, Transport } from '@nestjs/microservices'; import { MeecoAuthService } from './api/meeco-service.js'; import { ApplicationEnvironment } from './environment.js'; +import { RoleService } from './api/role-service.js'; Promise.all([ Migration({ @@ -29,7 +30,7 @@ Promise.all([ ensureIndexes: true }), MessageBrokerChannel.connect('AUTH_SERVICE'), - NestFactory.createMicroservice(AppModule,{ + NestFactory.createMicroservice(AppModule, { transport: Transport.NATS, options: { queue: 'auth-service', @@ -40,7 +41,7 @@ Promise.all([ }, }), InitializeVault(process.env.VAULT_PROVIDER) -]).then(async ([_, db, cn, app, vault]) => { +]).then(async ([_, db, cn, app, vault]) => { DataBaseHelper.orm = db; const state = new ApplicationState(); await state.setServiceName('AUTH_SERVICE').setConnection(cn).init(); @@ -68,6 +69,9 @@ Promise.all([ new WalletService().registerVault(vault); new WalletService().registerListeners(); + await new RoleService().setConnection(cn).init(); + new RoleService().registerListeners(); + if (parseInt(process.env.MEECO_AUTH_PROVIDER_ACTIVE, 10)) { await new MeecoAuthService().setConnection(cn).init(); new MeecoAuthService().registerListeners(); @@ -79,10 +83,10 @@ Promise.all([ await new OldSecretManager().setConnection(cn).init(); const secretManager = SecretManager.New(); - let {ACCESS_TOKEN_SECRET } = await secretManager.getSecrets('secretkey/auth'); + let { ACCESS_TOKEN_SECRET } = await secretManager.getSecrets('secretkey/auth'); if (!ACCESS_TOKEN_SECRET) { ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET; - await secretManager.setSecrets('secretkey/auth', { ACCESS_TOKEN_SECRET }); + await secretManager.setSecrets('secretkey/auth', { ACCESS_TOKEN_SECRET }); } state.updateState(ApplicationStates.READY); diff --git a/auth-service/src/constants/index.ts b/auth-service/src/constants/index.ts new file mode 100644 index 0000000000..cf5eca6aca --- /dev/null +++ b/auth-service/src/constants/index.ts @@ -0,0 +1 @@ +export { REQUIRED_PROPS as USER_REQUIRED_PROPS } from './user.js'; diff --git a/auth-service/src/constants/user.ts b/auth-service/src/constants/user.ts new file mode 100644 index 0000000000..6a31717136 --- /dev/null +++ b/auth-service/src/constants/user.ts @@ -0,0 +1,10 @@ +export const REQUIRED_PROPS = { + STATUS_CODE: 'status_code', + REASON: 'reason', + USER_NAME: 'username', + DID: 'did', + PARENT: 'parent', + HEDERA_ACCOUNT_ID: 'hederaAccountId', + ROLE: 'role', + ID: 'id', +}; diff --git a/auth-service/src/entity/dynamic-role.ts b/auth-service/src/entity/dynamic-role.ts new file mode 100644 index 0000000000..c9faf47ae8 --- /dev/null +++ b/auth-service/src/entity/dynamic-role.ts @@ -0,0 +1,68 @@ + +import { GenerateUUIDv4 } from '@guardian/interfaces'; +import { BeforeCreate, Entity, Index, Property } from '@mikro-orm/core'; +import { BaseEntity } from '@guardian/common'; + +/** + * Role collection + */ +@Entity() +@Index({ name: 'id_idx', properties: ['id', 'owner'] }) +@Index({ name: 'owner_idx', properties: ['owner'] }) +export class DynamicRole extends BaseEntity { + /** + * Role id + */ + @Property() + uuid: string; + + /** + * Role label + */ + @Property() + name: string; + + /** + * Role description + */ + @Property() + description: string; + + /** + * Role owner + */ + @Property() + owner: string; + + /** + * Permissions + */ + @Property() + permissions: string[]; + + /** + * Owner + */ + @Property() + default: boolean; + + /** + * Readonly + */ + @Property() + readonly: boolean; + + /** + * Set policy defaults + */ + @BeforeCreate() + setDefaults() { + this.name = this.name || ''; + this.description = this.description || ''; + this.owner = this.owner || ''; + this.uuid = this.uuid || GenerateUUIDv4(); + this.permissions = Array.isArray(this.permissions) ? this.permissions : []; + this.default = !!this.default; + this.readonly = !!this.readonly; + } +} diff --git a/auth-service/src/entity/role.ts b/auth-service/src/entity/role.ts new file mode 100644 index 0000000000..9447eb6d9a --- /dev/null +++ b/auth-service/src/entity/role.ts @@ -0,0 +1,43 @@ +import { BeforeCreate, Entity, Index, Property } from '@mikro-orm/core'; +import { BaseEntity } from '@guardian/common'; + +/** + * Role collection + */ +@Entity() +@Index({ name: 'id_idx', properties: ['name', 'owner'] }) +export class Role extends BaseEntity { + /** + * Name + */ + @Property() + name: string; + + /** + * Description + */ + @Property({ nullable: true }) + description?: string; + + /** + * Owner + */ + @Property() + owner: string; + + /** + * Permissions + */ + @Property() + permissions: string[]; + + /** + * Set defaults + */ + @BeforeCreate() + setInitState() { + this.name = this.name || ''; + this.owner = this.owner || ''; + this.permissions = Array.isArray(this.permissions) ? this.permissions : []; + } +} diff --git a/auth-service/src/entity/user.ts b/auth-service/src/entity/user.ts index c5f5c4c19f..e490582029 100644 --- a/auth-service/src/entity/user.ts +++ b/auth-service/src/entity/user.ts @@ -1,13 +1,13 @@ import { BeforeCreate, Entity, Enum, Property, Unique } from '@mikro-orm/core'; -import { IUser, UserRole } from '@guardian/interfaces'; +import { IGroup, IUser, UserRole } from '@guardian/interfaces'; import { BaseEntity } from '@guardian/common'; /** * User collection */ @Entity() -@Unique({ properties: ['username'], options: { partialFilterExpression: { username: { $type: 'string' }}}}) -@Unique({ properties: ['did'], options: { partialFilterExpression: { did: { $type: 'string' }}}}) +@Unique({ properties: ['username'], options: { partialFilterExpression: { username: { $type: 'string' } } } }) +@Unique({ properties: ['did'], options: { partialFilterExpression: { did: { $type: 'string' } } } }) export class User extends BaseEntity implements IUser { /** * Username @@ -48,7 +48,7 @@ export class User extends BaseEntity implements IUser { /** * User role */ - @Enum({ nullable: true}) + @Enum({ nullable: true }) role?: UserRole; /** @@ -72,15 +72,27 @@ export class User extends BaseEntity implements IUser { /** * Refresh token */ - @Property({nullable: true}) + @Property({ nullable: true }) refreshToken?: string; /** * Use fireblocks signing */ - @Property({nullable: true}) + @Property({ nullable: true }) useFireblocksSigning: boolean; + /** + * Group name + */ + @Property({ nullable: true }) + permissionsGroup?: IGroup[]; + + /** + * Permissions + */ + @Property({ nullable: true }) + permissions?: string[]; + /** * Set defaults */ diff --git a/auth-service/src/migrations/v2-24-1.ts b/auth-service/src/migrations/v2-24-1.ts new file mode 100644 index 0000000000..d5f9a347fd --- /dev/null +++ b/auth-service/src/migrations/v2-24-1.ts @@ -0,0 +1,128 @@ +import { DefaultRoles, GenerateUUIDv4, Permissions, OldRoles, UserRole } from '@guardian/interfaces'; +import { Migration } from '@mikro-orm/migrations-mongodb'; + +const policyApprover = [ + Permissions.ANALYTIC_POLICY_READ, + Permissions.POLICIES_POLICY_READ, + Permissions.ANALYTIC_MODULE_READ, + Permissions.ANALYTIC_TOOL_READ, + Permissions.ANALYTIC_SCHEMA_READ, + Permissions.POLICIES_POLICY_REVIEW, + Permissions.SCHEMAS_SCHEMA_READ, + Permissions.MODULES_MODULE_READ, + Permissions.TOOLS_TOOL_READ, + Permissions.TOKENS_TOKEN_READ, + Permissions.ARTIFACTS_FILE_READ, + Permissions.SETTINGS_THEME_READ, + Permissions.SETTINGS_THEME_CREATE, + Permissions.SETTINGS_THEME_UPDATE, + Permissions.SETTINGS_THEME_DELETE, + Permissions.TAGS_TAG_READ, + Permissions.TAGS_TAG_CREATE, + Permissions.SUGGESTIONS_SUGGESTIONS_READ, + Permissions.ACCESS_POLICY_ASSIGNED +]; +const policyManager = [ + Permissions.ANALYTIC_DOCUMENT_READ, + Permissions.POLICIES_POLICY_MANAGE, + Permissions.POLICIES_POLICY_READ, + Permissions.TOKENS_TOKEN_MANAGE, + Permissions.TOKENS_TOKEN_READ, + Permissions.ACCOUNTS_ACCOUNT_READ, + Permissions.TAGS_TAG_READ, + Permissions.TAGS_TAG_CREATE, + Permissions.ACCESS_POLICY_ASSIGNED_AND_PUBLISHED +]; + +/** + * Migration to version 2.9.0 + */ +export class ReleaseMigration extends Migration { + /** + * Up migration + */ + async up(): Promise { + await this.setDefaultRoles(); + } + + /** + * Change document state format + */ + async setDefaultRoles() { + const roleCollection = this.getCollection('DynamicRole'); + const userCollection = this.getCollection('User'); + + await roleCollection.insertOne({ + uuid: GenerateUUIDv4(), + name: 'Default policy user', + description: 'Default policy user', + owner: null, + permissions: DefaultRoles, + default: true, + readonly: true + }); + const srs = userCollection.find({ role: UserRole.STANDARD_REGISTRY }, { session: this.ctx }); + while (await srs.hasNext()) { + const sr = await srs.next(); + + const oldRoleUUID = GenerateUUIDv4(); + await roleCollection.insertMany([{ + uuid: GenerateUUIDv4(), + name: 'Policy Approver', + description: '', + owner: sr.did, + permissions: policyApprover, + default: false, + readonly: false + }, { + uuid: GenerateUUIDv4(), + name: 'Policy Manager', + description: '', + owner: sr.did, + permissions: policyManager, + default: false, + readonly: false + }, { + uuid: GenerateUUIDv4(), + name: 'Policy User', + description: '', + owner: sr.did, + permissions: DefaultRoles, + default: false, + readonly: false + }, { + uuid: oldRoleUUID, + name: 'Old Policy User', + description: '', + owner: sr.did, + permissions: OldRoles, + default: false, + readonly: false + } + ], { session: this.ctx }); + const oldRole = await roleCollection.findOne({ + uuid: oldRoleUUID, + owner: sr.did + }, { session: this.ctx }); + + const children = userCollection.find({ role: UserRole.USER, parent: sr.did }, { session: this.ctx }); + while (await children.hasNext()) { + const child = await children.next(); + await userCollection.updateOne( + { _id: child._id }, + { + $set: { + permissionsGroup: [{ + roleId: String(oldRole._id), + roleName: oldRole.name, + owner: oldRole.owner + }], + permissions: oldRole.permissions, + }, + }, + { session: this.ctx, upsert: false } + ); + } + } + } +} diff --git a/common/package.json b/common/package.json index d2bb267de4..6b033665e4 100644 --- a/common/package.json +++ b/common/package.json @@ -5,13 +5,13 @@ "@azure/identity": "^3.2.2", "@azure/keyvault-secrets": "^4.7.0", "@google-cloud/secret-manager": "^4.2.2", - "@guardian/interfaces": "^2.24.1", + "@guardian/interfaces": "^2.25.0", "@hashgraph/sdk": "2.34.1", "@mattrglobal/jsonld-signatures-bbs": "^1.1.2", "@meeco/cryppo": "^2.0.2", - "@mikro-orm/core": "^6.1.11", - "@mikro-orm/migrations-mongodb": "^6.1.11", - "@mikro-orm/mongodb": "^6.1.11", + "@mikro-orm/core": "6.2.2", + "@mikro-orm/migrations-mongodb": "6.2.2", + "@mikro-orm/mongodb": "6.2.2", "@nestjs/common": "^9.4.1", "@nestjs/core": "^9.4.1", "@nestjs/microservices": "^9.4.1", @@ -44,14 +44,15 @@ "lodash.set": "^4.3.2", "mathjs": "^10.1.0", "moment": "^2.29.2", - "mongodb": "^6.5.0", + "mongodb": "6.5.0", "nats": "^2.6.1", "node-vault": "^0.9.22", "reflect-metadata": "^0.1.13", "winston": "^3.8.1", "ws": "^8.2.1", "zlib": "^1.0.5", - "@formulajs/formulajs": "^4.4.0" + "@formulajs/formulajs": "^4.4.0", + "prom-client": "^14.1.1" }, "description": "Common package share cross all services", "devDependencies": { @@ -87,5 +88,5 @@ "test:stability": "mocha tests/stability.test.js" }, "type": "module", - "version": "2.24.1" + "version": "2.25.0" } diff --git a/common/src/database-modules/database-server.ts b/common/src/database-modules/database-server.ts index 3580a35d29..443c65622d 100644 --- a/common/src/database-modules/database-server.ts +++ b/common/src/database-modules/database-server.ts @@ -35,9 +35,11 @@ import { PolicyCache, PolicyCacheData, RetirePool, + AssignEntity, } from '../entity/index.js'; import { Binary } from 'bson'; import { + AssignedEntityType, GenerateUUIDv4, IVC, MintTransactionStatus, @@ -133,7 +135,7 @@ export class DatabaseServer { console.log(this); await DatabaseServer.clearDryRun(this.dryRun); // Clear files - const files = await new DataBaseHelper(DryRunFiles).find({policyId: this.dryRun}); + const files = await new DataBaseHelper(DryRunFiles).find({ policyId: this.dryRun }); await Promise.all(files.map(file => new DataBaseHelper(DryRunFiles).remove(file))); } @@ -1890,18 +1892,18 @@ export class DatabaseServer { }); const serials = vpDocument.serials ? vpDocument.serials.map((serial) => ({ - serial, - tokenId: vpDocument.tokenId, - })) + serial, + tokenId: vpDocument.tokenId, + })) : []; let amount = Number.isFinite(Number(vpDocument.amount)) ? Number(vpDocument.amount) : serials.length; const transferSerials = vpDocument.serials ? vpDocument.serials.map((serial) => ({ - serial, - tokenId: vpDocument.tokenId, - })) + serial, + tokenId: vpDocument.tokenId, + })) : []; let transferAmount = amount; const errors = []; @@ -3390,4 +3392,68 @@ export class DatabaseServer { public static async getDidDocument(did: string): Promise { return await (new DataBaseHelper(DidDocumentCollection)).findOne({ did }); } + + /** + * Assign entity + * @param type + * @param entityId + * @param assigned + * @param did + */ + public static async assignEntity( + type: AssignedEntityType, + entityId: string, + assigned: boolean, + did: string, + owner: string + ): Promise { + const item = new DataBaseHelper(AssignEntity).create({ type, entityId, assigned, did, owner }); + return await new DataBaseHelper(AssignEntity).save(item); + } + + /** + * Check entity + * @param type + * @param entityId + * @param did + */ + public static async getAssignedEntity(type: AssignedEntityType, entityId: string, did: string): Promise { + return await (new DataBaseHelper(AssignEntity)).findOne({ type, entityId, did }); + } + + /** + * Get assigned entities + * @param did + * @param type + */ + public static async getAssignedEntities(did: string, type?: AssignedEntityType): Promise { + if (type) { + return await (new DataBaseHelper(AssignEntity)).find({ type, did }); + } else { + return await (new DataBaseHelper(AssignEntity)).find({ did }); + } + } + + /** + * Remove assign entity + * @param type + * @param entityId + * @param did + */ + public static async removeAssignEntity( + type: AssignedEntityType, + entityId: string, + did: string, + owner?: string + ): Promise { + const filters: any = { type, entityId, did }; + if (owner) { + filters.owner = owner; + } + const item = await (new DataBaseHelper(AssignEntity)).findOne(filters); + if (item) { + await (new DataBaseHelper(AssignEntity)).remove(item); + } + return true; + } } diff --git a/common/src/entity/artifact.ts b/common/src/entity/artifact.ts index bae186906b..fe515d4e56 100644 --- a/common/src/entity/artifact.ts +++ b/common/src/entity/artifact.ts @@ -49,6 +49,12 @@ export class Artifact extends BaseEntity { @Property({ nullable: true }) category?: 'tool' | 'policy'; + /** + * Artifact creator + */ + @Property({ nullable: true }) + creator?: string; + /** * Default document values */ diff --git a/common/src/entity/assign-entity.ts b/common/src/entity/assign-entity.ts new file mode 100644 index 0000000000..19e09f3604 --- /dev/null +++ b/common/src/entity/assign-entity.ts @@ -0,0 +1,49 @@ +import { AssignedEntityType } from '@guardian/interfaces'; +import { BaseEntity } from '../models/index.js'; +import { + Entity, + Property, + Index, + Unique, +} from '@mikro-orm/core'; + +/** + * Block state + */ +@Entity() +@Index({ name: 'user_idx', properties: ['type', 'did'] }) +@Index({ name: 'entity_idx', properties: ['type', 'did', 'entityId'] }) +@Unique({ name: 'unique_idx', properties: ['type', 'did', 'entityId'] }) +export class AssignEntity extends BaseEntity { + /** + * Type + */ + @Index({ name: 'type' }) + @Property() + type: AssignedEntityType; + + /** + * User DID + */ + @Index({ name: 'did' }) + @Property() + did: string; + + /** + * Entity Id + */ + @Property() + entityId: string; + + /** + * Assigned + */ + @Property() + assigned: boolean; + + /** + * Owner DID + */ + @Property() + owner: string; +} diff --git a/common/src/entity/dynamic-role.ts b/common/src/entity/dynamic-role.ts new file mode 100644 index 0000000000..7dcbf68028 --- /dev/null +++ b/common/src/entity/dynamic-role.ts @@ -0,0 +1,47 @@ +import { BaseEntity } from '../models/index.js'; +import { GenerateUUIDv4 } from '@guardian/interfaces'; +import { BeforeCreate, Entity, Property } from '@mikro-orm/core'; + +/** + * Role collection + */ +@Entity() +export class DynamicRole extends BaseEntity { + /** + * Role id + */ + @Property() + uuid?: string; + + /** + * Role label + */ + @Property({ nullable: true }) + name?: string; + + /** + * Role description + */ + @Property({ nullable: true }) + description?: string; + + /** + * Role owner + */ + @Property({ nullable: true }) + owner?: string; + + /** + * Permissions + */ + @Property({ nullable: true }) + permissions?: string[]; + + /** + * Set policy defaults + */ + @BeforeCreate() + setDefaults() { + this.uuid = this.uuid || GenerateUUIDv4(); + } +} diff --git a/common/src/entity/index.ts b/common/src/entity/index.ts index 042b29dcef..2eb5c02d06 100644 --- a/common/src/entity/index.ts +++ b/common/src/entity/index.ts @@ -40,3 +40,4 @@ export * from './mint-transaction.js'; export * from './dry-run-files.js'; export * from './policy-cache-data.js'; export * from './policy-cache.js'; +export * from './assign-entity.js'; \ No newline at end of file diff --git a/common/src/entity/token.ts b/common/src/entity/token.ts index 104215084e..56eea9c13c 100644 --- a/common/src/entity/token.ts +++ b/common/src/entity/token.ts @@ -86,6 +86,12 @@ export class Token extends BaseEntity implements IToken { @Property({ nullable: true }) owner?: string; + /** + * Token creator + */ + @Property({ nullable: true }) + creator?: string; + /** * Owner */ diff --git a/common/src/hedera-modules/message/guardian-role-message.ts b/common/src/hedera-modules/message/guardian-role-message.ts new file mode 100644 index 0000000000..c75ffbe442 --- /dev/null +++ b/common/src/hedera-modules/message/guardian-role-message.ts @@ -0,0 +1,95 @@ +import { MessageAction } from './message-action.js'; +import { GuardianRoleMessageBody } from './message-body.interface.js'; +import { MessageType } from './message-type.js'; +import { VCMessage } from './vc-message.js'; + +/** + * Role message + */ +export class GuardianRoleMessage extends VCMessage { + /** + * UUID + */ + public uuid: string; + /** + * Name + */ + public name: string; + /** + * Description + */ + public description: string; + + constructor( + action: MessageAction, + type: MessageType = MessageType.GuardianRole + ) { + super(action, type); + } + + /** + * Set role + * @param role + */ + public setRole(role: { + uuid: string, + name: string, + description: string + }): void { + this.uuid = role.uuid; + this.name = role.name; + this.description = role.description; + } + + /** + * To JSON + */ + public override toJson(): any { + const result = super.toJson(); + result.uuid = this.uuid; + result.name = this.name; + result.description = this.description; + return result; + } + + /** + * To message object + */ + public override toMessageObject(): GuardianRoleMessageBody { + const result: GuardianRoleMessageBody = super.toMessageObject() as GuardianRoleMessageBody; + if (this.uuid) { + result.uuid = this.uuid; + } + if (this.name) { + result.name = this.name; + } + if (this.description) { + result.description = this.description; + } + return result; + } + + /** + * From message object + * @param json + */ + public static fromMessageObject(json: GuardianRoleMessageBody): GuardianRoleMessage { + if (!json) { + throw new Error('JSON Object is empty'); + } + + let message = new GuardianRoleMessage(json.action, json.type); + message = VCMessage._fromMessageObject(message, json); + message.uuid = json.uuid; + message.name = json.name; + message.description = json.description; + return message; + } + + /** + * Support for old messages + */ + protected override changeType(): void { + return; + } +} diff --git a/common/src/hedera-modules/message/index.ts b/common/src/hedera-modules/message/index.ts index 567f088b02..1c2f2dd3a9 100644 --- a/common/src/hedera-modules/message/index.ts +++ b/common/src/hedera-modules/message/index.ts @@ -17,3 +17,5 @@ export { TagMessage } from './tag-message.js'; export { RoleMessage } from './role-message.js'; export { ToolMessage } from './tool-message.js'; export { ContractMessage } from './contract-message.js'; +export { GuardianRoleMessage } from './guardian-role-message.js'; +export { UserPermissionsMessage } from './user-permissions-message.js'; \ No newline at end of file diff --git a/common/src/hedera-modules/message/message-action.ts b/common/src/hedera-modules/message/message-action.ts index 1ef9935c3e..3fe76abaa3 100644 --- a/common/src/hedera-modules/message/message-action.ts +++ b/common/src/hedera-modules/message/message-action.ts @@ -31,4 +31,8 @@ export enum MessageAction { DeferredDiscontinuePolicy = 'deferred-discontinue-policy', MigrateVC = 'migrate-vc-document', MigrateVP = 'migrate-vp-document', + CreateRole = 'create-role', + UpdateRole = 'update-role', + DeleteRole = 'delete-role', + SetRole = 'set-role' } diff --git a/common/src/hedera-modules/message/message-body.interface.ts b/common/src/hedera-modules/message/message-body.interface.ts index 941fad2129..6af1e17e04 100644 --- a/common/src/hedera-modules/message/message-body.interface.ts +++ b/common/src/hedera-modules/message/message-body.interface.ts @@ -466,6 +466,34 @@ export interface RoleMessageBody extends VcMessageBody { group?: string; } +/** + * Role message body + */ +export interface GuardianRoleMessageBody extends VcMessageBody { + /** + * UUID + */ + uuid?: string; + /** + * Name + */ + name?: string; + /** + * Description + */ + description?: string; +} + +/** + * Role message body + */ +export interface UserPermissionsMessageBody extends VcMessageBody { + /** + * User DID + */ + user?: string; +} + /** * Tool message body */ diff --git a/common/src/hedera-modules/message/message-server.ts b/common/src/hedera-modules/message/message-server.ts index 4a766443e2..8f9df6ebd7 100644 --- a/common/src/hedera-modules/message/message-server.ts +++ b/common/src/hedera-modules/message/message-server.ts @@ -21,6 +21,8 @@ import { ModuleMessage } from './module-message.js'; import { TagMessage } from './tag-message.js'; import { ToolMessage } from './tool-message.js'; import { RoleMessage } from './role-message.js'; +import { GuardianRoleMessage } from './guardian-role-message.js'; +import { UserPermissionsMessage } from './user-permissions-message.js'; /** * Message server @@ -63,7 +65,7 @@ export class MessageServer { constructor( operatorId: string | AccountId | null, operatorKey: string | PrivateKey | null, - signOptions: ISignOptions = {signType: SignType.INTERNAL}, + signOptions: ISignOptions = { signType: SignType.INTERNAL }, dryRun: string = null ) { this.clientOptions = { operatorId, operatorKey, dryRun }; @@ -313,6 +315,12 @@ export class MessageServer { case MessageType.RoleDocument: message = RoleMessage.fromMessageObject(json); break; + case MessageType.GuardianRole: + message = GuardianRoleMessage.fromMessageObject(json); + break; + case MessageType.UserPermissions: + message = UserPermissionsMessage.fromMessageObject(json); + break; // Default schemas case 'schema-document': message = SchemaMessage.fromMessageObject(json); diff --git a/common/src/hedera-modules/message/message-type.ts b/common/src/hedera-modules/message/message-type.ts index d48c96c09e..179af19302 100644 --- a/common/src/hedera-modules/message/message-type.ts +++ b/common/src/hedera-modules/message/message-type.ts @@ -16,6 +16,8 @@ export enum MessageType { Module = 'Module', Tag = 'Tag', RoleDocument = 'Role-Document', + GuardianRole = 'Guardian-Role-Document', Tool = 'Tool', - Contract = 'Contract' + Contract = 'Contract', + UserPermissions = 'User-Permissions' } diff --git a/common/src/hedera-modules/message/user-permissions-message.ts b/common/src/hedera-modules/message/user-permissions-message.ts new file mode 100644 index 0000000000..a99de577be --- /dev/null +++ b/common/src/hedera-modules/message/user-permissions-message.ts @@ -0,0 +1,73 @@ +import { MessageAction } from './message-action.js'; +import { UserPermissionsMessageBody } from './message-body.interface.js'; +import { MessageType } from './message-type.js'; +import { VCMessage } from './vc-message.js'; + +/** + * Role message + */ +export class UserPermissionsMessage extends VCMessage { + /** + * User DID + */ + public user: string; + + constructor( + action: MessageAction, + type: MessageType = MessageType.UserPermissions + ) { + super(action, type); + } + + /** + * Set role + * @param role + */ + public setRole(role: { + user: string + }): void { + this.user = role.user; + } + + /** + * To JSON + */ + public override toJson(): any { + const result = super.toJson(); + result.user = this.user; + return result; + } + + /** + * To message object + */ + public override toMessageObject(): UserPermissionsMessageBody { + const result: UserPermissionsMessageBody = super.toMessageObject() as UserPermissionsMessageBody; + if (this.user) { + result.user = this.user; + } + return result; + } + + /** + * From message object + * @param json + */ + public static fromMessageObject(json: UserPermissionsMessageBody): UserPermissionsMessage { + if (!json) { + throw new Error('JSON Object is empty'); + } + + let message = new UserPermissionsMessage(json.action, json.type); + message = VCMessage._fromMessageObject(message, json); + message.user = json.user; + return message; + } + + /** + * Support for old messages + */ + protected override changeType(): void { + return; + } +} diff --git a/common/src/helpers/users.ts b/common/src/helpers/users.ts index 053655149b..669723f46c 100644 --- a/common/src/helpers/users.ts +++ b/common/src/helpers/users.ts @@ -134,6 +134,24 @@ export class Users extends NatsService { return await this.sendMessage(AuthEvents.UPDATE_USER, { username, item }); } + /** + * Create default roles + * @param req + * @param item + */ + public async createDefaultRole(username: string) { + return await this.sendMessage(AuthEvents.CREATE_DEFAULT_USER_ROLE, { username }); + } + + /** + * Update current user entity + * @param req + * @param item + */ + public async setDefaultRole(username: string, owner: string) { + return await this.sendMessage(AuthEvents.SET_DEFAULT_USER_ROLE, { username, owner }); + } + /** * Save user * @param user @@ -156,7 +174,7 @@ export class Users extends NatsService { * @param password * @param role */ - public async registerNewUser(username: string, password: string, role: string) { + public async registerNewUser(username: string, password: string, role: string): Promise { return await this.sendMessage(AuthEvents.REGISTER_NEW_USER, { username, password, role }); } diff --git a/common/src/index.ts b/common/src/index.ts index 9ad2044e96..b12cc17272 100644 --- a/common/src/index.ts +++ b/common/src/index.ts @@ -1,6 +1,7 @@ import 'reflect-metadata'; import * as ent from './entity/index.js'; + export * from './models/index.js'; export * from './decorators/singleton.js'; export * from './helpers/index.js'; @@ -13,5 +14,6 @@ export * from './database-modules/index.js'; export * from './secret-manager/index.js'; export * from './import-export/index.js'; export * from './xlsx/index.js'; +export * from './metrics/index.js'; export const entities = Object.values(ent); diff --git a/common/src/interfaces/auth.interface.ts b/common/src/interfaces/auth.interface.ts index ebaf732be4..bf0ad200ef 100644 --- a/common/src/interfaces/auth.interface.ts +++ b/common/src/interfaces/auth.interface.ts @@ -1,6 +1,6 @@ import { Request } from 'express'; import WebSocket from 'ws'; -import { UserRole } from '@guardian/interfaces'; +import { IGroup, UserRole } from '@guardian/interfaces'; /** * Authenticated user interface @@ -38,6 +38,14 @@ export interface IAuthUser { * Use fireblocks signing */ useFireblocksSigning: boolean; + /** + * Group name + */ + permissionsGroup?: IGroup[]; + /** + * Permissions + */ + permissions?: string[]; } /** diff --git a/common/src/interfaces/providers/meeco.ts b/common/src/interfaces/providers/meeco.ts index e34ffa7612..17cab96280 100644 --- a/common/src/interfaces/providers/meeco.ts +++ b/common/src/interfaces/providers/meeco.ts @@ -1,112 +1,112 @@ export interface MeecoJwt { - iat: number - vp: Vp - nbf: number - aud: string - nonce: string - iss: string + iat: number + vp: Vp + nbf: number + aud: string + nonce: string + iss: string } export interface Vp { - '@context': string[] - type: string[] - verifiableCredential: string[] + '@context': string[] + type: string[] + verifiableCredential: string[] } export interface VerifiableCredential { - iat: number - exp: number - vc: Vc - sub: string - nbf: number - iss: string + iat: number + exp: number + vc: Vc + sub: string + nbf: number + iss: string } export interface CredentialStatus { - id: string - type: string - statusPurpose: string - statusListIndex: number - statusListCredential: string + id: string + type: string + statusPurpose: string + statusListIndex: number + statusListCredential: string } export interface Vc { - '@context': string[] - id: string - type: string[] - issuer: Issuer - credentialSubject: CredentialSubject - issuanceDate: string - credentialSchema: CredentialSchema - expirationDate: string - credentialStatus: CredentialStatus + '@context': string[] + id: string + type: string[] + issuer: Issuer + credentialSubject: CredentialSubject + issuanceDate: string + credentialSchema: CredentialSchema + expirationDate: string + credentialStatus: CredentialStatus } export interface Issuer { - id: string - name: string + id: string + name: string } export interface CredentialSubject { - id: string - familyName: string - firstName: string - dateOfBirth: string - personalIdentifier: string - nameAndFamilyNameAtBirth: string - placeOfBirth: string - currentAddress: string - gender: string + id: string + familyName: string + firstName: string + dateOfBirth: string + personalIdentifier: string + nameAndFamilyNameAtBirth: string + placeOfBirth: string + currentAddress: string + gender: string } export interface CredentialSchema { - id: string - type: string + id: string + type: string } export interface MeecoApprovedSubmission { - vpRequest: VpRequest - cid: string - role: string + vpRequest: VpRequest + cid: string + role: string } export interface VpRequest { - submission: Submission + submission: Submission } export interface Submission { - id: string - presentation_request_id: string - vp_token: string - id_token: string - state: any - status: string - created_at: string - updated_at: string - verification_result: any - last_verified_at: any + id: string + presentation_request_id: string + vp_token: string + id_token: string + state: any + status: string + created_at: string + updated_at: string + verification_result: any + last_verified_at: any } export interface VerifiableCredentialStatusListResult { - iat: number - vc: VcStatusList - nbf: number - iss: string - sub: string + iat: number + vc: VcStatusList + nbf: number + iss: string + sub: string } export interface VcStatusList { - 'context': string[] - id: string - type: string[] - issuer: string - issuanceDate: string - credentialSubject: CredentialSubjectStatusList + 'context': string[] + id: string + type: string[] + issuer: string + issuanceDate: string + credentialSubject: CredentialSubjectStatusList } export interface CredentialSubjectStatusList { - id: string - type: string - statusPurpose: string - encodedList: string + id: string + type: string + statusPurpose: string + encodedList: string } diff --git a/common/src/metrics/index.ts b/common/src/metrics/index.ts new file mode 100644 index 0000000000..5a17648fa7 --- /dev/null +++ b/common/src/metrics/index.ts @@ -0,0 +1 @@ +export * from './metrics-service.js' diff --git a/common/src/metrics/metrics-service.ts b/common/src/metrics/metrics-service.ts new file mode 100644 index 0000000000..ab622c1eaa --- /dev/null +++ b/common/src/metrics/metrics-service.ts @@ -0,0 +1,29 @@ +import express, { Express } from 'express' +import client, { Registry } from 'prom-client'; +import process from 'process'; +import { Logger } from '../helpers/index.js'; + +export class MetricsService{ + private readonly logger: Logger; + private readonly server: Express; + private readonly register: Registry; + private readonly port: number; + + constructor() { + this.server = express(); + this.register = client.register; + this.logger = new Logger(); + this.port = parseInt(process.env.PROMETEUS_PORT, 10) || 5007; + } + + public init(): void { + this.server.get('/', async (_, res) => { + res.set('Content-Type', this.register.contentType); + res.send(await this.register.metrics()) + }); + + this.server.listen(this.port, () => { + this.logger.info(`Prometeus client listening on port ${this.port}`); + }) + } +} diff --git a/configs/.env..indexer.system b/configs/.env..indexer.system new file mode 100644 index 0000000000..535bc141fd --- /dev/null +++ b/configs/.env..indexer.system @@ -0,0 +1,5 @@ +MQ_ADDRESS="message-broker" +DB_HOST="mongo" +IPFS_GATEWAY='http://ipfs-node:8080/ipfs/${cid}' +HEDERA_NET="testnet" # "mainnet" | "testnet" | "previewnet" | "localnode" +PREUSED_HEDERA_NET="testnet" diff --git a/configs/.env.develop.indexer.system b/configs/.env.develop.indexer.system new file mode 100644 index 0000000000..535bc141fd --- /dev/null +++ b/configs/.env.develop.indexer.system @@ -0,0 +1,5 @@ +MQ_ADDRESS="message-broker" +DB_HOST="mongo" +IPFS_GATEWAY='http://ipfs-node:8080/ipfs/${cid}' +HEDERA_NET="testnet" # "mainnet" | "testnet" | "previewnet" | "localnode" +PREUSED_HEDERA_NET="testnet" diff --git a/docker-compose-indexer.yml b/docker-compose-indexer.yml new file mode 100644 index 0000000000..684bdfda02 --- /dev/null +++ b/docker-compose-indexer.yml @@ -0,0 +1,105 @@ +version: "3.8" +services: + mongo: + image: mongo:6.0.13 + command: "--setParameter allowDiskUseByDefault=true" + restart: always + expose: + - 27017 + + mongo-express: + image: mongo-express:1.0.2-20 + expose: + - 8081 + environment: + ME_CONFIG_MONGODB_SERVER: mongo + ME_CONFIG_MONGODB_PORT: 27017 + ME_CONFIG_SITE_BASEURL: /mongo-admin # default credentials: admin/pass + depends_on: + - mongo + + ipfs-node: + image: ipfs/kubo:latest + ports: + - "5001:5001" + - "4001:4001" + - "8080:8080" + + message-broker: + image: nats:2.9.24 + expose: + - 4222 + ports: + - '8222:8222' + command: '--http_port 8222' + + indexer-worker-service: + env_file: + - ./configs/.env.${GUARDIAN_ENV}.indexer.system + build: + context: . + dockerfile: ./indexer-worker-service/Dockerfile + init: true + depends_on: + - mongo + - message-broker + environment: + - GUARDIAN_ENV=${GUARDIAN_ENV} + expose: + - 6555 + volumes: + - ./indexer-worker-service/tls:/usr/local/indexer-worker-service/tls:ro + - ./indexer-worker-service/configs:/usr/local/indexer-worker-service/configs:ro + deploy: + replicas: 5 + + indexer-api-gateway: + env_file: + - ./configs/.env.${GUARDIAN_ENV}.indexer.system + build: + context: . + dockerfile: ./indexer-api-gateway/Dockerfile + init: true + expose: + - 3002 + - 6555 + depends_on: + - mongo + - message-broker + - indexer-service + environment: + - GUARDIAN_ENV=${GUARDIAN_ENV} + volumes: + - ./indexer-api-gateway/configs:/usr/local/indexer-api-gateway/configs:ro + + indexer-service: + env_file: + - ./configs/.env.${GUARDIAN_ENV}.indexer.system + build: + context: . + dockerfile: ./indexer-service/Dockerfile + init: true + ports: + - "5007:5007" + volumes: + - ./indexer-service/tls:/usr/local/indexer-service/tls:ro + - ./indexer-service/configs:/usr/local/indexer-service/configs:ro + depends_on: + - mongo + - message-broker + environment: + - GUARDIAN_ENV=${GUARDIAN_ENV} + expose: + - 6555 + - 5007 + + indexer-web-proxy: + build: + context: . + dockerfile: ./indexer-web-proxy/Dockerfile + init: true + ports: + - "3000:80" + depends_on: + - indexer-api-gateway + - indexer-service diff --git a/docker-compose.yml b/docker-compose.yml index 9d09ae59de..d985ca9195 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -27,8 +27,6 @@ services: restart: always expose: - 6379 - ports: - - "6379:6379" ipfs-node: image: ipfs/kubo:v0.26.0 @@ -99,7 +97,7 @@ services: build: context: . dockerfile: ./worker-service/Dockerfile - init: true + init: true depends_on: ipfs-node: condition: service_healthy @@ -121,7 +119,7 @@ services: build: context: . dockerfile: ./auth-service/Dockerfile.demo - init: true + init: true ports: - '5005:5005' volumes: @@ -144,7 +142,7 @@ services: build: context: . dockerfile: ./api-gateway/Dockerfile.demo - init: true + init: true expose: - 3002 - 6555 @@ -166,7 +164,7 @@ services: build: context: . dockerfile: ./ai-service/Dockerfile - init: true + init: true expose: - 3013 depends_on: @@ -209,7 +207,7 @@ services: build: context: . dockerfile: ./guardian-service/Dockerfile - init: true + init: true ports: - "5007:5007" volumes: diff --git a/docs/.gitbook/assets/0 (1) (1) (1) (1) (1) (1).png b/docs/.gitbook/assets/0 (1) (1) (1) (1) (1) (1).png new file mode 100644 index 0000000000..9cb09d3045 Binary files /dev/null and b/docs/.gitbook/assets/0 (1) (1) (1) (1) (1) (1).png differ diff --git a/docs/.gitbook/assets/0 (1) (1) (1) (1) (1).png b/docs/.gitbook/assets/0 (1) (1) (1) (1) (1).png index 9cb09d3045..005f784fe9 100644 Binary files a/docs/.gitbook/assets/0 (1) (1) (1) (1) (1).png and b/docs/.gitbook/assets/0 (1) (1) (1) (1) (1).png differ diff --git a/docs/.gitbook/assets/0 (1) (1) (1) (1).png b/docs/.gitbook/assets/0 (1) (1) (1) (1).png index 005f784fe9..2353a305a3 100644 Binary files a/docs/.gitbook/assets/0 (1) (1) (1) (1).png and b/docs/.gitbook/assets/0 (1) (1) (1) (1).png differ diff --git a/docs/.gitbook/assets/0 (1) (1) (1).png b/docs/.gitbook/assets/0 (1) (1) (1).png index 2353a305a3..249147ab38 100644 Binary files a/docs/.gitbook/assets/0 (1) (1) (1).png and b/docs/.gitbook/assets/0 (1) (1) (1).png differ diff --git a/docs/.gitbook/assets/0 (1) (1).png b/docs/.gitbook/assets/0 (1) (1).png index 249147ab38..330b81ffa8 100644 Binary files a/docs/.gitbook/assets/0 (1) (1).png and b/docs/.gitbook/assets/0 (1) (1).png differ diff --git a/docs/.gitbook/assets/0 (1).png b/docs/.gitbook/assets/0 (1).png index 330b81ffa8..250acc4325 100644 Binary files a/docs/.gitbook/assets/0 (1).png and b/docs/.gitbook/assets/0 (1).png differ diff --git a/docs/.gitbook/assets/0 (14).png b/docs/.gitbook/assets/0 (14).png new file mode 100644 index 0000000000..2b779d5397 Binary files /dev/null and b/docs/.gitbook/assets/0 (14).png differ diff --git a/docs/.gitbook/assets/0 (15).png b/docs/.gitbook/assets/0 (15).png new file mode 100644 index 0000000000..9f5a437d4e Binary files /dev/null and b/docs/.gitbook/assets/0 (15).png differ diff --git a/docs/.gitbook/assets/0.png b/docs/.gitbook/assets/0.png index 250acc4325..04acf34de2 100644 Binary files a/docs/.gitbook/assets/0.png and b/docs/.gitbook/assets/0.png differ diff --git a/docs/.gitbook/assets/1 (16).png b/docs/.gitbook/assets/1 (16).png new file mode 100644 index 0000000000..56f6c80793 Binary files /dev/null and b/docs/.gitbook/assets/1 (16).png differ diff --git a/docs/.gitbook/assets/1 (17).png b/docs/.gitbook/assets/1 (17).png new file mode 100644 index 0000000000..58aa236452 Binary files /dev/null and b/docs/.gitbook/assets/1 (17).png differ diff --git a/docs/.gitbook/assets/10 (15).png b/docs/.gitbook/assets/10 (15).png new file mode 100644 index 0000000000..698c636d6d Binary files /dev/null and b/docs/.gitbook/assets/10 (15).png differ diff --git a/docs/.gitbook/assets/10 (16).png b/docs/.gitbook/assets/10 (16).png new file mode 100644 index 0000000000..53c99702a4 Binary files /dev/null and b/docs/.gitbook/assets/10 (16).png differ diff --git a/docs/.gitbook/assets/11 (13).png b/docs/.gitbook/assets/11 (13).png new file mode 100644 index 0000000000..00e3fd28a3 Binary files /dev/null and b/docs/.gitbook/assets/11 (13).png differ diff --git a/docs/.gitbook/assets/2 (18).png b/docs/.gitbook/assets/2 (18).png new file mode 100644 index 0000000000..9bcaac5442 Binary files /dev/null and b/docs/.gitbook/assets/2 (18).png differ diff --git a/docs/.gitbook/assets/2 (19).png b/docs/.gitbook/assets/2 (19).png new file mode 100644 index 0000000000..5947bffac2 Binary files /dev/null and b/docs/.gitbook/assets/2 (19).png differ diff --git a/docs/.gitbook/assets/3 (15).png b/docs/.gitbook/assets/3 (15).png new file mode 100644 index 0000000000..7336e8ad64 Binary files /dev/null and b/docs/.gitbook/assets/3 (15).png differ diff --git a/docs/.gitbook/assets/3 (16).png b/docs/.gitbook/assets/3 (16).png new file mode 100644 index 0000000000..941ce6f14b Binary files /dev/null and b/docs/.gitbook/assets/3 (16).png differ diff --git a/docs/.gitbook/assets/4 (13).png b/docs/.gitbook/assets/4 (13).png new file mode 100644 index 0000000000..a9ba175657 Binary files /dev/null and b/docs/.gitbook/assets/4 (13).png differ diff --git a/docs/.gitbook/assets/4 (14).png b/docs/.gitbook/assets/4 (14).png new file mode 100644 index 0000000000..cc707e0cf7 Binary files /dev/null and b/docs/.gitbook/assets/4 (14).png differ diff --git a/docs/.gitbook/assets/5 (16).png b/docs/.gitbook/assets/5 (16).png new file mode 100644 index 0000000000..b58db86848 Binary files /dev/null and b/docs/.gitbook/assets/5 (16).png differ diff --git a/docs/.gitbook/assets/5 (17).png b/docs/.gitbook/assets/5 (17).png new file mode 100644 index 0000000000..32cf10a4ac Binary files /dev/null and b/docs/.gitbook/assets/5 (17).png differ diff --git a/docs/.gitbook/assets/6 (15).png b/docs/.gitbook/assets/6 (15).png new file mode 100644 index 0000000000..20c4e97e5a Binary files /dev/null and b/docs/.gitbook/assets/6 (15).png differ diff --git a/docs/.gitbook/assets/6 (16).png b/docs/.gitbook/assets/6 (16).png new file mode 100644 index 0000000000..87f7455cbf Binary files /dev/null and b/docs/.gitbook/assets/6 (16).png differ diff --git a/docs/.gitbook/assets/7 (15).png b/docs/.gitbook/assets/7 (15).png new file mode 100644 index 0000000000..8773e55759 Binary files /dev/null and b/docs/.gitbook/assets/7 (15).png differ diff --git a/docs/.gitbook/assets/7 (16).png b/docs/.gitbook/assets/7 (16).png new file mode 100644 index 0000000000..1c5e16a210 Binary files /dev/null and b/docs/.gitbook/assets/7 (16).png differ diff --git a/docs/.gitbook/assets/8 (16).png b/docs/.gitbook/assets/8 (16).png new file mode 100644 index 0000000000..64a0e98d7f Binary files /dev/null and b/docs/.gitbook/assets/8 (16).png differ diff --git a/docs/.gitbook/assets/8 (17).png b/docs/.gitbook/assets/8 (17).png new file mode 100644 index 0000000000..db3194e062 Binary files /dev/null and b/docs/.gitbook/assets/8 (17).png differ diff --git a/docs/.gitbook/assets/9 (14).png b/docs/.gitbook/assets/9 (14).png new file mode 100644 index 0000000000..d6acee6f69 Binary files /dev/null and b/docs/.gitbook/assets/9 (14).png differ diff --git a/docs/.gitbook/assets/9 (15).png b/docs/.gitbook/assets/9 (15).png new file mode 100644 index 0000000000..531711011b Binary files /dev/null and b/docs/.gitbook/assets/9 (15).png differ diff --git a/docs/.gitbook/assets/image (603).png b/docs/.gitbook/assets/image (603).png new file mode 100644 index 0000000000..1587730b84 Binary files /dev/null and b/docs/.gitbook/assets/image (603).png differ diff --git a/docs/.gitbook/assets/image (604).png b/docs/.gitbook/assets/image (604).png new file mode 100644 index 0000000000..6be67cfb99 Binary files /dev/null and b/docs/.gitbook/assets/image (604).png differ diff --git a/docs/.gitbook/assets/image (605).png b/docs/.gitbook/assets/image (605).png new file mode 100644 index 0000000000..f09b0e8899 Binary files /dev/null and b/docs/.gitbook/assets/image (605).png differ diff --git a/docs/.gitbook/assets/image (617).png b/docs/.gitbook/assets/image (617).png new file mode 100644 index 0000000000..ad4bc19103 Binary files /dev/null and b/docs/.gitbook/assets/image (617).png differ diff --git a/docs/.gitbook/assets/image (618).png b/docs/.gitbook/assets/image (618).png new file mode 100644 index 0000000000..008ec29af2 Binary files /dev/null and b/docs/.gitbook/assets/image (618).png differ diff --git a/docs/.gitbook/assets/image (619).png b/docs/.gitbook/assets/image (619).png new file mode 100644 index 0000000000..e81b7c5e95 Binary files /dev/null and b/docs/.gitbook/assets/image (619).png differ diff --git a/docs/.gitbook/assets/image (620).png b/docs/.gitbook/assets/image (620).png new file mode 100644 index 0000000000..c9a9b79b93 Binary files /dev/null and b/docs/.gitbook/assets/image (620).png differ diff --git a/docs/.gitbook/assets/image (621).png b/docs/.gitbook/assets/image (621).png new file mode 100644 index 0000000000..c05b84c60f Binary files /dev/null and b/docs/.gitbook/assets/image (621).png differ diff --git a/docs/.gitbook/assets/image (622).png b/docs/.gitbook/assets/image (622).png new file mode 100644 index 0000000000..24acc408fa Binary files /dev/null and b/docs/.gitbook/assets/image (622).png differ diff --git a/docs/.gitbook/assets/image (623).png b/docs/.gitbook/assets/image (623).png new file mode 100644 index 0000000000..a6ef595938 Binary files /dev/null and b/docs/.gitbook/assets/image (623).png differ diff --git a/docs/.gitbook/assets/image (624).png b/docs/.gitbook/assets/image (624).png new file mode 100644 index 0000000000..43a69ac2dd Binary files /dev/null and b/docs/.gitbook/assets/image (624).png differ diff --git a/docs/.gitbook/assets/image (625).png b/docs/.gitbook/assets/image (625).png new file mode 100644 index 0000000000..d6557bd25c Binary files /dev/null and b/docs/.gitbook/assets/image (625).png differ diff --git a/docs/.gitbook/assets/image (626).png b/docs/.gitbook/assets/image (626).png new file mode 100644 index 0000000000..0e6eb2d48a Binary files /dev/null and b/docs/.gitbook/assets/image (626).png differ diff --git a/docs/.gitbook/assets/image (627).png b/docs/.gitbook/assets/image (627).png new file mode 100644 index 0000000000..65859e9b97 Binary files /dev/null and b/docs/.gitbook/assets/image (627).png differ diff --git a/docs/.gitbook/assets/image (628).png b/docs/.gitbook/assets/image (628).png new file mode 100644 index 0000000000..a4ed8e923e Binary files /dev/null and b/docs/.gitbook/assets/image (628).png differ diff --git a/docs/.gitbook/assets/image (629).png b/docs/.gitbook/assets/image (629).png new file mode 100644 index 0000000000..6a0b1a350f Binary files /dev/null and b/docs/.gitbook/assets/image (629).png differ diff --git a/docs/.gitbook/assets/image (630).png b/docs/.gitbook/assets/image (630).png new file mode 100644 index 0000000000..8f46d676e7 Binary files /dev/null and b/docs/.gitbook/assets/image (630).png differ diff --git a/docs/.gitbook/assets/image (631).png b/docs/.gitbook/assets/image (631).png new file mode 100644 index 0000000000..603a1a327a Binary files /dev/null and b/docs/.gitbook/assets/image (631).png differ diff --git a/docs/.gitbook/assets/image (632).png b/docs/.gitbook/assets/image (632).png new file mode 100644 index 0000000000..6b0f5cbd05 Binary files /dev/null and b/docs/.gitbook/assets/image (632).png differ diff --git a/docs/.gitbook/assets/image (633).png b/docs/.gitbook/assets/image (633).png new file mode 100644 index 0000000000..dfa06df093 Binary files /dev/null and b/docs/.gitbook/assets/image (633).png differ diff --git a/docs/.gitbook/assets/image (634).png b/docs/.gitbook/assets/image (634).png new file mode 100644 index 0000000000..017e6c263a Binary files /dev/null and b/docs/.gitbook/assets/image (634).png differ diff --git a/docs/.gitbook/assets/image (635).png b/docs/.gitbook/assets/image (635).png new file mode 100644 index 0000000000..5441df0b9f Binary files /dev/null and b/docs/.gitbook/assets/image (635).png differ diff --git a/docs/.gitbook/assets/image (636).png b/docs/.gitbook/assets/image (636).png new file mode 100644 index 0000000000..b9cb96f1c0 Binary files /dev/null and b/docs/.gitbook/assets/image (636).png differ diff --git a/docs/.gitbook/assets/image (637).png b/docs/.gitbook/assets/image (637).png new file mode 100644 index 0000000000..d36b40d610 Binary files /dev/null and b/docs/.gitbook/assets/image (637).png differ diff --git a/docs/.gitbook/assets/image (638).png b/docs/.gitbook/assets/image (638).png new file mode 100644 index 0000000000..f6a8727ef2 Binary files /dev/null and b/docs/.gitbook/assets/image (638).png differ diff --git a/docs/.gitbook/assets/image (639).png b/docs/.gitbook/assets/image (639).png new file mode 100644 index 0000000000..a2bc5955f9 Binary files /dev/null and b/docs/.gitbook/assets/image (639).png differ diff --git a/docs/.gitbook/assets/image (640).png b/docs/.gitbook/assets/image (640).png new file mode 100644 index 0000000000..602c269f0c Binary files /dev/null and b/docs/.gitbook/assets/image (640).png differ diff --git a/docs/.gitbook/assets/image (641).png b/docs/.gitbook/assets/image (641).png new file mode 100644 index 0000000000..ab4b2bc3b5 Binary files /dev/null and b/docs/.gitbook/assets/image (641).png differ diff --git a/docs/.gitbook/assets/image (642).png b/docs/.gitbook/assets/image (642).png new file mode 100644 index 0000000000..8544368811 Binary files /dev/null and b/docs/.gitbook/assets/image (642).png differ diff --git a/docs/.gitbook/assets/image (643).png b/docs/.gitbook/assets/image (643).png new file mode 100644 index 0000000000..03097dedee Binary files /dev/null and b/docs/.gitbook/assets/image (643).png differ diff --git a/docs/.gitbook/assets/image (644).png b/docs/.gitbook/assets/image (644).png new file mode 100644 index 0000000000..3e0b26334a Binary files /dev/null and b/docs/.gitbook/assets/image (644).png differ diff --git a/docs/.gitbook/assets/image (645).png b/docs/.gitbook/assets/image (645).png new file mode 100644 index 0000000000..35811a26f3 Binary files /dev/null and b/docs/.gitbook/assets/image (645).png differ diff --git a/docs/.gitbook/assets/image (646).png b/docs/.gitbook/assets/image (646).png new file mode 100644 index 0000000000..ecabd712dc Binary files /dev/null and b/docs/.gitbook/assets/image (646).png differ diff --git a/docs/.gitbook/assets/image (647).png b/docs/.gitbook/assets/image (647).png new file mode 100644 index 0000000000..150b7ce93b Binary files /dev/null and b/docs/.gitbook/assets/image (647).png differ diff --git a/docs/.gitbook/assets/swagger (2) (1).yaml b/docs/.gitbook/assets/swagger (2) (1).yaml new file mode 100644 index 0000000000..26784dd621 --- /dev/null +++ b/docs/.gitbook/assets/swagger (2) (1).yaml @@ -0,0 +1,12210 @@ +openapi: 3.0.0 +paths: + /accounts/session: + get: + operationId: AccountApi_getSession + summary: Returns current session of the user. + description: Returns current user session. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsSessionResponseDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_0 + - accounts + security: + - bearer: [] + /accounts/register: + post: + operationId: AccountApi_register + summary: Registers a new user account. + description: Object that contain username, password and role (optional) fields. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RegisterUserDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsResponseDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + /accounts/login: + post: + operationId: AccountApi_login + summary: Logs user into the system. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LoginUserDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsSessionResponseDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + /accounts/access-token: + post: + operationId: AccountApi_getAccessToken + summary: Returns access token. + description: Returns access token. + parameters: [] + responses: + '200': + description: Successful operation. + tags: *ref_0 + /accounts: + get: + operationId: AccountApi_getAllAccounts + summary: Returns a list of users, excluding Standard Registry and Auditors. + description: >- + Returns all users except those with roles Standard Registry and Auditor. + Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsResponseDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + security: + - bearerAuth: [] + /accounts/standard-registries: + get: + operationId: AccountApi_getStandatdRegistries + summary: Returns all Standard Registries. + description: Returns all Standard Registries. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsResponseDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + security: + - bearerAuth: [] + /accounts/standard-registries/aggregated: + get: + operationId: AccountApi_getAggregatedStandardRegistries + summary: Returns all Standard Registries aggregated with polices and vcDocuments. + description: Returns all Standard Registries aggregated with polices and vcDocuments + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AggregatedDTOItem' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + security: + - bearerAuth: [] + /accounts/balance: + get: + operationId: AccountApi_getBalance + summary: Returns user's Hedera account balance. + description: Requests current Hedera account balance. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BalanceResponseDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + security: + - bearerAuth: [] + /analytics/search/policies: + post: + operationId: AnalyticsApi_searchPolicies + summary: Search policies. + description: >- + Search policies. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterSearchPoliciesDTO' + examples: + Filter: + value: + policyId: '000000000000000000000000' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SearchPoliciesDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_1 + - analytics + security: + - bearerAuth: [] + /analytics/compare/policies: + post: + operationId: AnalyticsApi_comparePolicies + summary: Compare policies. + description: >- + Compare policies. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterPoliciesDTO' + examples: + Filter1: + value: + policyId1: '000000000000000000000001' + policyId2: '000000000000000000000002' + eventsLvl: '0' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + Filter2: + value: + policyIds: + - '000000000000000000000001' + - '000000000000000000000002' + eventsLvl: '0' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ComparePoliciesDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/modules: + post: + operationId: AnalyticsApi_compareModules + summary: Compare modules. + description: >- + Compare modules. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterModulesDTO' + examples: + Filter: + value: + moduleId1: '000000000000000000000001' + moduleId2: '000000000000000000000002' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareModulesDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/schemas: + post: + operationId: AnalyticsApi_compareSchemas + summary: Compare schemas. + description: >- + Compare schemas. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterSchemasDTO' + examples: + Filter: + value: + schemaId1: '000000000000000000000001' + schemaId2: '000000000000000000000002' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareSchemasDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/documents: + post: + operationId: AnalyticsApi_compareDocuments + summary: Compare documents. + description: >- + Compare documents. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterDocumentsDTO' + examples: + Filter1: + value: + documentId1: '000000000000000000000001' + documentId2: '000000000000000000000002' + Filter2: + value: + documentIds: + - '000000000000000000000001' + - '000000000000000000000002' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareDocumentsDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/tools: + post: + operationId: AnalyticsApi_compareTools + summary: Compare tools. + description: >- + Compare tools. Only users with the Standard Registry role are allowed to + make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterToolsDTO' + examples: + Filter1: + value: + toolId1: '000000000000000000000001' + toolId2: '000000000000000000000002' + Filter2: + value: + toolIds: + - '000000000000000000000001' + - '000000000000000000000002' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareToolsDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/policies/export: + post: + operationId: AnalyticsApi_comparePoliciesExport + summary: Compare policies. + description: >- + Compare policies. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterPoliciesDTO' + examples: + Filter1: + value: + policyId1: '000000000000000000000001' + policyId2: '000000000000000000000002' + eventsLvl: '0' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + Filter2: + value: + policyIds: + - '000000000000000000000001' + - '000000000000000000000002' + eventsLvl: '0' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/modules/export: + post: + operationId: AnalyticsApi_compareModulesExport + summary: Compare modules. + description: >- + Compare modules. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterModulesDTO' + examples: + Filter: + value: + moduleId1: '000000000000000000000001' + moduleId2: '000000000000000000000002' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/schemas/export: + post: + operationId: AnalyticsApi_compareSchemasExport + summary: Compare schemas. + description: >- + Compare schemas. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterSchemasDTO' + examples: + Filter: + value: + schemaId1: '000000000000000000000001' + schemaId2: '000000000000000000000002' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/documents/export: + post: + operationId: AnalyticsApi_compareDocumentsExport + summary: Compare documents. + description: >- + Compare documents. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterDocumentsDTO' + examples: + Filter1: + value: + documentId1: '000000000000000000000001' + documentId2: '000000000000000000000002' + Filter2: + value: + documentIds: + - '000000000000000000000001' + - '000000000000000000000002' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/compare/tools/export: + post: + operationId: AnalyticsApi_compareToolsExport + summary: Compare tools. + description: >- + Compare tools. Only users with the Standard Registry role are allowed to + make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterToolsDTO' + examples: + Filter1: + value: + toolId1: '000000000000000000000001' + toolId2: '000000000000000000000002' + Filter2: + value: + toolIds: + - '000000000000000000000001' + - '000000000000000000000002' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /analytics/search/blocks: + post: + operationId: AnalyticsApi_searchBlocks + summary: Search same blocks. + description: >- + Search same blocks. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterSearchPoliciesDTO' + examples: + Filter: + value: + uuid: '' + config: {} + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SearchPoliciesDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearerAuth: [] + /artifacts: + get: + tags: + - artifacts + description: Returns all artifacts. + security: + - bearerAuth: [] + summary: Returns all artifacts. + parameters: + - in: query + name: policyId + schema: + type: string + description: Policy identifier + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set + examples: + pageIndex: + summary: Example of a pageIndex + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The numbers of items to return + examples: + pageSize: + summary: Example of a pageSize + value: 100 + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Artifact' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /artifacts/{parentId}: + post: + operationId: ArtifactApi_uploadArtifacts + summary: Upload artifact. + description: Upload artifact. For users with the Standard Registry role only. + parameters: + - name: parentId + required: true + in: path + description: Parent ID + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ArtifactDTOItem' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: + - artifacts + security: + - bearerAuth: [] + /artifacts/{artifactId}: + delete: + tags: + - artifacts + description: Delete artifact. + security: + - bearerAuth: [] + summary: Delete artifact. + parameters: + - in: path + name: artifactId + schema: + type: string + required: true + description: Artifact identifier + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /contracts: + get: + operationId: ContractsApi_getContracts + summary: Return a list of all contracts. + description: Returns all contracts. + parameters: + - name: type + required: false + in: query + description: Contract type + example: RETIRE + schema: + enum: + - WIPE + - RETIRE + type: string + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + responses: + '200': + description: Contracts. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ContractDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_2 + - contracts + security: + - bearer: [] + post: + operationId: ContractsApi_createContract + summary: Create contract. + description: >- + Create smart-contract. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + description: + type: string + responses: + '201': + description: Created contract. + content: + application/json: + schema: + $ref: '#/components/schemas/ContractDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/import: + post: + operationId: ContractsApi_importContract + summary: Import contract. + description: >- + Import smart-contract. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + contractId: + type: string + description: Hedera Identifier + example: 0.0.1 + description: + type: string + required: + - contractId + responses: + '200': + description: Imported contract. + content: + application/json: + schema: + $ref: '#/components/schemas/ContractDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/{contractId}/permissions: + get: + operationId: ContractsApi_contractPermissions + summary: Get contract permissions. + description: >- + Get smart-contract permissions. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Contract permissions. + content: + application/json: + schema: + type: number + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/{contractId}: + delete: + operationId: ContractsApi_removeContract + summary: Remove contract. + description: >- + Remove smart-contract. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/requests: + get: + operationId: ContractsApi_getWipeRequests + summary: Return a list of all wipe requests. + description: >- + Returns all wipe requests. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: false + in: query + description: Contract identifier + example: 0.0.1 + schema: + type: string + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/WiperRequestDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/{contractId}/requests/enable: + post: + operationId: ContractsApi_enableWipeRequests + summary: Enable wipe requests. + description: >- + Enable wipe contract requests. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: contractId + required: false + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/{contractId}/requests/disable: + post: + operationId: ContractsApi_disableWipeRequests + summary: Disable wipe requests. + description: >- + Disable wipe contract requests. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: contractId + required: false + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/requests/{requestId}/approve: + post: + operationId: ContractsApi_approveWipeRequest + summary: Approve wipe request. + description: >- + Approve wipe contract request. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: requestId + required: true + in: path + description: Request identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/requests/{requestId}/reject: + delete: + operationId: ContractsApi_rejectWipeRequest + summary: Reject wipe request. + description: >- + Reject wipe contract request. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: ban + required: false + in: query + description: Reject and ban + schema: + type: boolean + - name: requestId + required: true + in: path + description: Request identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/{contractId}/requests: + delete: + operationId: ContractsApi_clearWipeRequests + summary: Clear wipe requests. + description: >- + Clear wipe contract requests. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/{contractId}/admin/{hederaId}: + post: + operationId: ContractsApi_wipeAddAdmin + summary: Add wipe admin. + description: >- + Add wipe contract admin. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + delete: + operationId: ContractsApi_wipeRemoveAdmin + summary: Remove wipe admin. + description: >- + Remove wipe contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/{contractId}/manager/{hederaId}: + post: + operationId: ContractsApi_wipeAddManager + summary: Add wipe manager. + description: >- + Add wipe contract manager. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + delete: + operationId: ContractsApi_wipeRemoveManager + summary: Remove wipe manager. + description: >- + Remove wipe contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/wipe/{contractId}/wiper/{hederaId}: + post: + operationId: ContractsApi_wipeAddWiper + summary: Add wipe wiper. + description: >- + Add wipe contract wiper. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + delete: + operationId: ContractsApi_wipeRemoveWiper + summary: Remove wipe wiper. + description: >- + Remove wipe contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/{contractId}/pools/sync: + post: + operationId: ContractsApi_retireSyncPools + summary: Sync retire pools. + description: >- + Sync retire contract pools. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: false + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Sync date. + content: + application/json: + schema: + $ref: '#/components/schemas/Date' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/requests: + get: + operationId: ContractsApi_getRetireRequests + summary: Return a list of all retire requests. + description: Returns all retire requests. + parameters: + - name: contractId + required: false + in: query + description: Contract identifier + example: 0.0.1 + schema: + type: string + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RetireRequestDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/pools: + get: + operationId: ContractsApi_getRetirePools + summary: Return a list of all retire pools. + description: Returns all retire pools. + parameters: + - name: tokens + required: false + in: query + description: Tokens + example: 0.0.1,0.0.2,0.0.3 + schema: + type: string + - name: contractId + required: false + in: query + description: Contract identifier + example: 0.0.1 + schema: + type: string + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RetirePoolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/{contractId}/requests: + delete: + operationId: ContractsApi_clearRetireRequests + summary: Clear retire requests. + description: >- + Clear retire contract requests. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: contractId + required: false + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/{contractId}/pools: + delete: + operationId: ContractsApi_clearRetirePools + summary: Clear retire pools. + description: >- + Clear retire contract pools. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: false + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + post: + operationId: ContractsApi_setRetirePool + summary: Set retire pool. + description: >- + Set retire contract pool. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: contractId + required: false + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RetirePoolTokenDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RetirePoolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/pools/{poolId}: + delete: + operationId: ContractsApi_unsetRetirePool + summary: Unset retire pool. + description: >- + Unset retire contract pool. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: poolId + required: false + in: path + description: Pool Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/requests/{requestId}: + delete: + operationId: ContractsApi_unsetRetireRequest + summary: Unset retire request. + description: >- + Unset retire contract request. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: requestId + required: false + in: path + description: Request Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/pools/{poolId}/retire: + post: + operationId: ContractsApi_retire + summary: Retire tokens. + description: Retire tokens. + parameters: + - name: poolId + required: false + in: path + description: Pool Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RetireRequestTokenDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/requests/{requestId}/approve: + post: + operationId: ContractsApi_approveRetire + summary: Approve retire request. + description: >- + Approve retire contract request. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: requestId + required: true + in: path + description: Request identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/requests/{requestId}/cancel: + delete: + operationId: ContractsApi_cancelRetireRequest + summary: Cancel retire request. + description: Cancel retire contract request. + parameters: + - name: requestId + required: true + in: path + description: Request identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire/{contractId}/admin/{hederaId}: + post: + operationId: ContractsApi_retireAddAdmin + summary: Add retire admin. + description: >- + Add retire contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + delete: + operationId: ContractsApi_retireRemoveAdmin + summary: Remove wipe admin. + description: >- + Remove wipe contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts/retire: + get: + operationId: ContractsApi_getRetireVCs + summary: Return a list of all retire vcs. + description: Returns all retire vcs. + parameters: + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /demo/registered-users: + get: + operationId: DemoApi_registeredUsers + summary: Returns list of registered users. + description: Returns list of registered users. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RegisteredUsersDTO' + tags: + - demo + /demo/random-key: + get: + tags: + - demo + description: Generates a new Hedera account with a random private key. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/HederaAccount' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /demo/push/random-key: + get: + tags: + - demo + description: Generates a new Hedera account with a random private key. + security: + - bearerAuth: [] + summary: Generates a new Hedera account with a random private key. + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /external: + post: + tags: + - external + description: Sends data from an external source. + summary: Sends data from an external source. + requestBody: + description: Object that contains a VC Document. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ExternalData' + responses: + '200': + description: Successful operation. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /ipfs/file: + post: + operationId: IpfsApi_postFile + summary: Add file from ipfs. + description: Add file from ipfs. + parameters: [] + responses: + '201': + description: '' + tags: + - ipfs + security: + - bearerAuth: [] + /ipfs/file/{cid}: + get: + tags: + - ipfs + description: Get file from ipfs. + summary: Get file from ipfs. + parameters: + - in: path + name: cid + schema: + type: string + required: true + description: File CID. + security: + - bearerAuth: [] + responses: + '201': + description: Created. + content: + binary/octet-stream: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /logs: + post: + tags: + - logs + description: Returns logs. For users with the Standard Registry role only. + security: + - bearerAuth: [] + requestBody: + description: Log filters. + content: + application/json: + schema: + $ref: '#/components/schemas/LogFilters' + summary: Returns logs. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + properties: + totalCount: + type: number + logs: + $ref: '#/components/schemas/Log' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /logs/attributes: + get: + tags: + - logs + description: Returns logs attributes. For users with the Standard Registry role only. + parameters: + - in: query + name: name + schema: + type: string + description: Part of name. + - in: query + name: existingAttributes + schema: + type: array + items: + type: string + description: Attributes to exclude. + security: + - bearerAuth: [] + summary: Returns logs attributes. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /map/key: + get: + tags: + - maps + description: Returns map api key. + security: + - bearerAuth: [] + summary: Returns map api key. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /map/sh: + get: + operationId: MapApi_getSentinelKey + parameters: [] + responses: + '200': + description: '' + tags: + - map + /metrics: + get: + operationId: MetricsApi_getMetrics + parameters: [] + responses: + '200': + description: '' + tags: + - metrics + /modules: + get: + tags: + - modules + description: >- + Returns all modules. Only users with the Standard Registry and Installer + role are allowed to make the request. + security: + - bearerAuth: [] + summary: Return a list of all modules. + parameters: + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set + examples: + pageIndex: + summary: Example of a pageIndex + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The numbers of items to return + examples: + pageSize: + summary: Example of a pageSize + value: 100 + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + $ref: '#/components/schemas/Module' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + tags: + - modules + description: >- + Creates a new module. Only users with the Standard Registry role are + allowed to make the request. + security: + - bearerAuth: [] + summary: Creates a new module. + requestBody: + description: Object that contains module configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Module' + responses: + '201': + description: Created. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/schemas: + get: + operationId: ModulesApi_getModuleSchemas + parameters: [] + responses: + '200': + description: '' + tags: &ref_3 + - modules + post: + operationId: ModulesApi_postSchemas + parameters: [] + responses: + '201': + description: '' + tags: *ref_3 + /modules/{uuid}: + get: + tags: + - modules + description: >- + Retrieves module configuration for the specified module ID. Only users + with the Standard Registry role are allowed to make the request. + parameters: + - in: path + name: uuid + schema: + type: string + required: true + description: Selected module ID. + summary: Retrieves module configuration. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Module' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + put: + tags: + - modules + description: >- + Updates module configuration for the specified module ID. Only users + with the Standard Registry role are allowed to make the request. + summary: Updates module configuration. + parameters: + - in: path + name: uuid + description: Selected module ID. + required: true + schema: + type: string + requestBody: + description: Object that contains module configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Module' + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Module' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + delete: + tags: + - modules + description: >- + Deletes the module with the provided module ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - in: path + name: uuid + schema: + type: string + required: true + description: Module ID. + security: + - bearerAuth: [] + summary: Deletes the module. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/menu: + get: + tags: + - modules + description: >- + Returns modules menu. Only users with the Standard Registry and + Installer role are allowed to make the request. + security: + - bearerAuth: [] + summary: Return a list of modules. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Module' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/{uuid}/export/file: + get: + tags: + - modules + description: >- + Returns a zip file containing the published module and all associated + artifacts, i.e. schemas and VCs. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - in: path + name: uuid + schema: + type: string + required: true + description: Selected module ID. + security: + - bearerAuth: [] + summary: >- + Return module and its artifacts in a zip file format for the specified + module. + responses: + '200': + description: Successful operation. Response zip file + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/{uuid}/export/message: + get: + tags: + - modules + description: >- + Returns the Hedera message ID for the specified module published onto + IPFS. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - in: path + name: uuid + schema: + type: string + required: true + description: Selected module ID. + security: + - bearerAuth: [] + summary: Return Heder message ID for the specified published module. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportModule' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/import/message: + post: + tags: + - modules + description: >- + Imports new module and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + security: + - bearerAuth: [] + summary: Imports new module from IPFS. + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the module. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '201': + description: Created. + content: + application/json: + schema: + $ref: '#/components/schemas/Module' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/import/file: + post: + tags: + - modules + description: >- + Imports new module and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Imports new module from a zip file. + requestBody: + description: >- + A zip file that contains the module and associated schemas and VCs to + be imported. + required: true + content: + binary/octet-stream: + schema: + type: string + format: binary + responses: + '201': + description: Created. + content: + application/json: + schema: + $ref: '#/components/schemas/Module' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/import/message/preview: + post: + tags: + - modules + description: >- + Previews the module from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + summary: Module preview from IPFS. + security: + - bearerAuth: [] + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the module. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PreviewModule' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/import/file/preview: + post: + tags: + - modules + description: >- + Previews the module from a zip file without loading it into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + summary: Module preview from a zip file. + security: + - bearerAuth: [] + requestBody: + description: >- + A zip file that contains the module and associated schemas and VCs to + be viewed. + required: true + content: + binary/octet-stream: + schema: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PreviewModule' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/{uuid}/publish: + put: + tags: + - modules + description: >- + Publishes the module with the specified (internal) module ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - in: path + name: uuid + schema: + type: string + required: true + description: Selected module ID. + summary: Publishes the module onto IPFS. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PublishModule' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /modules/validate: + post: + tags: + - modules + description: >- + Validates selected module. Only users with the Standard Registry role + are allowed to make the request. + security: + - bearerAuth: [] + summary: Validates module. + requestBody: + description: Object that contains module configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Module' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ValidateModule' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tools: + post: + operationId: ToolsApi_createNewTool + summary: Creates a new tool. + description: >- + Creates a new tool. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_4 + - tools + security: + - bearerAuth: [] + get: + operationId: ToolsApi_getTools + summary: Return a list of all tools. + description: >- + Returns all tools. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: pageSize + required: false + in: query + description: The numbers of items to return + schema: + type: number + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + schema: + type: number + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/push: + post: + operationId: ToolsApi_createNewToolAsync + summary: Creates a new tool. + description: >- + Creates a new tool. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/{id}: + delete: + operationId: ToolsApi_deleteTool + summary: >- + Deletes the tool with the provided tool ID. Only users with the Standard + Registry role are allowed to make the request. + description: Deletes the tool. + parameters: + - name: id + required: true + in: path + description: Tool ID + schema: + type: string + responses: + '200': + description: Successful operation. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + get: + operationId: ToolsApi_getToolById + summary: Retrieves tool configuration. + description: >- + Retrieves tool configuration for the specified tool ID. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + put: + operationId: ToolsApi_updateTool + summary: Updates tool configuration. + description: >- + Updates tool configuration for the specified tool ID. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/{id}/publish: + put: + operationId: ToolsApi_publishTool + summary: Publishes the tool onto IPFS. + description: >- + Publishes the tool with the specified (internal) tool ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/{id}/push/publish: + put: + operationId: ToolsApi_publishToolAsync + summary: Publishes the tool onto IPFS. + description: >- + Publishes the tool with the specified (internal) tool ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/validate: + post: + operationId: ToolsApi_validateTool + summary: Validates selected tool. + description: >- + Validates selected tool. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: '' + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/{id}/export/file: + get: + operationId: ToolsApi_toolExportFile + summary: >- + Return tool and its artifacts in a zip file format for the specified + tool. + description: >- + Returns a zip file containing the published tool and all associated + artifacts, i.e. schemas and VCs. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + schema: + type: string + responses: + '200': + description: Successful operation. Response zip file. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/{id}/export/message: + get: + operationId: ToolsApi_toolExportMessage + summary: Return Heder message ID for the specified published tool. + description: >- + Returns the Hedera message ID for the specified tool published onto + IPFS. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: id + required: true + in: path + description: Tool ID + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/import/message/preview: + post: + operationId: ToolsApi_toolImportMessagePreview + summary: Imports new tool from IPFS. + description: >- + Imports new tool and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/import/message: + post: + operationId: ToolsApi_toolImportMessage + summary: Imports new tool from IPFS. + description: >- + Imports new tool and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/import/file/preview: + post: + operationId: ToolsApi_toolImportFilePreview + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/import/file: + post: + operationId: ToolsApi_toolImportFile + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/push/import/file: + post: + operationId: ToolsApi_toolImportFileAsync + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/push/import/message: + post: + operationId: ToolsApi_toolImportMessageAsync + summary: Imports new tool from IPFS. + description: >- + Imports new tool and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /tools/menu/all: + get: + operationId: ToolsApi_getMenu + summary: Return a list of tools. + description: >- + Returns tools menu. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: '' + content: + application/json: + schema: + type: array + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearerAuth: [] + /profiles/{username}: + get: + operationId: ProfileApi_getProfile + summary: Returns user account info. + description: >- + Returns user account information. For users with the Standard Registry + role it also returns address book and VC document information. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to fetch the information + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ProfileDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_5 + - profiles + security: + - bearerAuth: [] + - bearer: [] + put: + operationId: ProfileApi_setUserProfile + summary: Sets Hedera credentials for the user. + description: >- + Sets Hedera credentials for the user. For users with the Standard + Registry role it also creates an address book. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to update the information. + schema: + type: string + requestBody: + required: true + description: Object that contains the Hedera account data. + content: + application/json: + schema: + $ref: '#/components/schemas/CredentialsDTO' + responses: + '200': + description: Created. + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearerAuth: [] + - bearer: [] + /profiles/push/{username}: + put: + operationId: ProfileApi_setUserProfileAsync + summary: Sets Hedera credentials for the user. + description: >- + Sets Hedera credentials for the user. For users with the Standard + Registry role it also creates an address book. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to update the information. + schema: + type: string + requestBody: + required: true + description: Object that contains the Hedera account data. + content: + application/json: + schema: + $ref: '#/components/schemas/CredentialsDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearerAuth: [] + - bearer: [] + /profiles/{username}/balance: + get: + operationId: ProfileApi_getUserBalance + summary: Returns user's Hedera account balance. + description: >- + Requests Hedera account balance. Only users with the Installer role are + allowed to make the request. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to fetch the balance. + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearerAuth: [] + - bearer: [] + /profiles/restore/{username}: + put: + operationId: ProfileApi_restoreUserProfile + summary: Restore user data (policy, DID documents, VC documents). + description: Restore user data (policy, DID documents, VC documents). + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to restore the information. + schema: + type: string + requestBody: + required: true + description: Object that contains the Hedera account data. + content: + application/json: + schema: + $ref: '#/components/schemas/CredentialsDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearerAuth: [] + - bearer: [] + /profiles/restore/topics/{username}: + put: + operationId: ProfileApi_restoreTopic + summary: List of available recovery topics. + description: List of available recovery topics. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to restore the information. + schema: + type: string + requestBody: + required: true + description: Object that contains the Hedera account data. + content: + application/json: + schema: + $ref: '#/components/schemas/CredentialsDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearerAuth: [] + - bearer: [] + /profiles/did-document/validate: + post: + operationId: ProfileApi_validateDidDocument + summary: Validate DID document format. + description: Validate DID document format. + parameters: [] + requestBody: + required: true + description: DID Document. + content: + application/json: + schema: + $ref: '#/components/schemas/DidDocumentDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/DidDocumentStatusDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearerAuth: [] + - bearer: [] + /profiles/did-keys/validate: + post: + operationId: ProfileApi_validateDidKeys + summary: Validate DID document keys. + description: Validate DID document keys. + parameters: [] + requestBody: + required: true + description: DID Document and keys. + content: + application/json: + schema: + $ref: '#/components/schemas/DidDocumentWithKeyDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/DidKeyStatusDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearerAuth: [] + - bearer: [] + /policies: + get: + tags: + - policies + description: >- + Returns all policies. Only users with the Standard Registry and + Installer role are allowed to make the request. + security: + - bearerAuth: [] + summary: Return a list of all policies. + parameters: + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set + examples: + pageIndex: + summary: Example of a pageIndex + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The numbers of items to return + examples: + pageSize: + summary: Example of a pageSize + value: 100 + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + allOf: + - $ref: '#/components/schemas/PolicyConfig' + - type: object + properties: + userRoles: + type: array + items: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + tags: + - policies + description: >- + Creates a new policy. Only users with the Standard Registry role are + allowed to make the request. + security: + - bearerAuth: [] + summary: Creates a new policy. + requestBody: + description: Object that contains policy configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyConfig' + responses: + '201': + description: Created. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/migrate-data: + post: + operationId: PolicyApi_migrateData + summary: Migrate policy data. + description: >- + Migrate policy data. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Migration config. + content: + application/json: + schema: + $ref: '#/components/schemas/MigrationConfigDTO' + responses: + '200': + description: Errors while migration. + content: + application/json: + schema: + type: array + items: + type: object + properties: + error: + type: string + id: + type: string + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_6 + - policies + security: + - bearerAuth: [] + /policies/push/migrate-data: + post: + operationId: PolicyApi_migrateDataAsync + summary: Migrate policy data asynchronous. + description: >- + Migrate policy data asynchronous. Only users with the Standard Registry + role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Migration config. + content: + application/json: + schema: + $ref: '#/components/schemas/MigrationConfigDTO' + responses: + '202': + description: Created task. + content: + application/json: + schema: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + /policies/push: + post: + tags: + - policies + description: >- + Creates a new policy. Only users with the Standard Registry role are + allowed to make the request. + security: + - bearerAuth: [] + summary: Creates a new policy. + requestBody: + description: Object that contains policy configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyConfig' + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/push/{policyId}: + post: + operationId: PolicyApi_updatePolicyAsync + summary: '' + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearerAuth: [] + delete: + operationId: PolicyApi_deletePolicyAsync + parameters: [] + responses: + '202': + description: '' + tags: *ref_6 + security: + - bearerAuth: [] + /policies/{policyId}: + get: + tags: + - policies + description: >- + Retrieves policy configuration for the specified policy ID. Only users + with the Standard Registry role are allowed to make the request. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + summary: Retrieves policy configuration. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/PolicyConfig' + - type: object + properties: + userRoles: + type: array + items: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + put: + tags: + - policies + description: >- + Updates policy configuration for the specified policy ID. Only users + with the Standard Registry role are allowed to make the request. + summary: Updates policy configuration. + parameters: + - in: path + name: policyId + description: Selected policy ID. + required: true + schema: + type: string + requestBody: + description: Object that contains policy configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyConfig' + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyConfig' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/publish: + put: + tags: + - policies + description: >- + Publishes the policy with the specified (internal) policy ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + requestBody: + description: Object that contains policy version. + required: true + content: + application/json: + schema: + type: object + properties: + policyVersion: + type: string + summary: Publishes the policy onto IPFS. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PublishPolicy' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/push/{policyId}/publish: + put: + tags: + - policies + description: >- + Publishes the policy with the specified (internal) policy ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + security: + - bearerAuth: [] + summary: >- + Publishes the policy with the specified (internal) policy ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + requestBody: + description: Object that contains policy version. + required: true + content: + application/json: + schema: + type: object + properties: + policyVersion: + type: string + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/dry-run: + put: + tags: + - policies + description: >- + Run policy without making any persistent changes or executing + transaction. Only users with the Standard Registry role are allowed to + make the request. + security: + - bearerAuth: [] + summary: Dry Run policy. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '201': + description: Created. + content: + application/json: + schema: + $ref: '#/components/schemas/PublishPolicy' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/discontinue: + put: + operationId: PolicyApi_discontinuePolicy + summary: Discontunue policy. + description: >- + Discontunue policy. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy identifier. + schema: {} + requestBody: + required: true + description: Discontinue details. + content: + application/json: + schema: + type: object + properties: + date: + type: date + responses: + '200': + description: Policies. + content: + application/json: + schema: + type: array + items: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearerAuth: [] + /policies/{policyId}/draft: + put: + tags: + - policies + description: >- + Return policy to editing. Only users with the Standard Registry role are + allowed to make the request. + security: + - bearerAuth: [] + summary: Return policy to editing. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PublishPolicy' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/validate: + post: + tags: + - policies + description: >- + Validates selected policy. Only users with the Standard Registry role + are allowed to make the request. + security: + - bearerAuth: [] + summary: Validates policy. + requestBody: + description: Object that contains policy configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyConfig' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ValidatePolicy' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/navigation: + get: + operationId: PolicyApi_getPolicyNavigation + summary: Returns a policy navigation. + description: Returns a policy navigation. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearerAuth: [] + /policies/{policyId}/groups: + get: + tags: + - policies + description: Returns a list of groups the user is a member of. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + summary: Returns a list of groups the user is a member of. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + type: object + properties: + id: + type: string + uuid: + type: string + role: + type: string + groupLabel: + type: string + groupName: + type: string + active: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + tags: + - policies + description: >- + Makes the selected group active. if UUID is not set then returns the + user to the default state. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + summary: Makes the selected group active. + requestBody: + description: Selected group. + required: true + content: + application/json: + schema: + type: object + properties: + uuid: + type: string + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/documents: + get: + operationId: PolicyApi_getPolicyDocuments + summary: Get policy documents. + description: >- + Get policy documents. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: pageSize + required: true + in: query + description: Page size. + schema: + type: number + - name: pageIndex + required: true + in: query + description: Page index. + schema: + type: number + - name: type + required: true + in: query + description: Document type. + schema: + enum: + - VC + - VP + type: string + - name: includeDocument + required: true + in: query + description: Include document field. + schema: + type: boolean + - name: policyId + required: true + in: path + description: Policy identifier. + schema: {} + responses: + '200': + description: Documents. + headers: + X-Total-Count: + description: Total documents count. + content: + application/json: + schema: + type: array + items: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearerAuth: [] + /policies/{policyId}/blocks: + get: + tags: + - policies + description: >- + Returns data from the root policy block. Only users with the Standard + Registry and Installer role are allowed to make the request. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + summary: Retrieves data for the policy root block. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyBlock' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/blocks/{uuid}: + get: + tags: + - policies + description: >- + Requests block data. Only users with a role that described in block are + allowed to make the request. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + - in: path + name: uuid + schema: + type: string + required: true + description: Selected block UUID. + summary: Requests block data. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyBlockData' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + tags: + - policies + description: Sends data to the specified block. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + - in: path + name: uuid + schema: + type: string + required: true + description: Selected block UUID. + summary: Sends data to the specified block. + requestBody: + description: Object with the data to be sent to the block. + required: true + content: + application/json: + schema: + type: object + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/tag/{tagName}/blocks: + post: + operationId: PolicyApi_setBlocksByTagName + summary: Sends data to the specified block. + description: Sends data to the specified block. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearerAuth: [] + get: + operationId: PolicyApi_getBlocksByTagName + summary: Requests block data. + description: >- + Requests block data by tag. Only users with a role that described in + block are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearerAuth: [] + /policies/{policyId}/tag/{tagName}: + get: + operationId: PolicyApi_getBlockByTagName + summary: Requests block data. + description: >- + Requests block data by tag. Only users with a role that described in + block are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearerAuth: [] + /policies/{policyId}/blocks/{uuid}/parents: + get: + operationId: PolicyApi_getBlockParents + parameters: [] + responses: + '200': + description: '' + tags: *ref_6 + /policies/{policyId}/export/file: + get: + tags: + - policies + description: >- + Returns a zip file containing the published policy and all associated + artifacts, i.e. schemas and VCs. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + security: + - bearerAuth: [] + summary: >- + Return policy and its artifacts in a zip file format for the specified + policy. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportPolicy' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/export/message: + get: + tags: + - policies + description: >- + Returns the Hedera message ID for the specified policy published onto + IPFS. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + security: + - bearerAuth: [] + summary: Return Heder message ID for the specified published policy. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportPolicy' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/export/xlsx: + get: + operationId: PolicyApi_getPolicyExportXlsx + summary: >- + Return policy and its artifacts in a xlsx file format for the specified + policy. + description: >- + Returns a xlsx file containing the published policy and all associated + artifacts, i.e. schemas and VCs. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearer: [] + /policies/import/message: + post: + tags: + - policies + description: >- + Imports new policy and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - in: query + name: versionOfTopicId + schema: + type: string + description: The topic ID of policy version. + examples: + pageIndex: + summary: Example of a topic ID of policy version. + value: 0.0.00000001 + security: + - bearerAuth: [] + summary: Imports new policy from IPFS. + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the Policy. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '201': + description: Created. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyConfig' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/push/import/message: + post: + tags: + - policies + description: >- + Imports new policy and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + security: + - bearerAuth: [] + summary: >- + Imports new policy and all associated artifacts from IPFS into the local + DB. + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the Policy. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/import/message/preview: + post: + tags: + - policies + description: >- + Previews the policy from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + summary: Policy preview from IPFS. + security: + - bearerAuth: [] + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the policy. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PreviewPolicy' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/push/import/message/preview: + post: + tags: + - policies + description: >- + Previews the policy from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Previews the policy from IPFS without loading it into the local DB. + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the policy. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/import/file: + post: + tags: + - policies + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - in: query + name: versionOfTopicId + schema: + type: string + description: The topic ID of policy version. + examples: + pageIndex: + summary: Example of a topic ID of policy version. + value: 0.0.00000001 + security: + - bearerAuth: [] + summary: Imports new policy from a zip file. + requestBody: + description: >- + A zip file that contains the policy and associated schemas and VCs to + be imported. + required: true + content: + binary/octet-stream: + schema: + type: string + format: binary + responses: + '201': + description: Created. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyConfig' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/push/import/file: + post: + tags: + - policies + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. + requestBody: + description: >- + A zip file that contains the policy and associated schemas and VCs to + be imported. + required: true + content: + binary/octet-stream: + schema: + type: string + format: binary + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/import/file/preview: + post: + tags: + - policies + description: >- + Previews the policy from a zip file without loading it into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + summary: Policy preview from a zip file. + security: + - bearerAuth: [] + requestBody: + description: >- + A zip file that contains the policy and associated schemas and VCs to + be viewed. + required: true + content: + binary/octet-stream: + schema: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PreviewPolicy' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/import/xlsx: + post: + operationId: PolicyApi_importPolicyFromXlsx + summary: Imports new policy from a xlsx file. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided xlsx file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: policyId + required: true + in: query + description: Policy Id + schema: + type: string + requestBody: + required: true + description: A xlsx file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearer: [] + /policies/push/import/xlsx: + post: + operationId: PolicyApi_importPolicyFromXlsxAsync + summary: Imports new policy from a xlsx file. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided xlsx file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: policyId + required: true + in: query + description: Policy Id + schema: + type: string + requestBody: + required: true + description: A xlsx file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearer: [] + /policies/import/xlsx/preview: + post: + operationId: PolicyApi_importPolicyFromXlsxPreview + summary: Policy preview from a xlsx file. + description: >- + Previews the policy from a xlsx file without loading it into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + requestBody: + required: true + description: A xlsx file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearerAuth: [] + - bearer: [] + /policies/blocks/about: + get: + operationId: PolicyApi_getBlockAbout + parameters: [] + responses: + '200': + description: '' + tags: *ref_6 + /policies/{policyId}/dry-run/users: + get: + tags: + - policies + description: >- + Returns all virtual users. Only users with the Standard Registry role + are allowed to make the request. + security: + - bearerAuth: [] + summary: Returns all virtual users. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + type: object + properties: + username: + type: string + did: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/dry-run/user: + post: + tags: + - policies + description: >- + Create a new virtual account. Only users with the Standard Registry role + are allowed to make the request. + security: + - bearerAuth: [] + summary: Create a new virtual account. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + type: object + properties: + username: + type: string + did: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/dry-run/login: + post: + tags: + - policies + description: >- + Logs virtual user into the system. Only users with the Standard Registry + role are allowed to make the request. + security: + - bearerAuth: [] + summary: Logs virtual user into the system. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + requestBody: + description: Virtual user + required: true + content: + application/json: + schema: + type: object + properties: + did: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + type: object + properties: + username: + type: string + did: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/dry-run/restart: + post: + tags: + - policies + description: >- + Restarts the execution of the policy. Clear data in database. Only users + with the Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Restarts the execution of the policy. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/dry-run/transactions: + get: + tags: + - policies + description: >- + Returns lists of virtual transactions. Only users with the Standard + Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Returns lists of virtual transactions. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + type: object + properties: + createDate: + type: string + type: + type: string + hederaAccountId: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/dry-run/artifacts: + get: + tags: + - policies + description: >- + Returns lists of virtual artifacts. Only users with the Standard + Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Returns lists of virtual artifacts. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + type: object + properties: + createDate: + type: string + type: + type: string + owner: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/dry-run/ipfs: + get: + tags: + - policies + description: >- + Returns lists of virtual artifacts. Only users with the Standard + Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Returns lists of virtual artifacts. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + type: object + properties: + createDate: + type: string + documentURL: + type: string + document: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/multiple: + post: + tags: + - policies + description: >- + Creates a link between the current policy and the main policy. Or + creates a group making the current policy the main one. + security: + - bearerAuth: [] + summary: Creates Multi policy config. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + requestBody: + description: Multi policy config. + required: true + content: + application/json: + schema: + type: object + required: + - mainPolicyTopicId + - synchronizationTopicId + properties: + mainPolicyTopicId: + type: string + synchronizationTopicId: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/MultiPolicyConfig' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + get: + tags: + - policies + description: Requests Multi policy config. + security: + - bearerAuth: [] + summary: Requests Multi policy config. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/MultiPolicyConfig' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/methodologies/categories: + get: + operationId: PolicyApi_getPolicyCategoriesAsync + summary: Get all categories + description: Get all categories + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyCategoryDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + /policies/methodologies/search: + post: + operationId: PolicyApi_getPoliciesByCategory + summary: Get filtered policies + description: Get policies by categories and text + parameters: [] + requestBody: + required: true + description: Filters + content: + application/json: + schema: + type: string + examples: + Filter1: + value: + categoryIds: + - '000000000000000000000001' + - '000000000000000000000002' + text: abc + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + /schema/{schemaId}: + get: + tags: + - schema + description: Returns schema by schema ID. + security: + - bearerAuth: [] + summary: Returns schema by schema ID. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schema/{schemaId}/parents: + get: + operationId: SingleSchemaApi_getSchemaParents + summary: Returns all parent schemas. + description: Returns all parent schemas. + parameters: + - name: schemaId + required: true + in: path + description: Schema identifier + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_7 + - schema + security: + - bearerAuth: [] + /schema/{schemaId}/tree: + get: + operationId: SingleSchemaApi_getSchemaTree + summary: Returns schema tree. + description: Returns schema tree. + parameters: + - name: schemaId + required: true + in: path + description: Schema identifier + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + properties: + name: + type: string + type: + type: string + children: + type: array + items: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + security: + - bearerAuth: [] + /schemas: + get: + tags: + - schemas + description: Returns all schemas. + security: + - bearerAuth: [] + summary: Returns all schemas. + parameters: + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set + examples: + pageIndex: + summary: Example of a pageIndex + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The numbers of items to return + examples: + pageSize: + summary: Example of a pageSize + value: 100 + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/{topicId}: + post: + tags: + - schemas + description: >- + Creates new schema. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - in: path + name: topicId + schema: + type: string + required: true + description: Topic ID. + examples: + topicId: + summary: Example of a Topic ID + value: 0.0.00000001 + security: + - bearerAuth: [] + summary: Create new schema. + requestBody: + description: Object that contains a valid schema. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + responses: + '201': + description: Created. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + get: + tags: + - schemas + description: Returns all schemas by topicId. + security: + - bearerAuth: [] + summary: Returns all schemas by topicId. + parameters: + - in: path + name: topicId + schema: + type: string + required: true + description: Topic ID. + examples: + topicId: + summary: Example of a Topic ID + value: 0.0.00000001 + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set + examples: + pageIndex: + summary: Example of a pageIndex + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The numbers of items to return + examples: + pageSize: + summary: Example of a pageSize + value: 100 + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/type/{schemaType}: + get: + operationId: SchemaApi_getSchemaByType + summary: Finds the schema using the json document type. + description: Finds the schema using the json document type. + parameters: + - name: schemaType + required: true + in: path + description: Type + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_8 + - schemas + security: + - bearerAuth: [] + /schemas/list/all: + get: + operationId: SchemaApi_getAll + summary: Returns a list of schemas. + description: >- + Returns a list of schemas. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearerAuth: [] + /schemas/list/sub: + get: + operationId: SchemaApi_getSub + summary: Returns a list of schemas. + description: >- + Returns a list of schemas. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: category + required: false + in: query + description: Schema category + schema: + type: string + - name: topicId + required: false + in: query + description: Topic Id + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearerAuth: [] + /schemas/push/copy: + post: + operationId: SchemaApi_copySchemaAsync + summary: Copy schema. + description: >- + Copy schema. Only users with the Standard Registry role are allowed to + make the request. + parameters: [] + requestBody: + required: true + description: Object that contains a valid schema. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + - bearerAuth: [] + /schemas/push/{topicId}: + post: + tags: + - schemas + description: >- + Creates new schema. Only users with the Standard Registry role are + allowed to make the request. + security: + - bearerAuth: [] + summary: Create new schema. + parameters: + - in: path + name: topicId + schema: + type: string + required: true + description: Topic ID. + examples: + topicId: + summary: Example of a Topic ID + value: 0.0.00000001 + requestBody: + description: Object that contains a valid schema. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/{schemaId}: + put: + tags: + - schemas + description: >- + Updates the schema with the provided schema ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + security: + - bearerAuth: [] + summary: Updates the schema. + requestBody: + description: Object that contains a valid schema. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + delete: + tags: + - schemas + description: >- + Deletes the schema with the provided schema ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + security: + - bearerAuth: [] + summary: Deletes the schema. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/{schemaId}/publish: + put: + tags: + - schemas + description: >- + Publishes the schema with the provided (internal) schema ID onto IPFS, + sends a message featuring IPFS CID into the corresponding Hedera topic. + Only users with the Standard Registry role are allowed to make the + request. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + security: + - bearerAuth: [] + summary: Publishes the schema. + requestBody: + description: Object that contains policy version. + required: true + content: + application/json: + schema: + type: object + properties: + version: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/push/{schemaId}/publish: + put: + tags: + - schemas + description: >- + Publishes the schema with the provided (internal) schema ID onto IPFS, + sends a message featuring IPFS CID into the corresponding Hedera topic. + Only users with the Standard Registry role are allowed to make the + request. + security: + - bearerAuth: [] + summary: >- + Publishes the schema with the provided (internal) schema ID onto IPFS, + sends a message featuring IPFS CID into the corresponding Hedera topic. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + requestBody: + description: Object that contains policy version. + required: true + content: + application/json: + schema: + type: object + properties: + version: + type: string + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/import/message/preview: + post: + tags: + - schemas + description: >- + Previews the schema from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Schema preview from IPFS. + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the schema. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/push/import/message/preview: + post: + tags: + - schemas + description: >- + Previews the schema from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Schema preview from IPFS. + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the schema. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/import/file/preview: + post: + tags: + - schemas + description: >- + Previews the schema from a zip file. Only users with the Standard + Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Schema preview from a zip file. + requestBody: + description: A zip file containing the schema to be viewed. + required: true + content: + binary/octet-stream: + schema: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/{topicId}/import/message: + post: + tags: + - schemas + description: >- + Imports new schema from IPFS into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - in: path + name: topicId + schema: + type: string + required: true + description: Topic ID. + examples: + topicId: + summary: Example of a Topic ID + value: 0.0.00000001 + security: + - bearerAuth: [] + summary: Imports new schema from IPFS. + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the schema. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + responses: + '201': + description: Created. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/push/{topicId}/import/message: + post: + tags: + - schemas + description: >- + Imports new schema from IPFS into the local DB. Only users with the + Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Imports new schema from IPFS. + requestBody: + description: >- + Object that contains the identifier of the Hedera message which + contains the IPFS CID of the schema. + required: true + content: + application/json: + schema: + type: object + properties: + messageId: + type: string + parameters: + - in: path + name: topicId + schema: + type: string + required: true + description: Topic ID. + examples: + topicId: + summary: Example of a Topic ID + value: 0.0.00000001 + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/{topicId}/import/file: + post: + tags: + - schemas + description: >- + Imports new schema from a zip file into the local DB. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - in: path + name: topicId + schema: + type: string + required: true + description: Topic ID. + examples: + topicId: + summary: Example of a Topic ID + value: 0.0.00000001 + security: + - bearerAuth: [] + summary: Imports new schema from a zip file. + requestBody: + description: A zip file containing schema to be imported. + content: + binary/octet-stream: + schema: + type: string + format: binary + required: true + responses: + '201': + description: Created. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/push/{topicId}/import/file: + post: + tags: + - schemas + description: >- + Imports new schema from a zip file into the local DB. Only users with + the Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Imports new schema from a zip file. + requestBody: + description: A zip file containing schema to be imported. + content: + binary/octet-stream: + schema: + type: string + format: binary + required: true + parameters: + - in: path + name: topicId + schema: + type: string + required: true + description: Topic ID. + examples: + topicId: + summary: Example of a Topic ID + value: 0.0.00000001 + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/{schemaId}/export/message: + post: + tags: + - schemas + description: >- + Returns Hedera message IDs of the published schemas, these messages + contain IPFS CIDs of these schema files. Only users with the Standard + Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: List Hedera message IDs of published schemas. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Selected schema ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportSchema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/{schemaId}/export/file: + post: + tags: + - schemas + description: >- + Returns schema files for the schemas. Only users with the Standard + Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Return zip file with schemas. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Selected schema ID. + responses: + '200': + description: Successful operation. Response zip file + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/system/{username}: + post: + tags: + - schemas + description: >- + Creates new system schema. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - in: path + name: username + schema: + type: string + required: true + description: Username. + security: + - bearerAuth: [] + summary: Creates new system schema. + requestBody: + description: Object that contains a valid schema. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + responses: + '201': + description: Created. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + get: + tags: + - schemas + description: >- + Returns all system schemas by username. Only users with the Standard + Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Returns all system schemas by username. + parameters: + - in: path + name: username + schema: + type: string + required: true + description: Username. + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set. + examples: + pageIndex: + summary: Example of a pageIndex. + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The number of items to return. + examples: + pageSize: + summary: Example of a pageSize. + value: 100 + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total number of items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/system/{schemaId}: + put: + tags: + - schemas + description: >- + Updates the system schema with the provided schema ID. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + security: + - bearerAuth: [] + summary: Updates the schema. + requestBody: + description: Object that contains a valid schema. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + delete: + tags: + - schemas + description: >- + Deletes the system schema with the provided schema ID. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + security: + - bearerAuth: [] + summary: Deletes the schema. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/system/{schemaId}/active: + put: + tags: + - schemas + description: >- + Makes the selected scheme active. Other schemes of the same type become + inactive. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + security: + - bearerAuth: [] + summary: Publishes the schema. + requestBody: + description: Object that contains policy version. + required: true + content: + application/json: + schema: + type: object + properties: + version: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/system/entity/{schemaEntity}: + get: + tags: + - schemas + description: Finds the schema using the schema type. + parameters: + - in: path + name: schemaEntity + schema: + type: string + enum: + - STANDARD_REGISTRY + - USER + - POLICY + - MINT_TOKEN + - WIPE_TOKEN + - MINT_NFTOKEN + required: true + description: schema type. + security: + - bearerAuth: [] + summary: Returns schema by schema type. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /schemas/{schemaId}/export/xlsx: + get: + operationId: SchemaApi_getPolicyExportXlsx + summary: Return schemas in a xlsx file format for the specified policy. + description: >- + Returns a xlsx file containing schemas. Only users with the Standard + Registry role are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearerAuth: [] + - bearer: [] + /schemas/{topicId}/import/xlsx: + post: + operationId: SchemaApi_importPolicyFromXlsx + summary: Imports new schema from a xlsx file into the local DB. + description: >- + Imports new schema from a xlsx file into the local DB. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + schema: + type: string + requestBody: + required: true + description: A xlsx file containing schema config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearerAuth: [] + - bearer: [] + /schemas/push/{topicId}/import/xlsx: + post: + operationId: SchemaApi_importPolicyFromXlsxAsync + summary: Imports new schema from a xlsx file into the local DB. + description: >- + Imports new schema from a xlsx file into the local DB. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + schema: + type: string + requestBody: + required: true + description: A xlsx file containing schema config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearerAuth: [] + - bearer: [] + /schemas/import/xlsx/preview: + post: + operationId: SchemaApi_importPolicyFromXlsxPreview + summary: Previews the schema from a xlsx file. + description: >- + Previews the schema from a xlsx file. Only users with the Standard + Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: A xlsx file containing schema config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearerAuth: [] + - bearer: [] + /schemas/export/template: + get: + operationId: SchemaApi_exportTemplate + summary: Returns a list of schemas. + description: >- + Returns a list of schemas. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearerAuth: [] + - bearer: [] + /settings: + get: + tags: + - settings + description: >- + Returns current settings. For users with the Standard Registry role + only. + security: + - bearerAuth: [] + summary: Returns current settings. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CommonSettings' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + tags: + - settings + description: Set settings. For users with the Standard Registry role only. + security: + - bearerAuth: [] + summary: Set settings. + responses: + '201': + description: Created. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/CommonSettings' + /settings/environment: + get: + tags: + - settings + description: Returns current environment name. + security: + - bearerAuth: [] + summary: Returns current environment name. + responses: + '200': + description: Successful operation. + content: + text/plain: + schema: + type: string + example: testnet + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /settings/about: + get: + operationId: SettingsApi_getAbout + parameters: [] + responses: + '200': + description: '' + tags: + - settings + /tags: + post: + operationId: TagsApi_setTags + parameters: [] + responses: + '201': + description: '' + tags: + - tags + /tags/search: + post: + tags: + - tags + description: Search tags. + security: + - bearerAuth: [] + requestBody: + description: Object that contains filters. + required: true + content: + application/json: + schema: + oneOf: + - type: object + required: + - entity + - target + properties: + entity: + type: string + enum: + - Schema + - Policy + - Token + - Module + - Contract + - PolicyDocument + target: + type: string + - type: object + required: + - entity + - targets + properties: + entity: + type: string + enum: + - Schema + - Policy + - Token + - Module + - Contract + - PolicyDocument + targets: + type: array + items: + type: string + examples: + Single: + value: + entity: PolicyDocument + target: targetId1 + Multiple: + value: + entity: PolicyDocument + targets: + - targetId1 + - targetId2 + summary: Search tags. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + description: a (targetId, Tags) map. `targetId1` is an example key + properties: + targetId1: + $ref: '#/components/schemas/TagMap' + additionalProperties: + $ref: '#/components/schemas/TagMap' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tags/{uuid}: + delete: + tags: + - tags + description: Delete tag. + security: + - bearerAuth: [] + summary: Delete tag. + parameters: + - in: path + name: uuid + schema: + type: string + example: 00000000-0000-0000-0000-000000000000 + required: true + description: Tag identifier + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tags/synchronization: + post: + tags: + - tags + description: synchronization. + security: + - bearerAuth: [] + requestBody: + description: Object that contains filters. + required: true + content: + application/json: + schema: + type: object + required: + - entity + - target + properties: + entity: + type: string + enum: + - Schema + - Policy + - Token + - Module + - Contract + - PolicyDocument + example: PolicyDocument + target: + type: string + example: targetId + summary: synchronization. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TagMap' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tags/schemas: + get: + tags: + - tags + description: Returns all schema. + security: + - bearerAuth: [] + summary: Returns all schemas. + parameters: + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set + examples: + pageIndex: + summary: Example of a pageIndex + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The numbers of items to return + examples: + pageSize: + summary: Example of a pageSize + value: 100 + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + tags: + - tags + description: >- + Creates new schema. Only users with the Standard Registry role are + allowed to make the request. + security: + - bearerAuth: [] + summary: Creates new schema. + requestBody: + description: Object that contains a valid schema. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + responses: + '201': + description: Created. + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tags/schemas/{schemaId}: + delete: + tags: + - tags + description: >- + Deletes the schema with the provided schema ID. Only users with the + Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Delete the schema. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + put: + tags: + - tags + description: >- + Updates the schema with the provided schema ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + security: + - bearerAuth: [] + summary: Updates the schema. + requestBody: + description: Object that contains a valid schema. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tags/schemas/{schemaId}/publish: + put: + tags: + - tags + description: >- + Publishes the schema with the provided (internal) schema ID onto IPFS, + sends a message featuring IPFS CID into the corresponding Hedera topic. + Only users with the Standard Registry role are allowed to make the + request. + parameters: + - in: path + name: schemaId + schema: + type: string + required: true + description: Schema ID. + security: + - bearerAuth: [] + summary: Publishes the schema. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tags/schemas/published: + get: + tags: + - tags + description: Return a list of all published schemas. + security: + - bearerAuth: [] + summary: Return a list of all published schemas. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tasks/{taskId}: + get: + tags: + - tasks + description: Returns task statuses by Id. + security: + - bearerAuth: [] + summary: Returns task statuses. + parameters: + - in: path + name: taskId + schema: + type: string + required: true + description: Task ID. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskStatus' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens: + get: + tags: + - tokens + description: >- + Returns all tokens. For the Standard Registry role it returns only the + list of tokens, for other users it also returns token balances as well + as the KYC, Freeze, and Association statuses. Not allowed for the + Auditor role. + security: + - bearerAuth: [] + summary: Return a list of tokens. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + allOf: + - $ref: '#/components/schemas/TokenInfo' + - type: object + properties: + policies: + type: array + items: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + tags: + - tokens + description: >- + Creates a new token. Only users with the Standard Registry role are + allowed to make the request. + security: + - bearerAuth: [] + summary: Creates a new token. + requestBody: + description: Object that contains token information. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Token' + responses: + '201': + description: Created. + content: + application/json: + schema: + type: array + items: + allOf: + - $ref: '#/components/schemas/TokenInfo' + - type: object + properties: + policies: + type: array + items: + type: string + '400': + description: Bad Request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/push: + post: + tags: + - tokens + description: >- + Creates a new token. Only users with the Standard Registry role are + allowed to make the request. + security: + - bearerAuth: [] + summary: Creates a new token. + requestBody: + description: Object that contains token information. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Token' + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/push/{tokenId}: + delete: + operationId: TokensApi_deleteTokenAsync + parameters: [] + responses: + '202': + description: '' + tags: &ref_9 + - tokens + /tokens/{tokenId}/associate: + put: + tags: + - tokens + description: >- + Associates the user with the provided Hedera token. Only users with the + Installer role are allowed to make the request. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + security: + - bearerAuth: [] + summary: Associates the user with the provided Hedera token. + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/push/{tokenId}/associate: + put: + tags: + - tokens + description: >- + Associates the user with the provided Hedera token. Only users with the + Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Associates the user with the provided Hedera token. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/{tokenId}/dissociate: + put: + tags: + - tokens + description: >- + Disassociates the user with the provided Hedera token. Only users with + the Installer role are allowed to make the request. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + security: + - bearerAuth: [] + summary: Associate the user with the provided Hedera token. + responses: + '202': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/push/{tokenId}/dissociate: + put: + tags: + - tokens + description: >- + Disassociates the user with the provided Hedera token. Only users with + the Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Disassociates the user with the provided Hedera token. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/{tokenId}/{username}/grant-kyc: + put: + tags: + - tokens + description: >- + Sets the KYC flag for the user. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + security: + - bearerAuth: [] + summary: Sets the KYC flag for the user. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfo' + '400': + description: Bad Request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/push/{tokenId}/{username}/grant-kyc: + put: + tags: + - tokens + description: >- + Sets the KYC flag for the user. Only users with the Standard Registry + role are allowed to make the request. + security: + - bearerAuth: [] + summary: Sets the KYC flag for the user. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/{tokenId}/{username}/revoke-kyc: + put: + tags: + - tokens + description: >- + Unsets the KYC flag for the user. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + security: + - bearerAuth: [] + summary: Unsets the KYC flag for the user. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfo' + '400': + description: Bad Request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/push/{tokenId}/{username}/revoke-kyc: + put: + tags: + - tokens + description: >- + Unsets the KYC flag for the user. Only users with the Standard Registry + role are allowed to make the request. + security: + - bearerAuth: [] + summary: Unsets the KYC flag for the user. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/{tokenId}/{username}/freeze: + put: + tags: + - tokens + description: >- + Freezes transfers of the specified token for the user. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + security: + - bearerAuth: [] + summary: Freeze transfers of the specified token for the user. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfo' + '400': + description: Bad Request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/{tokenId}/{username}/unfreeze: + put: + tags: + - tokens + description: >- + Unfreezes transfers of the specified token for the user. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + security: + - bearerAuth: [] + summary: Unfreezes transfers of the specified token for the user. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfo' + '400': + description: Bad Request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/push/{tokenId}/{username}/freeze: + put: + tags: + - tokens + description: >- + Freezes transfers of the specified token for the user. Only users with + the Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Freeze transfers of the specified token for the user. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/push/{tokenId}/{username}/unfreeze: + put: + tags: + - tokens + description: >- + Unfreezes transfers of the specified token for the user. Only users with + the Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + summary: Unfreezes transfers of the specified token for the user. + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + responses: + '202': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Task' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/{tokenId}/{username}/info: + get: + tags: + - tokens + description: >- + Returns user information for the selected token. Only users with the + Standard Registry role are allowed to make the request. + security: + - bearerAuth: [] + parameters: + - in: path + name: tokenId + schema: + type: string + required: true + description: Token ID. + - in: path + name: username + schema: + type: string + required: true + description: Username. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfo' + '400': + description: Bad Request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tokens/{tokenId}/serials: + get: + operationId: TokensApi_getTokenSerials + summary: Return token serials. + description: Returns token serials of current user. + parameters: + - name: tokenId + required: true + in: path + description: Token identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Token serials. + content: + application/json: + schema: + type: array + items: + type: number + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /themes: + get: + tags: + - themes + description: Returns all themes. + security: + - bearerAuth: [] + summary: Return a list of all themes. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Theme' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + post: + tags: + - themes + description: Creates a new theme. + security: + - bearerAuth: [] + summary: Creates a new theme. + requestBody: + description: Object that contains theme configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Theme' + responses: + '201': + description: Created. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /themes/{themeId}: + put: + tags: + - themes + description: Updates theme configuration for the specified theme ID. + summary: Updates theme configuration. + parameters: + - in: path + name: themeId + description: Selected theme ID. + required: true + schema: + type: string + requestBody: + description: Object that contains theme configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Theme' + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Theme' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + delete: + tags: + - themes + description: Deletes the theme with the provided theme ID. + parameters: + - in: path + name: themeId + schema: + type: string + required: true + description: Theme ID. + security: + - bearerAuth: [] + summary: Deletes the theme. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /themes/import/file: + post: + tags: + - themes + description: Imports new theme from the provided zip file into the local DB. + security: + - bearerAuth: [] + summary: Imports new theme from a zip file. + requestBody: + description: A zip file that contains the theme to be imported. + required: true + content: + binary/octet-stream: + schema: + type: string + format: binary + responses: + '201': + description: Created. + content: + application/json: + schema: + $ref: '#/components/schemas/Theme' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /themes/{themeId}/export/file: + get: + tags: + - themes + description: Returns a zip file containing the theme. + parameters: + - in: path + name: themeId + schema: + type: string + required: true + description: Selected theme ID. + security: + - bearerAuth: [] + summary: Returns a zip file containing the theme. + responses: + '200': + description: Successful operation. Response zip file + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /trust-chains: + get: + tags: + - trustchains + description: >- + Requests all VP documents. Only users with the Auditor role are allowed + to make the request. + security: + - bearerAuth: [] + summary: Returns a list of all VP documents. + parameters: + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set + examples: + pageIndex: + summary: Example of a pageIndex + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The numbers of items to return + examples: + pageSize: + summary: Example of a pageSize + value: 100 + - in: query + name: policyId + schema: + type: string + description: Selected policy ID. + - in: query + name: policyOwner + schema: + type: string + description: Selected Standard Registry (DID). + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/VerifiablePresentation' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /trust-chains/{hash}: + get: + tags: + - trustchains + description: >- + Builds and returns a trustchain, from the VP to the root VC document. + Only users with the Auditor role are allowed to make the request. + parameters: + - in: path + name: hash + schema: + type: string + required: true + description: Hash or ID of a VP document. + security: + - bearerAuth: [] + summary: Returns a trustchain for a VP document. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TrustChains' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /wizard/policy: + post: + tags: + - wizard + description: >- + Creates a new policy by wizard. Only users with the Standard Registry + role are allowed to make the request. + security: + - bearerAuth: [] + summary: Creates a new policy. + requestBody: + description: Object that contains wizard configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/WizardConfig' + responses: + '201': + description: Successful operation. + content: + application/json: + schema: + type: object + properties: + policyId: + type: string + wizardConfig: + $ref: '#/components/schemas/WizardConfig' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /wizard/push/policy: + post: + operationId: WizardApi_setPolicyAsync + summary: Creates a new policy. + description: >- + Creates a new policy by wizard. Only users with the Standard Registry + role are allowed to make the request. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + saveState: + type: boolean + wizardConfig: + type: object + required: + - policy + - roles + - schemas + - trustChain + properties: + roles: + type: array + items: + type: string + policy: + type: object + properties: + name: + type: string + description: + type: string + topicDescription: + type: string + policyTag: + type: string + schemas: + type: array + items: + type: object + properties: + name: + type: string + iri: + type: string + isApproveEnable: + type: boolean + isMintSchema: + type: boolean + mintOptions: + type: object + properties: + tokenId: + type: string + rule: + type: string + dependencySchemaIri: + type: string + relationshipsSchemaIri: + type: string + initialRolesFor: + type: array + items: + type: string + rolesConfig: + type: array + items: + type: object + properties: + role: + type: string + isApprover: + type: boolean + isCreator: + type: boolean + gridColumns: + type: array + items: + type: object + properties: + field: + type: string + title: + type: string + trustChain: + type: array + items: + type: object + properties: + role: + type: string + mintSchemaIri: + type: string + viewOnlyOwnDocuments: + type: boolean + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: + - wizard + /wizard/{policyId}/config: + post: + tags: + - wizard + description: >- + Get policy config by wizard. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy identifier. + security: + - bearerAuth: [] + summary: Get policy config. + requestBody: + description: Object that contains wizard configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/WizardConfig' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + properties: + policyConfig: + $ref: '#/components/schemas/PolicyConfig' + wizardConfig: + $ref: '#/components/schemas/WizardConfig' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /branding: + post: + operationId: BrandingApi_setBranding + parameters: [] + responses: + '401': + description: Unauthorized + tags: &ref_10 + - branding + security: + - bearer: [] + get: + operationId: BrandingApi_getBranding + parameters: [] + responses: + '200': + description: '' + tags: *ref_10 + /suggestions: + post: + operationId: SuggestionsApi_policySuggestions + summary: Get next and nested suggested block types + description: >- + Get next and nested suggested block types. Only users with the Standard + Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsInputDTO' + responses: + '200': + description: >- + Successful operation. Suggested next and nested block types + respectively. + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsOutputDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_11 + - suggestions + security: + - bearer: [] + - bearerAuth: [] + /suggestions/config: + post: + operationId: SuggestionsApi_setPolicySuggestionsConfig + summary: Set suggestions config + description: >- + Set suggestions config. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsConfigDTO' + responses: + '201': + description: Successful operation. Response setted suggestions config. + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsConfigDTO' + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + - bearerAuth: [] + get: + operationId: SuggestionsApi_getPolicySuggestionsConfig + summary: Get suggestions config + description: >- + Get suggestions config. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. Response suggestions config. + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsConfigDTO' + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + - bearerAuth: [] + /notifications: + get: + operationId: NotificationsApi_getAllNotifications + summary: Get all notifications + description: Returns all notifications. + parameters: [] + responses: + '200': + description: Successful operation. Returns notifications and count. + headers: + X-Total-Count: + description: Count of notifications + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NotificationDTO' + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_12 + - notifications + security: + - bearer: [] + - bearerAuth: [] + /notifications/new: + get: + operationId: NotificationsApi_getNewNotifications + summary: Get new notifications + description: Returns new notifications. + parameters: [] + responses: + '200': + description: Successful operation. Returns new notifications. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NotificationDTO' + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_12 + security: + - bearer: [] + - bearerAuth: [] + /notifications/progresses: + get: + operationId: NotificationsApi_getProgresses + summary: Get progresses + description: Returns progresses. + parameters: [] + responses: + '200': + description: Successful operation. Returns progresses. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ProgressDTO' + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_12 + security: + - bearer: [] + - bearerAuth: [] + /notifications/read/all: + post: + operationId: NotificationsApi_readAll + summary: Read all notifications + description: Returns new notifications. + parameters: [] + responses: + '200': + description: Successful operation. Returns notifications. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NotificationDTO' + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_12 + security: + - bearer: [] + - bearerAuth: [] + /notifications/delete/{notificationId}: + delete: + operationId: NotificationsApi_delete + summary: Delete notifications up to this point + description: Returns deleted notifications count. + parameters: + - name: notificationId + required: true + in: path + schema: + type: string + responses: + '200': + description: Successful operation. Returns deleted notifications count. + content: + application/json: + schema: + type: number + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_12 + security: + - bearer: [] + - bearerAuth: [] + /projects/search: + post: + operationId: ProjectsAPI_projectSearch + summary: Search projects + description: Search projects by filters + parameters: [] + requestBody: + required: true + description: The question of choosing a methodology + content: + application/json: + schema: + type: string + examples: + q: + value: >- + What methodology can I use for production of electricity using + renewable energy technologies? + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ProjectDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_13 + - projects + /projects/compare/documents: + post: + operationId: ProjectsAPI_compareDocuments + summary: Compare documents. + description: Compare documents. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterDocumentsDTO' + examples: + Filter1: + value: + documentId1: '000000000000000000000001' + documentId2: '000000000000000000000002' + Filter2: + value: + documentIds: + - '000000000000000000000001' + - '000000000000000000000002' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareDocumentsDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + /projects/properties: + get: + operationId: ProjectsAPI_getPolicyProperties + summary: Get all properties + description: Get all properties + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PropertiesDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + /record/{policyId}/status: + get: + operationId: RecordApi_getRecordStatus + summary: Get recording or running status. + description: >- + Get recording or running status. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RecordStatusDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_14 + - record + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/recording/start: + post: + operationId: RecordApi_startRecord + summary: Start recording. + description: >- + Start recording. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/recording/stop: + post: + operationId: RecordApi_stopRecord + summary: Stop recording. + description: >- + Stop recording. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/recording/actions: + get: + operationId: RecordApi_getRecordActions + summary: Get recorded actions. + description: >- + Get recorded actions. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RecordActionDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/running/start: + post: + operationId: RecordApi_runRecord + summary: Run record from a zip file. + description: >- + Run record from a zip file. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + requestBody: + required: true + description: A zip file containing record to be run. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/running/stop: + post: + operationId: RecordApi_stopRunning + summary: Stop running. + description: >- + Stop running. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/running/results: + get: + operationId: RecordApi_getRecordResults + summary: Get running results. + description: >- + Get running results. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RunningResultDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/running/details: + get: + operationId: RecordApi_getRecordDetails + summary: Get running details. + description: >- + Get running details. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RunningDetailsDTO' + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/running/fast-forward: + post: + operationId: RecordApi_fastForward + summary: Fast Forward. + description: >- + Fast Forward. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/running/retry: + post: + operationId: RecordApi_retryStep + summary: Retry step. + description: >- + Retry step. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /record/{policyId}/running/skip: + post: + operationId: RecordApi_skipStep + summary: Skip step. + description: >- + Skip step. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearerAuth: [] + - bearer: [] + /ai-suggestions/ask: + get: + operationId: AISuggestionsAPI_getAIAnswer + summary: Get methodology suggestion + description: Returns AI response to the current question + parameters: + - name: q + required: true + in: path + description: The question of choosing a methodology + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + example: ACM0001, ACM0002, ACM0006, ACM0007, ACM0018 + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_15 + - ai-suggestions + /ai-suggestions/rebuild-vector: + put: + operationId: AISuggestionsAPI_rebuildVector + summary: Rebuild AI vector + description: Rebuilds vector based on policy data in the DB + parameters: [] + responses: + '200': + description: '' + tags: *ref_15 + /schemas/type/{type}: + get: + tags: + - schemas + description: Finds the schema using the json document type. + parameters: + - in: path + name: type + schema: + type: string + required: true + description: JSON type. + security: + - bearerAuth: [] + summary: Returns schema by type. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/Schema' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/tag/{tag}: + get: + tags: + - policies + description: >- + Requests block ID from a policy by tag. Only users with the Standard + Registry and Installer roles are allowed to make the request. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Selected policy ID. + - in: path + name: tag + schema: + type: string + required: true + description: Tag from the selected policy. + summary: Requests block ID from a policy by tag. + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + properties: + id: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /policies/{policyId}/tag/{tag}/blocks: + post: + tags: + - policies + description: Sends data to the specified block. + security: + - bearerAuth: [] + summary: Sends data to the specified block. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + - in: path + name: tag + schema: + type: string + required: true + description: Tag from the selected policy. + requestBody: + description: Object with the data to be sent to the block. + required: true + content: + application/json: + schema: + type: object + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyBlockData' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + get: + tags: + - policies + description: >- + Requests block data by tag. Only users with a role that described in + block are allowed to make the request. + security: + - bearerAuth: [] + summary: Requests block data. + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy ID. + - in: path + name: tag + schema: + type: string + required: true + description: Tag from the selected policy. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyBlockData' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /ipfs/file/: + post: + tags: + - ipfs + description: Add file to ipfs. + summary: Add file to ipfs. + requestBody: + description: Data array of file. + required: true + content: + binary/octet-stream: + schema: + type: string + format: binary + security: + - bearerAuth: [] + responses: + '201': + description: Created. + content: + application/json: + schema: + description: CID of added file. + type: string + '401': + description: Unauthorized. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /artifacts/{policyId}: + post: + tags: + - artifacts + description: Upload artifact. For users with the Standard Registry role only. + security: + - bearerAuth: [] + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + artifacts: + type: array + items: + type: string + format: binary + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy identifier + summary: Upload Artifact. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Artifact' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /artifact: + get: + deprecated: true + tags: + - artifacts + description: Returns all artifacts. + security: + - bearerAuth: [] + summary: Returns all artifacts. + parameters: + - in: query + name: policyId + schema: + type: string + description: Policy identifier + - in: query + name: pageIndex + schema: + type: integer + description: >- + The number of pages to skip before starting to collect the result + set + examples: + pageIndex: + summary: Example of a pageIndex + value: 0 + - in: query + name: pageSize + schema: + type: integer + description: The numbers of items to return + examples: + pageSize: + summary: Example of a pageSize + value: 100 + responses: + '200': + description: Successful operation. + headers: + x-total-count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Artifact' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /artifact/{policyId}: + post: + deprecated: true + tags: + - artifacts + description: Upload artifact. For users with the Standard Registry role only. + security: + - bearerAuth: [] + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + artifacts: + type: array + items: + type: string + format: binary + parameters: + - in: path + name: policyId + schema: + type: string + required: true + description: Policy identifier + summary: Upload Artifact. + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Artifact' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /artifact/{artifactId}: + delete: + deprecated: true + tags: + - artifacts + description: Delete artifact. + security: + - bearerAuth: [] + summary: Delete artifact. + parameters: + - in: path + name: artifactId + schema: + type: string + required: true + description: Artifact identifier + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /tags/: + post: + tags: + - tags + description: Creates new tag. + security: + - bearerAuth: [] + summary: Creates new tag. + requestBody: + description: Object that contains tag information. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/Tag' + responses: + '201': + description: Created. + content: + application/json: + schema: + $ref: '#/components/schemas/Tag' + '400': + description: Bad Request. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' +info: + title: Guardian + description: >- + The Guardian is a modular open-source solution that includes best-in-class + identity management and decentralized ledger technology (DLT) libraries. At + the heart of the Guardian solution is a sophisticated Policy Workflow Engine + (PWE) that enables applications to offer a requirements-based tokenization + implementation. + version: 2.21.1 + contact: + name: API developer + url: https://envisionblockchain.com + email: info@envisionblockchain.com + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html +tags: [] +servers: + - url: /api/v1 + description: version 1.0 +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT + schemas: + AccountsResponseDTO: + type: object + properties: + username: + type: string + role: + type: string + did: + type: string + required: + - username + - role + - did + InternalServerErrorDTO: + type: object + properties: + code: + type: number + message: + type: string + required: + - code + - message + RegisterUserDTO: + type: object + properties: + username: + type: string + password: + type: string + password_confirmation: + type: string + role: + type: string + required: + - username + - password + - password_confirmation + - role + AccountsSessionResponseDTO: + type: object + properties: + username: + type: string + role: + type: string + accessToken: + type: string + required: + - username + - role + - accessToken + LoginUserDTO: + type: object + properties: + username: + type: string + password: + type: string + required: + - username + - password + CredentialSubjectDTO: + type: object + properties: + geography: + type: string + law: + type: string + tags: + type: string + ISIC: + type: string + '@context': + type: array + items: + type: string + id: + type: string + type: + type: string + required: + - geography + - law + - tags + - ISIC + - '@context' + - id + - type + ProofDTO: + type: object + properties: + type: + type: string + created: + format: date-time + type: string + verificationMethod: + type: string + proofPurpose: + type: string + jws: + type: string + required: + - type + - created + - verificationMethod + - proofPurpose + - jws + VcDocumentDTO: + type: object + properties: + id: + type: string + type: + type: array + items: + type: string + issuer: + type: string + issuanceDate: + format: date-time + type: string + '@context': + type: array + items: + type: string + credentialSubject: + $ref: '#/components/schemas/CredentialSubjectDTO' + proof: + $ref: '#/components/schemas/ProofDTO' + required: + - id + - type + - issuer + - issuanceDate + - '@context' + - credentialSubject + - proof + PolicyDTO: + type: object + properties: + _id: + type: string + createDate: + format: date-time + type: string + uuid: + type: string + name: + type: string + description: + type: string + status: + type: string + creator: + type: string + owner: + type: string + topicId: + type: string + policyTag: + type: string + codeVersion: + type: string + userRoles: + type: array + items: + type: string + userGroups: + type: array + items: + type: string + userRole: + type: string + userGroup: + type: string + id: + type: string + required: + - _id + - createDate + - uuid + - name + - description + - status + - creator + - owner + - topicId + - policyTag + - codeVersion + - userRoles + - userGroups + - userRole + - userGroup + - id + AggregatedDTOItem: + type: object + properties: + did: + type: string + hederaAccountId: + type: string + vcDocument: + $ref: '#/components/schemas/VcDocumentDTO' + policies: + $ref: '#/components/schemas/PolicyDTO' + required: + - did + - hederaAccountId + - vcDocument + - policies + UserDTO: + type: object + properties: + username: + type: string + did: + type: string + required: + - username + - did + BalanceResponseDTO: + type: object + properties: + balance: + type: number + unit: + type: string + user: + $ref: '#/components/schemas/UserDTO' + required: + - balance + - unit + - user + FilterSearchPoliciesDTO: + type: object + properties: + policyId: + type: string + required: + - policyId + SearchPoliciesDTO: + type: object + properties: + target: + type: object + result: + type: object + required: + - target + - result + FilterPoliciesDTO: + type: object + properties: + policyId1: + type: string + policyId2: + type: string + policyIds: + type: string + eventsLvl: + type: number + propLvl: + type: number + childrenLvl: + type: number + idLvl: + type: number + required: + - policyId1 + - policyId2 + - policyIds + - eventsLvl + - propLvl + - childrenLvl + - idLvl + ComparePoliciesDTO: + type: object + properties: + blocks: + type: object + groups: + type: object + left: + type: object + right: + type: object + roles: + type: object + tokens: + type: object + topics: + type: object + total: + type: object + required: + - blocks + - groups + - left + - right + - roles + - tokens + - topics + - total + FilterModulesDTO: + type: object + properties: + moduleId1: + type: string + moduleId2: + type: string + eventsLvl: + type: number + propLvl: + type: number + childrenLvl: + type: number + idLvl: + type: number + required: + - moduleId1 + - moduleId2 + - eventsLvl + - propLvl + - childrenLvl + - idLvl + CompareModulesDTO: + type: object + properties: + blocks: + type: object + left: + type: object + right: + type: object + inputEvents: + type: object + outputEvents: + type: object + variables: + type: object + total: + type: object + required: + - blocks + - left + - right + - inputEvents + - outputEvents + - variables + - total + FilterSchemasDTO: + type: object + properties: + schemaId1: + type: string + schemaId2: + type: string + idLvl: + type: number + required: + - schemaId1 + - schemaId2 + - idLvl + CompareSchemasDTO: + type: object + properties: + fields: + type: object + left: + type: object + right: + type: object + total: + type: object + required: + - fields + - left + - right + - total + FilterDocumentsDTO: + type: object + properties: + documentId1: + type: string + documentId2: + type: string + documentIds: + type: string + required: + - documentId1 + - documentId2 + - documentIds + CompareDocumentsDTO: + type: object + properties: + documents: + type: object + left: + type: object + right: + type: object + total: + type: object + required: + - documents + - left + - right + - total + FilterToolsDTO: + type: object + properties: + toolId1: + type: string + toolId2: + type: string + toolIds: + type: string + required: + - toolId1 + - toolId2 + - toolIds + CompareToolsDTO: + type: object + properties: + blocks: + type: object + left: + type: object + right: + type: object + inputEvents: + type: object + outputEvents: + type: object + variables: + type: object + total: + type: object + required: + - blocks + - left + - right + - inputEvents + - outputEvents + - variables + - total + ArtifactDTOItem: + type: object + properties: + id: + type: string + name: + type: string + uuid: + type: string + extention: + type: string + type: + type: string + required: + - id + - name + - uuid + - extention + - type + ContractDTO: + type: object + properties: + id: + type: string + contractId: + type: string + description: + type: string + owner: + type: string + permissions: + type: number + topicId: + type: string + type: + type: string + enum: + - WIPE + - RETIRE + syncRequestsDate: + format: date-time + type: string + syncPoolsDate: + format: date-time + type: string + lastSyncEventTimeStamp: + type: string + wipeContractIds: + type: array + items: + type: string + required: + - id + - contractId + - description + - owner + - permissions + - topicId + - type + - syncRequestsDate + - syncPoolsDate + - lastSyncEventTimeStamp + - wipeContractIds + WiperRequestDTO: + type: object + properties: + id: + type: string + contractId: + type: string + user: + type: string + required: + - id + - contractId + - user + RetireRequestDTO: + type: object + properties: + id: + type: string + contractId: + type: string + tokens: + type: object + properties: + token: + type: string + count: + type: number + serials: + type: array + items: + type: number + decimals: + type: number + type: + enum: + - non-fungible + - fungible + tokenSymbol: + type: string + tokenIds: + type: array + items: + type: string + user: + type: string + required: + - id + - contractId + - tokens + - tokenIds + - user + Date: + type: object + properties: {} + RetirePoolDTO: + type: object + properties: + id: + type: string + contractId: + type: string + tokens: + type: object + properties: + token: + type: string + contract: + type: string + count: + type: number + decimals: + type: number + type: + enum: + - non-fungible + - fungible + tokenSymbol: + type: string + tokenIds: + type: array + items: + type: string + immediately: + type: boolean + enabled: + type: boolean + required: + - id + - contractId + - tokens + - tokenIds + - immediately + - enabled + RetirePoolTokenDTO: + type: object + properties: + token: + type: string + count: + type: number + required: + - token + - count + RetireRequestTokenDTO: + type: object + properties: + token: + type: string + count: + type: number + serials: + type: array + items: + type: string + required: + - token + - count + - serials + ProfileDTO: + type: object + properties: + username: + type: string + nullable: false + role: + type: string + nullable: false + did: + type: string + nullable: true + parent: + type: string + nullable: true + hederaAccountId: + type: string + nullable: true + confirmed: + type: boolean + nullable: true + failed: + type: boolean + nullable: true + topicId: + type: string + nullable: true + parentTopicId: + type: string + nullable: true + didDocument: + type: object + nullable: true + vcDocument: + type: object + nullable: true + required: + - username + - role + SubjectDTO: + type: object + properties: + '@context': + nullable: true + type: array + items: + type: string + id: + type: string + nullable: true + type: + type: string + nullable: true + required: + - '@context' + DidDocumentDTO: + type: object + properties: + id: + type: string + nullable: false + context: + nullable: true + type: array + items: + type: string + alsoKnownAs: + nullable: true + type: array + items: + type: string + controller: + nullable: true + type: array + items: + type: string + verificationMethod: + nullable: true + type: array + items: + type: object + authentication: + nullable: true + type: array + items: + type: object + assertionMethod: + nullable: true + type: array + items: + type: object + keyAgreement: + nullable: true + type: array + items: + type: object + capabilityInvocation: + nullable: true + type: array + items: + type: object + capabilityDelegation: + nullable: true + type: array + items: + type: object + service: + nullable: true + type: array + items: + type: object + required: + - id + - context + - alsoKnownAs + - controller + - verificationMethod + - authentication + - assertionMethod + - keyAgreement + - capabilityInvocation + - capabilityDelegation + - service + DidKeyDTO: + type: object + properties: + id: + type: string + nullable: false + key: + type: string + nullable: false + required: + - id + - key + CredentialsDTO: + type: object + properties: + entity: + type: string + nullable: false + hederaAccountId: + type: string + nullable: false + hederaAccountKey: + type: string + nullable: false + parent: + type: string + nullable: true + vcDocument: + nullable: true + allOf: + - $ref: '#/components/schemas/SubjectDTO' + didDocument: + nullable: true + allOf: + - $ref: '#/components/schemas/DidDocumentDTO' + didKeys: + nullable: true + type: array + items: + $ref: '#/components/schemas/DidKeyDTO' + required: + - entity + - hederaAccountId + - hederaAccountKey + TaskDTO: + type: object + properties: + taskId: + type: string + expectation: + type: number + required: + - taskId + - expectation + DidDocumentStatusDTO: + type: object + properties: + valid: + type: boolean + nullable: false + error: + type: string + nullable: true + didDocument: + type: object + nullable: false + required: + - valid + - error + - didDocument + DidDocumentWithKeyDTO: + type: object + properties: + document: + nullable: false + allOf: + - $ref: '#/components/schemas/DidDocumentDTO' + keys: + nullable: false + type: array + items: + $ref: '#/components/schemas/DidKeyDTO' + required: + - document + - keys + DidKeyStatusDTO: + type: object + properties: + id: + type: string + nullable: false + key: + type: string + nullable: false + valid: + type: boolean + nullable: false + required: + - id + - key + - valid + MigrationConfigPoliciesDTO: + type: object + properties: + src: + type: string + dst: + type: string + required: + - src + - dst + MigrationConfigDTO: + type: object + properties: + policies: + $ref: '#/components/schemas/MigrationConfigPoliciesDTO' + vcs: + type: array + items: + type: string + vps: + type: array + items: + type: string + schemas: + type: object + groups: + type: object + roles: + type: object + required: + - policies + - vcs + - vps + - schemas + - groups + - roles + PolicyCategoryDTO: + type: object + properties: + id: + type: string + name: + type: string + type: + type: string + required: + - id + - name + - type + SchemaDTO: + type: object + properties: + id: + type: string + name: + type: string + description: + type: string + entity: + type: string + document: + type: string + uuid: + type: string + iri: + type: string + hash: + type: string + status: + type: string + topicId: + type: string + version: + type: string + owner: + type: string + messageId: + type: string + required: + - id + - name + - description + - entity + - document + - uuid + - iri + - hash + - status + - topicId + - version + - owner + - messageId + VersionSchemaDTO: + type: object + properties: + version: + type: string + required: + - version + MessageSchemaDTO: + type: object + properties: + messageId: + type: string + required: + - messageId + ExportSchemaDTO: + type: object + properties: + id: + type: string + name: + type: string + description: + type: string + version: + type: string + owner: + type: string + messageId: + type: string + required: + - id + - name + - description + - version + - owner + - messageId + SystemSchemaDTO: + type: object + properties: + name: + type: string + entity: + type: string + required: + - name + - entity + SettingsDTO: + type: object + properties: + ipfsStorageApiKey: + type: string + operatorId: + type: string + operatorKey: + type: string + required: + - ipfsStorageApiKey + - operatorId + - operatorKey + SuggestionsInputDTO: + type: object + properties: + blockType: + type: string + children: + nullable: true + type: array + items: + type: object + required: + - blockType + - children + SuggestionsOutputDTO: + type: object + properties: + next: + type: string + nested: + type: string + required: + - next + - nested + SuggestionsConfigItemDTO: + type: object + properties: + id: + type: string + type: + type: string + enum: + - Policy + - Module + index: + type: number + required: + - id + - type + - index + SuggestionsConfigDTO: + type: object + properties: + items: + $ref: '#/components/schemas/SuggestionsConfigItemDTO' + required: + - items + NotificationDTO: + type: object + properties: + title: + type: string + message: + type: string + type: + type: string + enum: + - INFO + - ERROR + - WARN + - SUCCESS + action: + type: string + enum: + - POLICY_CONFIGURATION + - POLICY_VIEW + - POLICIES_PAGE + - SCHEMAS_PAGE + - TOKENS_PAGE + - PROFILE_PAGE + result: + type: object + read: + type: boolean + old: + type: boolean + required: + - title + - message + - type + - action + - result + - read + - old + ProgressDTO: + type: object + properties: + action: + type: string + message: + type: string + progress: + type: number + type: + type: string + enum: + - INFO + - ERROR + - WARN + - SUCCESS + taskId: + type: string + required: + - action + - message + - progress + - type + - taskId + ProjectDTO: + type: object + properties: + id: + type: string + policyId: + type: string + policyName: + type: string + registered: + type: string + title: + type: string + companyName: + type: string + sectoralScope: + type: string + required: + - id + - policyId + - policyName + - registered + - title + - companyName + - sectoralScope + PropertiesDTO: + type: object + properties: + id: + type: string + title: + type: string + value: + type: string + required: + - id + - title + - value + RecordStatusDTO: + type: object + properties: + type: + type: string + policyId: + type: string + uuid: + type: string + status: + type: string + required: + - type + - policyId + - uuid + - status + Object: + type: object + properties: {} + RecordActionDTO: + type: object + properties: + uuid: + type: string + policyId: + type: string + method: + type: string + action: + type: string + time: + type: string + user: + type: string + target: + type: string + required: + - uuid + - policyId + - method + - action + - time + - user + - target + ResultInfoDTO: + type: object + properties: + tokens: + type: number + documents: + type: number + required: + - tokens + - documents + ResultDocumentDTO: + type: object + properties: + type: + type: string + schema: + type: string + rate: + type: string + documents: + type: object + required: + - type + - schema + - rate + - documents + RunningResultDTO: + type: object + properties: + info: + $ref: '#/components/schemas/ResultInfoDTO' + total: + type: number + documents: + $ref: '#/components/schemas/ResultDocumentDTO' + required: + - info + - total + - documents + RunningDetailsDTO: + type: object + properties: + left: + type: object + right: + type: object + total: + type: number + documents: + type: object + required: + - left + - right + - total + - documents + ToolDTO: + type: object + properties: + id: + type: string + uuid: + type: string + name: + type: string + description: + type: string + config: + type: object + status: + type: string + creator: + type: string + owner: + type: string + topicId: + type: string + messageId: + type: string + codeVersion: + type: string + createDate: + type: string + required: + - id + - uuid + - name + - description + - config + - status + - creator + - owner + - topicId + - messageId + - codeVersion + - createDate + RegisteredUsersDTO: + type: object + properties: + username: + type: string + did: + type: string + parent: + type: string + role: + type: string + policyRoles: + type: array + items: + type: string + required: + - username + - did + - parent + - role + - policyRoles + Credentials: + type: object + required: + - username + - password + properties: + username: + type: string + password: + type: string + Account: + type: object + required: + - username + - role + properties: + username: + type: string + role: + type: string + did: + type: string + Session: + type: object + required: + - username + - role + - accessToken + properties: + username: + type: string + role: + type: string + accessToken: + type: string + User: + type: object + required: + - username + - role + properties: + confirmed: + type: string + failed: + type: string + username: + type: string + role: + type: string + hederaAccountId: + type: string + hederaAccountKey: + type: string + did: + type: string + didDocument: + type: object + vcDocument: + type: object + parent: + type: string + topicId: + type: string + Schema: + type: object + required: + - id + - name + - description + - entity + - document + properties: + id: + type: string + iri: + type: string + uuid: + type: string + name: + type: string + description: + type: string + entity: + type: string + hash: + type: string + status: + type: string + document: + oneOf: + - type: string + - type: object + topicId: + type: string + version: + type: string + owner: + type: string + messageId: + type: string + ImportSchema: + type: object + required: + - schemes + properties: + schemes: + type: array + items: + type: object + required: + - document + - entity + - name + - uuid + properties: + document: + type: string + entity: + type: string + hash: + type: string + name: + type: string + uuid: + type: string + ExportSchema: + type: object + required: + - ids + properties: + name: + type: string + version: + type: string + messageId: + type: string + Token: + type: object + required: + - changeSupply + - decimals + - enableAdmin + - enableKYC + - enableFreeze + - enableWipe + - initialSupply + - tokenName + - tokenSymbol + - tokenType + properties: + changeSupply: + type: boolean + decimals: + type: string + enableAdmin: + type: boolean + enableFreeze: + type: boolean + enableKYC: + type: boolean + enableWipe: + type: boolean + initialSupply: + type: string + tokenName: + type: string + tokenSymbol: + type: string + tokenType: + type: string + TokenInfo: + type: object + required: + - id + - tokenId + - tokenName + - tokenSymbol + - tokenType + - decimals + - associated + - balance + - frozen + - kyc + properties: + id: + type: string + tokenId: + type: string + tokenName: + type: string + tokenSymbol: + type: string + tokenType: + type: string + decimals: + type: string + associated: + type: boolean + balance: + type: string + frozen: + type: boolean + kyc: + type: boolean + enableAdmin: + type: boolean + enableKYC: + type: boolean + enableFreeze: + type: boolean + enableWipe: + type: boolean + PolicyConfig: + type: object + required: + - name + - version + - description + - topicDescription + - config + - topicId + - policyTag + properties: + id: + type: string + uuid: + type: string + name: + type: string + version: + type: string + description: + type: string + topicDescription: + type: string + config: + type: object + status: + type: string + owner: + type: string + policyRoles: + type: array + items: + type: string + topicId: + type: string + policyTag: + type: string + policyTopics: + type: array + items: + type: object + properties: + name: + type: string + description: + type: string + type: + type: string + static: + type: boolean + TrustChains: + type: object + required: + - chain + - userMap + properties: + chain: + type: array + items: + type: object + required: + - id + - type + - tag + - label + - schema + - owner + - document + properties: + id: + type: string + type: + type: string + tag: + type: string + label: + type: string + schema: + type: string + owner: + type: string + document: + type: object + userMap: + type: array + items: + type: object + required: + - did + - username + properties: + did: + type: string + username: + type: string + VerifiablePresentation: + type: object + required: + - hash + - id + - policyId + - signature + - status + - tag + - type + - updateDate + - createDate + - owner + - document + properties: + hash: + type: string + id: + type: string + policyId: + type: string + signature: + type: string + status: + type: string + tag: + type: string + type: + type: string + updateDate: + type: string + createDate: + type: string + owner: + type: string + document: + type: object + PublishPolicy: + type: object + required: + - errors + - isValid + - policies + properties: + errors: + type: array + items: + type: object + isValid: + type: boolean + policies: + type: array + items: + type: object + ValidatePolicy: + type: object + required: + - config + - results + properties: + config: + type: object + results: + type: object + PolicyBlock: + type: object + required: + - id + - blockType + - isActive + - uiMetaData + properties: + id: + type: string + blockType: + type: string + isActive: + type: boolean + uiMetaData: + type: object + blocks: + type: array + items: + type: object + PolicyBlockData: + type: object + required: + - id + - isActive + - uiMetaData + - data + properties: + id: + type: string + blockType: + type: string + isActive: + type: boolean + uiMetaData: + type: object + data: + type: object + fields: + type: array + items: + type: object + index: + type: number + roles: + type: array + items: + type: string + blocks: + type: array + items: + $ref: '#/components/schemas/PolicyBlock' + ExportPolicy: + type: object + required: + - name + - version + - messageId + properties: + name: + type: string + version: + type: string + tokens: + type: string + PreviewPolicy: + type: object + required: + - policy + - schemas + - tokens + properties: + policy: + type: object + schemas: + type: array + items: + type: object + tokens: + type: array + items: + type: object + Error: + type: object + required: + - code + - message + properties: + code: + type: number + message: + type: string + ExternalData: + type: object + required: + - owner + - policyTag + - document + properties: + owner: + type: string + policyTag: + type: string + document: + type: object + HederaAccount: + type: object + required: + - id + - key + properties: + id: + type: string + key: + type: string + CommonSettings: + type: object + properties: + operatorId: + type: string + operatorKey: + type: string + nftApiKey: + deprecated: true + type: string + ipfsStorageApiKey: + type: string + LogFilters: + type: object + properties: + type: + type: string + startDate: + type: string + endDate: + type: string + attributes: + type: array + items: + type: string + message: + type: string + pageSize: + type: number + pageIndex: + type: number + sortDirection: + type: string + enum: + - ASC + - DESC + Log: + type: object + properties: + type: + type: string + datetime: + type: string + message: + type: string + attributes: + type: array + items: + type: string + Task: + type: object + properties: + taskId: + type: string + expectation: + type: number + TaskStatus: + type: object + properties: + date: + type: string + name: + type: string + statuses: + type: array + items: + type: object + properties: + type: + type: string + message: + type: string + result: + type: object + error: + type: object + Artifact: + type: object + properties: + id: + type: string + name: + type: string + uuid: + type: string + extention: + type: string + type: + type: string + MultiPolicyConfig: + type: object + properties: + id: + type: string + uuid: + type: string + owner: + type: string + type: + type: string + instanceTopicId: + type: string + mainPolicyTopicId: + type: string + synchronizationTopicId: + type: string + policyOwner: + type: string + user: + type: string + Contract: + type: object + properties: + id: + type: string + contractId: + type: string + description: + type: string + owner: + type: string + isOwnerCreator: + type: string + status: + type: string + RetireRequest: + type: object + properties: + id: + type: string + contractId: + type: string + baseTokenId: + type: string + owner: + type: string + oppositeTokenId: + type: string + baseTokenCount: + type: number + oppositeTokenCount: + type: number + Module: + type: object + properties: + id: + type: string + uuid: + type: string + name: + type: string + description: + type: string + config: + type: object + status: + type: string + creator: + type: string + owner: + type: string + topicId: + type: string + messageId: + type: string + codeVersion: + type: string + createDate: + type: string + type: + type: string + PreviewModule: + type: object + properties: + module: + $ref: '#/components/schemas/Module' + ExportModule: + type: object + properties: + uuid: + type: string + name: + type: string + description: + type: string + messageId: + type: string + owner: + type: string + PublishModule: + type: object + properties: + errors: + type: object + isValid: + type: boolean + module: + $ref: '#/components/schemas/Module' + ValidateModule: + type: object + properties: + module: + $ref: '#/components/schemas/Module' + results: + type: object + Tag: + type: object + required: + - name + - entity + - localTarget + properties: + uuid: + type: string + example: 00000000-0000-0000-0000-000000000000 + name: + type: string + example: Tag label + description: + type: string + example: Description + owner: + type: string + example: did + entity: + type: string + enum: + - Schema + - Policy + - Token + - Module + - Contract + - PolicyDocument + example: PolicyDocument + target: + type: string + example: '0000000000.000000000' + localTarget: + type: string + example: db id + status: + type: string + enum: + - Draft + - Published + - History + example: Published + operation: + type: string + enum: + - Create + - Delete + example: Create + date: + type: string + example: '1900-01-01T00:00:00.000Z' + topicId: + type: string + example: 0.0.0000000 + messageId: + type: string + example: '0000000000.000000000' + policyId: + type: string + example: db id + uri: + type: string + example: document uri + document: + type: object + TagMap: + type: object + required: + - entity + - target + - refreshDate + - tags + properties: + entity: + type: string + enum: + - Schema + - Policy + - Token + - Module + - Contract + - PolicyDocument + example: PolicyDocument + target: + type: string + example: db id + refreshDate: + type: string + example: '1900-01-01T00:00:00.000Z' + tags: + type: array + items: + $ref: '#/components/schemas/Tag' + Theme: + type: object + required: + - uuid + - name + - rules + properties: + id: + type: string + example: db id + uuid: + type: string + example: 00000000-0000-0000-0000-000000000000 + name: + type: string + example: Theme name + rules: + type: array + items: + type: object + required: + - text + - background + - border + - shape + - borderWidth + - filterType + - filterValue + properties: + description: + type: string + example: description + text: + type: string + pattern: (^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$) + example: '#000000' + background: + type: string + pattern: (^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$) + example: '#000000' + border: + type: string + pattern: (^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$) + example: '#000000' + shape: + type: string + enum: + - '0' + - '1' + - '2' + - '3' + - '4' + - '5' + example: '0' + borderWidth: + type: string + enum: + - 0px + - 1px + - 2px + - 3px + - 4px + - 5px + - 6px + - 7px + example: 2px + filterType: + type: string + enum: + - type + - api + - role + example: type + filterValue: + oneOf: + - type: string + - type: array + items: + type: string + example: + - type + WizardConfig: + type: object + required: + - policy + - roles + - schemas + - trustChain + properties: + roles: + type: array + items: + type: string + policy: + type: object + properties: + name: + type: string + description: + type: string + topicDescription: + type: string + policyTag: + type: string + schemas: + type: array + items: + type: object + properties: + name: + type: string + iri: + type: string + isApproveEnable: + type: boolean + isMintSchema: + type: boolean + mintOptions: + type: object + properties: + tokenId: + type: string + rule: + type: string + dependencySchemaIri: + type: string + relationshipsSchemaIri: + type: string + initialRolesFor: + type: array + items: + type: string + rolesConfig: + type: array + items: + type: object + properties: + role: + type: string + isApprover: + type: boolean + isCreator: + type: boolean + gridColumns: + type: array + items: + type: object + properties: + field: + type: string + title: + type: string + trustChain: + type: array + items: + type: object + properties: + role: + type: string + mintSchemaIri: + type: string + viewOnlyOwnDocuments: + type: boolean diff --git a/docs/.gitbook/assets/swagger (2).yaml b/docs/.gitbook/assets/swagger (2).yaml index 26784dd621..79eefbaddc 100644 --- a/docs/.gitbook/assets/swagger (2).yaml +++ b/docs/.gitbook/assets/swagger (2).yaml @@ -112,7 +112,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_0 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /accounts/standard-registries: get: operationId: AccountApi_getStandatdRegistries @@ -138,7 +139,7 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_0 security: - - bearerAuth: [] + - bearer: [] /accounts/standard-registries/aggregated: get: operationId: AccountApi_getAggregatedStandardRegistries @@ -166,7 +167,7 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_0 security: - - bearerAuth: [] + - bearer: [] /accounts/balance: get: operationId: AccountApi_getBalance @@ -192,7 +193,7 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_0 security: - - bearerAuth: [] + - bearer: [] /analytics/search/policies: post: operationId: AnalyticsApi_searchPolicies @@ -232,7 +233,8 @@ paths: tags: &ref_1 - analytics security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/policies: post: operationId: AnalyticsApi_comparePolicies @@ -285,7 +287,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/modules: post: operationId: AnalyticsApi_compareModules @@ -328,7 +331,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/schemas: post: operationId: AnalyticsApi_compareSchemas @@ -369,7 +373,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/documents: post: operationId: AnalyticsApi_compareDocuments @@ -414,7 +419,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/tools: post: operationId: AnalyticsApi_compareTools @@ -459,7 +465,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/policies/export: post: operationId: AnalyticsApi_comparePoliciesExport @@ -512,7 +519,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/modules/export: post: operationId: AnalyticsApi_compareModulesExport @@ -555,7 +563,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/schemas/export: post: operationId: AnalyticsApi_compareSchemasExport @@ -596,7 +605,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/documents/export: post: operationId: AnalyticsApi_compareDocumentsExport @@ -641,7 +651,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/compare/tools/export: post: operationId: AnalyticsApi_compareToolsExport @@ -686,7 +697,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /analytics/search/blocks: post: operationId: AnalyticsApi_searchBlocks @@ -726,14 +738,15 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: *ref_1 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /artifacts: get: tags: - artifacts description: Returns all artifacts. security: - - bearerAuth: [] + - bearer: [] summary: Returns all artifacts. parameters: - in: query @@ -797,6 +810,19 @@ paths: description: Parent ID schema: type: string + requestBody: + required: true + description: Form data with artifacts. + content: + multipart/form-data: + schema: + type: array + items: + type: object + properties: + artifacts: + type: string + format: binary responses: '200': description: Successful operation. @@ -819,14 +845,15 @@ paths: tags: - artifacts security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /artifacts/{artifactId}: delete: tags: - artifacts description: Delete artifact. security: - - bearerAuth: [] + - bearer: [] summary: Delete artifact. parameters: - in: path @@ -912,6 +939,7 @@ paths: - contracts security: - bearer: [] + - bearer: [] post: operationId: ContractsApi_createContract summary: Create contract. @@ -948,6 +976,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/import: post: operationId: ContractsApi_importContract @@ -991,6 +1020,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/{contractId}/permissions: get: operationId: ContractsApi_contractPermissions @@ -1026,6 +1056,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/{contractId}: delete: operationId: ContractsApi_removeContract @@ -1061,6 +1092,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/requests: get: operationId: ContractsApi_getWipeRequests @@ -1119,6 +1151,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/{contractId}/requests/enable: post: operationId: ContractsApi_enableWipeRequests @@ -1128,7 +1161,7 @@ paths: role are allowed to make the request. parameters: - name: contractId - required: false + required: true in: path description: Contract identifier example: 652745597a7b53526de37c05 @@ -1150,6 +1183,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/{contractId}/requests/disable: post: operationId: ContractsApi_disableWipeRequests @@ -1159,7 +1193,7 @@ paths: role are allowed to make the request. parameters: - name: contractId - required: false + required: true in: path description: Contract identifier example: 652745597a7b53526de37c05 @@ -1181,6 +1215,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/requests/{requestId}/approve: post: operationId: ContractsApi_approveWipeRequest @@ -1212,6 +1247,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/requests/{requestId}/reject: delete: operationId: ContractsApi_rejectWipeRequest @@ -1249,6 +1285,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/{contractId}/requests: delete: operationId: ContractsApi_clearWipeRequests @@ -1280,6 +1317,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/{contractId}/admin/{hederaId}: post: operationId: ContractsApi_wipeAddAdmin @@ -1318,6 +1356,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] delete: operationId: ContractsApi_wipeRemoveAdmin summary: Remove wipe admin. @@ -1355,6 +1394,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/{contractId}/manager/{hederaId}: post: operationId: ContractsApi_wipeAddManager @@ -1393,6 +1433,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] delete: operationId: ContractsApi_wipeRemoveManager summary: Remove wipe manager. @@ -1430,6 +1471,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/wipe/{contractId}/wiper/{hederaId}: post: operationId: ContractsApi_wipeAddWiper @@ -1468,6 +1510,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] delete: operationId: ContractsApi_wipeRemoveWiper summary: Remove wipe wiper. @@ -1505,6 +1548,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/{contractId}/pools/sync: post: operationId: ContractsApi_retireSyncPools @@ -1514,7 +1558,7 @@ paths: are allowed to make the request. parameters: - name: contractId - required: false + required: true in: path description: Contract identifier example: 652745597a7b53526de37c05 @@ -1540,6 +1584,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/requests: get: operationId: ContractsApi_getRetireRequests @@ -1596,6 +1641,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/pools: get: operationId: ContractsApi_getRetirePools @@ -1659,6 +1705,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/{contractId}/requests: delete: operationId: ContractsApi_clearRetireRequests @@ -1668,7 +1715,7 @@ paths: role are allowed to make the request. parameters: - name: contractId - required: false + required: true in: path description: Contract identifier example: 652745597a7b53526de37c05 @@ -1694,6 +1741,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/{contractId}/pools: delete: operationId: ContractsApi_clearRetirePools @@ -1703,7 +1751,7 @@ paths: are allowed to make the request. parameters: - name: contractId - required: false + required: true in: path description: Contract identifier example: 652745597a7b53526de37c05 @@ -1729,6 +1777,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] post: operationId: ContractsApi_setRetirePool summary: Set retire pool. @@ -1737,7 +1786,7 @@ paths: allowed to make the request. parameters: - name: contractId - required: false + required: true in: path description: Contract identifier example: 652745597a7b53526de37c05 @@ -1769,6 +1818,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/pools/{poolId}: delete: operationId: ContractsApi_unsetRetirePool @@ -1778,7 +1828,7 @@ paths: are allowed to make the request. parameters: - name: poolId - required: false + required: true in: path description: Pool Identifier example: 652745597a7b53526de37c05 @@ -1804,6 +1854,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/requests/{requestId}: delete: operationId: ContractsApi_unsetRetireRequest @@ -1813,7 +1864,7 @@ paths: role are allowed to make the request. parameters: - name: requestId - required: false + required: true in: path description: Request Identifier example: 652745597a7b53526de37c05 @@ -1839,6 +1890,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/pools/{poolId}/retire: post: operationId: ContractsApi_retire @@ -1846,7 +1898,7 @@ paths: description: Retire tokens. parameters: - name: poolId - required: false + required: true in: path description: Pool Identifier example: 652745597a7b53526de37c05 @@ -1878,6 +1930,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/requests/{requestId}/approve: post: operationId: ContractsApi_approveRetire @@ -1909,6 +1962,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/requests/{requestId}/cancel: delete: operationId: ContractsApi_cancelRetireRequest @@ -1938,6 +1992,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire/{contractId}/admin/{hederaId}: post: operationId: ContractsApi_retireAddAdmin @@ -1976,6 +2031,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] delete: operationId: ContractsApi_retireRemoveAdmin summary: Remove wipe admin. @@ -2013,6 +2069,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /contracts/retire: get: operationId: ContractsApi_getRetireVCs @@ -2046,9 +2103,7 @@ paths: content: application/json: schema: - type: array - items: - $ref: '#/components/schemas/' + type: object '401': description: Unauthorized. '403': @@ -2062,6 +2117,7 @@ paths: tags: *ref_2 security: - bearer: [] + - bearer: [] /demo/registered-users: get: operationId: DemoApi_registeredUsers @@ -2083,7 +2139,7 @@ paths: - demo description: Generates a new Hedera account with a random private key. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -2107,7 +2163,7 @@ paths: - demo description: Generates a new Hedera account with a random private key. security: - - bearerAuth: [] + - bearer: [] summary: Generates a new Hedera account with a random private key. responses: '202': @@ -2155,12 +2211,31 @@ paths: description: Add file from ipfs. parameters: [] responses: - '201': - description: '' - tags: + '401': + description: Unauthorized + tags: &ref_3 - ipfs security: - - bearerAuth: [] + - bearer: [] + /ipfs/file/dry-run/{policyId}: + post: + operationId: IpfsApi_postFileDryRun + summary: Add file from ipfs for dry run mode. + description: Add file from ipfs for dry run mode. + parameters: + - name: policyId + required: true + in: path + description: Policy identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '401': + description: Unauthorized + tags: *ref_3 + security: + - bearer: [] /ipfs/file/{cid}: get: tags: @@ -2175,7 +2250,7 @@ paths: required: true description: File CID. security: - - bearerAuth: [] + - bearer: [] responses: '201': description: Created. @@ -2192,13 +2267,30 @@ paths: application/json: schema: $ref: '#/components/schemas/Error' + /ipfs/file/{cid}/dry-run: + get: + operationId: IpfsApi_getFileDryRun + summary: Get file from ipfs for dry run mode. + description: Get file from ipfs for dry run mode. + parameters: + - name: cid + required: true + in: path + schema: + type: string + responses: + '401': + description: Unauthorized + tags: *ref_3 + security: + - bearer: [] /logs: post: tags: - logs description: Returns logs. For users with the Standard Registry role only. security: - - bearerAuth: [] + - bearer: [] requestBody: description: Log filters. content: @@ -2247,7 +2339,7 @@ paths: type: string description: Attributes to exclude. security: - - bearerAuth: [] + - bearer: [] summary: Returns logs attributes. responses: '200': @@ -2274,7 +2366,7 @@ paths: - maps description: Returns map api key. security: - - bearerAuth: [] + - bearer: [] summary: Returns map api key. responses: '200': @@ -2317,7 +2409,7 @@ paths: Returns all modules. Only users with the Standard Registry and Installer role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Return a list of all modules. parameters: - in: query @@ -2369,7 +2461,7 @@ paths: Creates a new module. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Creates a new module. requestBody: description: Object that contains module configuration. @@ -2396,17 +2488,21 @@ paths: operationId: ModulesApi_getModuleSchemas parameters: [] responses: - '200': - description: '' - tags: &ref_3 + '401': + description: Unauthorized + tags: &ref_4 - modules + security: + - bearer: [] post: operationId: ModulesApi_postSchemas parameters: [] responses: - '201': - description: '' - tags: *ref_3 + '401': + description: Unauthorized + tags: *ref_4 + security: + - bearer: [] /modules/{uuid}: get: tags: @@ -2423,7 +2519,7 @@ paths: description: Selected module ID. summary: Retrieves module configuration. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -2463,7 +2559,7 @@ paths: schema: $ref: '#/components/schemas/Module' security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -2495,7 +2591,7 @@ paths: required: true description: Module ID. security: - - bearerAuth: [] + - bearer: [] summary: Deletes the module. responses: '200': @@ -2522,7 +2618,7 @@ paths: Returns modules menu. Only users with the Standard Registry and Installer role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Return a list of modules. responses: '200': @@ -2559,7 +2655,7 @@ paths: required: true description: Selected module ID. security: - - bearerAuth: [] + - bearer: [] summary: >- Return module and its artifacts in a zip file format for the specified module. @@ -2592,7 +2688,7 @@ paths: required: true description: Selected module ID. security: - - bearerAuth: [] + - bearer: [] summary: Return Heder message ID for the specified published module. responses: '200': @@ -2620,7 +2716,7 @@ paths: DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Imports new module from IPFS. requestBody: description: >- @@ -2660,7 +2756,7 @@ paths: VCs, from the provided zip file into the local DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Imports new module from a zip file. requestBody: description: >- @@ -2698,7 +2794,7 @@ paths: users with the Standard Registry role are allowed to make the request. summary: Module preview from IPFS. security: - - bearerAuth: [] + - bearer: [] requestBody: description: >- Object that contains the identifier of the Hedera message which @@ -2738,7 +2834,7 @@ paths: request. summary: Module preview from a zip file. security: - - bearerAuth: [] + - bearer: [] requestBody: description: >- A zip file that contains the module and associated schemas and VCs to @@ -2784,7 +2880,7 @@ paths: description: Selected module ID. summary: Publishes the module onto IPFS. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -2810,7 +2906,7 @@ paths: Validates selected module. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Validates module. requestBody: description: Object that contains module configuration. @@ -2851,16 +2947,19 @@ paths: application/json: schema: $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_4 + tags: &ref_5 - tools security: - - bearerAuth: [] + - bearer: [] + - bearer: [] get: operationId: ToolsApi_getTools summary: Return a list of all tools. @@ -2889,15 +2988,18 @@ paths: application/json: schema: $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/push: post: operationId: ToolsApi_createNewToolAsync @@ -2913,15 +3015,18 @@ paths: application/json: schema: $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/{id}: delete: operationId: ToolsApi_deleteTool @@ -2939,15 +3044,18 @@ paths: responses: '200': description: Successful operation. + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] get: operationId: ToolsApi_getToolById summary: Retrieves tool configuration. @@ -2978,9 +3086,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] put: operationId: ToolsApi_updateTool summary: Updates tool configuration. @@ -3011,9 +3120,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/{id}/publish: put: operationId: ToolsApi_publishTool @@ -3047,9 +3157,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/{id}/push/publish: put: operationId: ToolsApi_publishToolAsync @@ -3083,9 +3194,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/validate: post: operationId: ToolsApi_validateTool @@ -3111,9 +3223,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/{id}/export/file: get: operationId: ToolsApi_toolExportFile @@ -3144,9 +3257,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/{id}/export/message: get: operationId: ToolsApi_toolExportMessage @@ -3179,9 +3293,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/import/message/preview: post: operationId: ToolsApi_toolImportMessagePreview @@ -3208,9 +3323,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/import/message: post: operationId: ToolsApi_toolImportMessage @@ -3237,9 +3353,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/import/file/preview: post: operationId: ToolsApi_toolImportFilePreview @@ -3266,9 +3383,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/import/file: post: operationId: ToolsApi_toolImportFile @@ -3295,25 +3413,40 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] - /tools/push/import/file: + - bearer: [] + - bearer: [] + /tools/import/file-metadata: post: - operationId: ToolsApi_toolImportFileAsync + operationId: ToolsApi_toolImportFileWithMetadata summary: Imports new tool from a zip file. description: >- Imports new tool and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB. Only users with the Standard Registry role are allowed to make the request. parameters: [] + requestBody: + required: true + description: Form data with tool file and metadata. + content: + multipart/form-data: + schema: + type: object + properties: + file: + type: string + format: binary + metadata: + type: string + format: binary responses: '200': description: Successful operation. content: application/json: schema: - $ref: '#/components/schemas/TaskDTO' + $ref: '#/components/schemas/ToolDTO' '401': description: Unauthorized. '403': @@ -3324,14 +3457,89 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] - /tools/push/import/message: + - bearer: [] + - bearer: [] + /tools/push/import/file: post: - operationId: ToolsApi_toolImportMessageAsync - summary: Imports new tool from IPFS. - description: >- + operationId: ToolsApi_toolImportFileAsync + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearer: [] + - bearer: [] + /tools/push/import/file-metadata: + post: + operationId: ToolsApi_toolImportFileWithMetadataAsync + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Form data with tool file and metadata. + content: + multipart/form-data: + schema: + type: object + properties: + file: + type: string + format: binary + metadata: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearer: [] + - bearer: [] + /tools/push/import/message: + post: + operationId: ToolsApi_toolImportMessageAsync + summary: Imports new tool from IPFS. + description: >- Imports new tool and all associated artifacts from IPFS into the local DB. Only users with the Standard Registry role are allowed to make the request. @@ -3353,9 +3561,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /tools/menu/all: get: operationId: ToolsApi_getMenu @@ -3371,6 +3580,8 @@ paths: application/json: schema: type: array + items: + type: object '401': description: Unauthorized. '403': @@ -3381,9 +3592,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_4 + tags: *ref_5 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /profiles/{username}: get: operationId: ProfileApi_getProfile @@ -3415,10 +3627,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_5 + tags: &ref_6 - profiles security: - - bearerAuth: [] + - bearer: [] - bearer: [] put: operationId: ProfileApi_setUserProfile @@ -3453,9 +3665,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_5 + tags: *ref_6 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /profiles/push/{username}: put: @@ -3495,9 +3707,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_5 + tags: *ref_6 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /profiles/{username}/balance: get: @@ -3530,9 +3742,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_5 + tags: *ref_6 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /profiles/restore/{username}: put: @@ -3570,9 +3782,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_5 + tags: *ref_6 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /profiles/restore/topics/{username}: put: @@ -3610,9 +3822,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_5 + tags: *ref_6 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /profiles/did-document/validate: post: @@ -3644,9 +3856,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_5 + tags: *ref_6 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /profiles/did-keys/validate: post: @@ -3678,9 +3890,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_5 + tags: *ref_6 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /policies: get: @@ -3690,7 +3902,7 @@ paths: Returns all policies. Only users with the Standard Registry and Installer role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Return a list of all policies. parameters: - in: query @@ -3751,7 +3963,7 @@ paths: Creates a new policy. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Creates a new policy. requestBody: description: Object that contains policy configuration. @@ -3802,16 +4014,19 @@ paths: type: string id: type: string + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_6 + tags: &ref_7 - policies security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /policies/push/migrate-data: post: operationId: PolicyApi_migrateDataAsync @@ -3834,15 +4049,18 @@ paths: application/json: schema: type: object + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /policies/push: post: tags: @@ -3851,7 +4069,7 @@ paths: Creates a new policy. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Creates a new policy. requestBody: description: Object that contains policy configuration. @@ -3881,7 +4099,14 @@ paths: post: operationId: PolicyApi_updatePolicyAsync summary: '' - parameters: [] + parameters: + - name: policyId + required: true + in: path + description: Policy identifier + example: 652745597a7b53526de37c05 + schema: + type: string responses: '200': description: Successful operation. @@ -3889,25 +4114,34 @@ paths: application/json: schema: type: object + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] delete: operationId: PolicyApi_deletePolicyAsync - parameters: [] + parameters: + - name: policyId + required: true + in: path + description: Policy identifier + example: 652745597a7b53526de37c05 + schema: + type: string responses: - '202': - description: '' - tags: *ref_6 + '401': + description: Unauthorized + tags: *ref_7 security: - - bearerAuth: [] + - bearer: [] /policies/{policyId}: get: tags: @@ -3924,7 +4158,7 @@ paths: description: Selected policy ID. summary: Retrieves policy configuration. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -3971,7 +4205,7 @@ paths: schema: $ref: '#/components/schemas/PolicyConfig' security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -4017,7 +4251,7 @@ paths: type: string summary: Publishes the policy onto IPFS. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -4045,7 +4279,7 @@ paths: topic. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: >- Publishes the policy with the specified (internal) policy ID onto IPFS, sends a message featuring its IPFS CID into the corresponding Hedera @@ -4093,7 +4327,7 @@ paths: transaction. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Dry Run policy. parameters: - in: path @@ -4141,7 +4375,7 @@ paths: type: object properties: date: - type: date + type: object responses: '200': description: Policies. @@ -4151,16 +4385,19 @@ paths: type: array items: type: object + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] + - bearer: [] /policies/{policyId}/draft: put: tags: @@ -4169,7 +4406,7 @@ paths: Return policy to editing. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Return policy to editing. parameters: - in: path @@ -4203,7 +4440,7 @@ paths: Validates selected policy. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Validates policy. requestBody: description: Object that contains policy configuration. @@ -4234,7 +4471,14 @@ paths: operationId: PolicyApi_getPolicyNavigation summary: Returns a policy navigation. description: Returns a policy navigation. - parameters: [] + parameters: + - name: policyId + required: true + in: path + description: Policy identifier + example: 652745597a7b53526de37c05 + schema: + type: string responses: '200': description: Successful operation. @@ -4242,16 +4486,18 @@ paths: application/json: schema: type: object + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] /policies/{policyId}/groups: get: tags: @@ -4266,7 +4512,7 @@ paths: description: Selected policy ID. summary: Returns a list of groups the user is a member of. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -4324,7 +4570,7 @@ paths: uuid: type: string security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -4380,26 +4626,202 @@ paths: schema: {} responses: '200': - description: Documents. - headers: - X-Total-Count: - description: Total documents count. - content: - application/json: - schema: - type: array - items: - type: object + description: Documents. + headers: + X-Total-Count: + description: Total documents count. + schema: + type: integer + content: + application/json: + schema: + type: array + items: + type: object + '401': + description: Unauthorized + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + security: + - bearer: [] + /policies/{policyId}/data: + get: + operationId: PolicyApi_downloadPolicyData + summary: Get policy data. + description: >- + Get policy data. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy identifier. + schema: {} + responses: + '200': + description: Policy data. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + security: + - bearer: [] + - bearer: [] + - bearer: [] + /policies/data: + post: + operationId: PolicyApi_uploadPolicyData + summary: Upload policy data. + description: >- + Upload policy data. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Policy data file + content: + application/json: + schema: + type: string + format: binary + responses: + '200': + description: Uploaded policy. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + security: + - bearer: [] + - bearer: [] + - bearer: [] + /policies/{policyId}/tag-block-map: + get: + operationId: PolicyApi_getTagBlockMap + summary: Get policy tag block map. + description: >- + Get policy tag block map. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy identifier. + schema: {} + responses: + '200': + description: Policy tag block map. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + security: + - bearer: [] + - bearer: [] + - bearer: [] + /policies/{policyId}/virtual-keys: + get: + operationId: PolicyApi_downloadVirtualKeys + summary: Get policy virtual keys. + description: >- + Get policy virtual keys. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy identifier. + schema: {} + responses: + '200': + description: Policy virtual keys. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + security: + - bearer: [] + - bearer: [] + - bearer: [] + post: + operationId: PolicyApi_uploadVirtualKeys + summary: Upload policy virtual keys. + description: >- + Upload policy virtual keys. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy identifier. + schema: {} + requestBody: + required: true + description: Virtual keys file + content: + application/json: + schema: + type: string + format: binary + responses: + '200': + description: Operation completed. + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] + - bearer: [] /policies/{policyId}/blocks: get: tags: @@ -4416,7 +4838,7 @@ paths: description: Selected policy ID. summary: Retrieves data for the policy root block. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -4456,7 +4878,7 @@ paths: description: Selected block UUID. summary: Requests block data. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -4500,7 +4922,7 @@ paths: schema: type: object security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -4519,7 +4941,21 @@ paths: operationId: PolicyApi_setBlocksByTagName summary: Sends data to the specified block. description: Sends data to the specified block. - parameters: [] + parameters: + - name: tagName + required: true + in: path + description: Policy block tag + example: someTag + schema: + type: string + - name: policyId + required: true + in: path + description: Policy identifier + example: 652745597a7b53526de37c05 + schema: + type: string responses: '200': description: Successful operation. @@ -4527,23 +4963,38 @@ paths: application/json: schema: type: object + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] - - bearerAuth: [] + - bearer: [] get: operationId: PolicyApi_getBlocksByTagName summary: Requests block data. description: >- Requests block data by tag. Only users with a role that described in block are allowed to make the request. - parameters: [] + parameters: + - name: tagName + required: true + in: path + description: Policy block tag + example: someTag + schema: + type: string + - name: policyId + required: true + in: path + description: Policy identifier + example: 652745597a7b53526de37c05 + schema: + type: string responses: '200': description: Successful operation. @@ -4551,16 +5002,17 @@ paths: application/json: schema: type: object + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] - - bearerAuth: [] + - bearer: [] /policies/{policyId}/tag/{tagName}: get: operationId: PolicyApi_getBlockByTagName @@ -4568,7 +5020,21 @@ paths: description: >- Requests block data by tag. Only users with a role that described in block are allowed to make the request. - parameters: [] + parameters: + - name: tagName + required: true + in: path + description: Policy block tag + example: someTag + schema: + type: string + - name: policyId + required: true + in: path + description: Policy identifier + example: 652745597a7b53526de37c05 + schema: + type: string responses: '200': description: Successful operation. @@ -4576,24 +5042,41 @@ paths: application/json: schema: type: object + '401': + description: Unauthorized '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] - - bearerAuth: [] + - bearer: [] /policies/{policyId}/blocks/{uuid}/parents: get: operationId: PolicyApi_getBlockParents - parameters: [] + parameters: + - name: uuid + required: true + in: path + description: Block identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: policyId + required: true + in: path + description: Policy identifier + example: 652745597a7b53526de37c05 + schema: + type: string responses: - '200': - description: '' - tags: *ref_6 + '401': + description: Unauthorized + tags: *ref_7 + security: + - bearer: [] /policies/{policyId}/export/file: get: tags: @@ -4610,7 +5093,7 @@ paths: required: true description: Selected policy ID. security: - - bearerAuth: [] + - bearer: [] summary: >- Return policy and its artifacts in a zip file format for the specified policy. @@ -4647,7 +5130,7 @@ paths: required: true description: Selected policy ID. security: - - bearerAuth: [] + - bearer: [] summary: Return Heder message ID for the specified published policy. responses: '200': @@ -4701,9 +5184,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /policies/import/message: post: @@ -4724,7 +5207,7 @@ paths: summary: Example of a topic ID of policy version. value: 0.0.00000001 security: - - bearerAuth: [] + - bearer: [] summary: Imports new policy from IPFS. requestBody: description: >- @@ -4766,7 +5249,7 @@ paths: DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: >- Imports new policy and all associated artifacts from IPFS into the local DB. @@ -4808,7 +5291,7 @@ paths: users with the Standard Registry role are allowed to make the request. summary: Policy preview from IPFS. security: - - bearerAuth: [] + - bearer: [] requestBody: description: >- Object that contains the identifier of the Hedera message which @@ -4846,7 +5329,7 @@ paths: Previews the policy from IPFS without loading it into the local DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Previews the policy from IPFS without loading it into the local DB. requestBody: description: >- @@ -4896,7 +5379,7 @@ paths: summary: Example of a topic ID of policy version. value: 0.0.00000001 security: - - bearerAuth: [] + - bearer: [] summary: Imports new policy from a zip file. requestBody: description: >- @@ -4927,6 +5410,56 @@ paths: application/json: schema: $ref: '#/components/schemas/Error' + /policies/import/file-metadata: + post: + operationId: PolicyApi_importPolicyFromFileWithMetadata + summary: Imports new policy from a zip file with metadata. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: versionOfTopicId + required: false + in: query + description: Topic Id + schema: + type: string + requestBody: + required: true + description: Form data with policy file and metadata. + content: + multipart/form-data: + schema: + type: object + properties: + policyFile: + type: string + format: binary + metadata: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + security: + - bearer: [] + - bearer: [] /policies/push/import/file: post: tags: @@ -4936,7 +5469,7 @@ paths: VCs, from the provided zip file into the local DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: >- Imports new policy and all associated artifacts, such as schemas and VCs, from the provided zip file into the local DB. @@ -4967,6 +5500,56 @@ paths: application/json: schema: $ref: '#/components/schemas/Error' + /policies/push/import/file-metadata: + post: + operationId: PolicyApi_importPolicyFromFileWithMetadataAsync + summary: Imports new policy from a zip file with metadata. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: versionOfTopicId + required: false + in: query + description: Topic Id + schema: + type: string + requestBody: + required: true + description: Form data with policy file and metadata. + content: + multipart/form-data: + schema: + type: object + properties: + policyFile: + type: string + format: binary + metadata: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + security: + - bearer: [] + - bearer: [] /policies/import/file/preview: post: tags: @@ -4977,7 +5560,7 @@ paths: request. summary: Policy preview from a zip file. security: - - bearerAuth: [] + - bearer: [] requestBody: description: >- A zip file that contains the policy and associated schemas and VCs to @@ -5044,9 +5627,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /policies/push/import/xlsx: post: @@ -5087,9 +5670,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /policies/import/xlsx/preview: post: @@ -5124,18 +5707,20 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /policies/blocks/about: get: operationId: PolicyApi_getBlockAbout parameters: [] responses: - '200': - description: '' - tags: *ref_6 + '401': + description: Unauthorized + tags: *ref_7 + security: + - bearer: [] /policies/{policyId}/dry-run/users: get: tags: @@ -5144,7 +5729,7 @@ paths: Returns all virtual users. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Returns all virtual users. parameters: - in: path @@ -5185,7 +5770,7 @@ paths: Create a new virtual account. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Create a new virtual account. parameters: - in: path @@ -5226,7 +5811,7 @@ paths: Logs virtual user into the system. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Logs virtual user into the system. parameters: - in: path @@ -5277,7 +5862,7 @@ paths: Restarts the execution of the policy. Clear data in database. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Restarts the execution of the policy. parameters: - in: path @@ -5307,7 +5892,7 @@ paths: Returns lists of virtual transactions. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Returns lists of virtual transactions. parameters: - in: path @@ -5350,7 +5935,7 @@ paths: Returns lists of virtual artifacts. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Returns lists of virtual artifacts. parameters: - in: path @@ -5393,7 +5978,7 @@ paths: Returns lists of virtual artifacts. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Returns lists of virtual artifacts. parameters: - in: path @@ -5436,7 +6021,7 @@ paths: Creates a link between the current policy and the main policy. Or creates a group making the current policy the main one. security: - - bearerAuth: [] + - bearer: [] summary: Creates Multi policy config. parameters: - in: path @@ -5482,7 +6067,7 @@ paths: - policies description: Requests Multi policy config. security: - - bearerAuth: [] + - bearer: [] summary: Requests Multi policy config. parameters: - in: path @@ -5529,7 +6114,7 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 /policies/methodologies/search: post: operationId: PolicyApi_getPoliciesByCategory @@ -5563,14 +6148,14 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_6 + tags: *ref_7 /schema/{schemaId}: get: tags: - schema description: Returns schema by schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Returns schema by schema ID. parameters: - in: path @@ -5627,10 +6212,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_7 + tags: &ref_8 - schema security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /schema/{schemaId}/tree: get: operationId: SingleSchemaApi_getSchemaTree @@ -5669,16 +6255,17 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_7 + tags: *ref_8 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /schemas: get: tags: - schemas description: Returns all schemas. security: - - bearerAuth: [] + - bearer: [] summary: Returns all schemas. parameters: - in: query @@ -5744,7 +6331,7 @@ paths: summary: Example of a Topic ID value: 0.0.00000001 security: - - bearerAuth: [] + - bearer: [] summary: Create new schema. requestBody: description: Object that contains a valid schema. @@ -5771,7 +6358,7 @@ paths: - schemas description: Returns all schemas by topicId. security: - - bearerAuth: [] + - bearer: [] summary: Returns all schemas by topicId. parameters: - in: path @@ -5857,10 +6444,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_8 + tags: &ref_9 - schemas security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /schemas/list/all: get: operationId: SchemaApi_getAll @@ -5888,9 +6476,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_8 + tags: *ref_9 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /schemas/list/sub: get: operationId: SchemaApi_getSub @@ -5930,9 +6519,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_8 + tags: *ref_9 security: - - bearerAuth: [] + - bearer: [] + - bearer: [] /schemas/push/copy: post: operationId: SchemaApi_copySchemaAsync @@ -5965,10 +6555,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_8 + tags: *ref_9 security: - bearer: [] - - bearerAuth: [] + - bearer: [] /schemas/push/{topicId}: post: tags: @@ -5977,7 +6567,7 @@ paths: Creates new schema. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Create new schema. parameters: - in: path @@ -6029,7 +6619,7 @@ paths: required: true description: Schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Updates the schema. requestBody: description: Object that contains a valid schema. @@ -6071,7 +6661,7 @@ paths: required: true description: Schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Deletes the schema. responses: '200': @@ -6109,7 +6699,7 @@ paths: required: true description: Schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Publishes the schema. requestBody: description: Object that contains policy version. @@ -6150,7 +6740,7 @@ paths: Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: >- Publishes the schema with the provided (internal) schema ID onto IPFS, sends a message featuring IPFS CID into the corresponding Hedera topic. @@ -6196,7 +6786,7 @@ paths: Previews the schema from IPFS without loading it into the local DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Schema preview from IPFS. requestBody: description: >- @@ -6237,7 +6827,7 @@ paths: Previews the schema from IPFS without loading it into the local DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Schema preview from IPFS. requestBody: description: >- @@ -6276,7 +6866,7 @@ paths: Previews the schema from a zip file. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Schema preview from a zip file. requestBody: description: A zip file containing the schema to be viewed. @@ -6324,7 +6914,7 @@ paths: summary: Example of a Topic ID value: 0.0.00000001 security: - - bearerAuth: [] + - bearer: [] summary: Imports new schema from IPFS. requestBody: description: >- @@ -6365,7 +6955,7 @@ paths: Imports new schema from IPFS into the local DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Imports new schema from IPFS. requestBody: description: >- @@ -6426,7 +7016,7 @@ paths: summary: Example of a Topic ID value: 0.0.00000001 security: - - bearerAuth: [] + - bearer: [] summary: Imports new schema from a zip file. requestBody: description: A zip file containing schema to be imported. @@ -6463,7 +7053,7 @@ paths: Imports new schema from a zip file into the local DB. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Imports new schema from a zip file. requestBody: description: A zip file containing schema to be imported. @@ -6510,7 +7100,7 @@ paths: contain IPFS CIDs of these schema files. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: List Hedera message IDs of published schemas. parameters: - in: path @@ -6544,7 +7134,7 @@ paths: Returns schema files for the schemas. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Return zip file with schemas. parameters: - in: path @@ -6581,7 +7171,7 @@ paths: required: true description: Username. security: - - bearerAuth: [] + - bearer: [] summary: Creates new system schema. requestBody: description: Object that contains a valid schema. @@ -6610,7 +7200,7 @@ paths: Returns all system schemas by username. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Returns all system schemas by username. parameters: - in: path @@ -6678,7 +7268,7 @@ paths: required: true description: Schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Updates the schema. requestBody: description: Object that contains a valid schema. @@ -6720,7 +7310,7 @@ paths: required: true description: Schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Deletes the schema. responses: '200': @@ -6757,7 +7347,7 @@ paths: required: true description: Schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Publishes the schema. requestBody: description: Object that contains policy version. @@ -6808,7 +7398,7 @@ paths: required: true description: schema type. security: - - bearerAuth: [] + - bearer: [] summary: Returns schema by schema type. responses: '200': @@ -6859,9 +7449,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_8 + tags: *ref_9 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /schemas/{topicId}/import/xlsx: post: @@ -6901,9 +7491,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_8 + tags: *ref_9 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /schemas/push/{topicId}/import/xlsx: post: @@ -6943,9 +7533,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_8 + tags: *ref_9 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /schemas/import/xlsx/preview: post: @@ -6979,9 +7569,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_8 + tags: *ref_9 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /schemas/export/template: get: @@ -7009,9 +7599,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_8 + tags: *ref_9 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /settings: get: @@ -7021,7 +7611,7 @@ paths: Returns current settings. For users with the Standard Registry role only. security: - - bearerAuth: [] + - bearer: [] summary: Returns current settings. responses: '200': @@ -7045,7 +7635,7 @@ paths: - settings description: Set settings. For users with the Standard Registry role only. security: - - bearerAuth: [] + - bearer: [] summary: Set settings. responses: '201': @@ -7066,7 +7656,7 @@ paths: - settings description: Returns current environment name. security: - - bearerAuth: [] + - bearer: [] summary: Returns current environment name. responses: '200': @@ -7087,26 +7677,30 @@ paths: operationId: SettingsApi_getAbout parameters: [] responses: - '200': - description: '' + '401': + description: Unauthorized tags: - settings + security: + - bearer: [] /tags: post: operationId: TagsApi_setTags parameters: [] responses: - '201': - description: '' + '401': + description: Unauthorized tags: - tags + security: + - bearer: [] /tags/search: post: tags: - tags description: Search tags. security: - - bearerAuth: [] + - bearer: [] requestBody: description: Object that contains filters. required: true @@ -7188,7 +7782,7 @@ paths: - tags description: Delete tag. security: - - bearerAuth: [] + - bearer: [] summary: Delete tag. parameters: - in: path @@ -7221,7 +7815,7 @@ paths: - tags description: synchronization. security: - - bearerAuth: [] + - bearer: [] requestBody: description: Object that contains filters. required: true @@ -7270,7 +7864,7 @@ paths: - tags description: Returns all schema. security: - - bearerAuth: [] + - bearer: [] summary: Returns all schemas. parameters: - in: query @@ -7324,7 +7918,7 @@ paths: Creates new schema. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Creates new schema. requestBody: description: Object that contains a valid schema. @@ -7358,7 +7952,7 @@ paths: Deletes the schema with the provided schema ID. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Delete the schema. parameters: - in: path @@ -7398,7 +7992,7 @@ paths: required: true description: Schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Updates the schema. requestBody: description: Object that contains a valid schema. @@ -7443,7 +8037,7 @@ paths: required: true description: Schema ID. security: - - bearerAuth: [] + - bearer: [] summary: Publishes the schema. responses: '200': @@ -7470,7 +8064,7 @@ paths: - tags description: Return a list of all published schemas. security: - - bearerAuth: [] + - bearer: [] summary: Return a list of all published schemas. responses: '200': @@ -7497,7 +8091,7 @@ paths: - tasks description: Returns task statuses by Id. security: - - bearerAuth: [] + - bearer: [] summary: Returns task statuses. parameters: - in: path @@ -7533,7 +8127,7 @@ paths: as the KYC, Freeze, and Association statuses. Not allowed for the Auditor role. security: - - bearerAuth: [] + - bearer: [] summary: Return a list of tokens. responses: '200': @@ -7568,7 +8162,7 @@ paths: Creates a new token. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Creates a new token. requestBody: description: Object that contains token information. @@ -7617,7 +8211,7 @@ paths: Creates a new token. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Creates a new token. requestBody: description: Object that contains token information. @@ -7646,12 +8240,21 @@ paths: /tokens/push/{tokenId}: delete: operationId: TokensApi_deleteTokenAsync - parameters: [] + parameters: + - name: tokenId + required: true + in: path + description: Token identifier + example: 652745597a7b53526de37c05 + schema: + type: string responses: - '202': - description: '' - tags: &ref_9 + '401': + description: Unauthorized + tags: &ref_10 - tokens + security: + - bearer: [] /tokens/{tokenId}/associate: put: tags: @@ -7667,7 +8270,7 @@ paths: required: true description: Token ID. security: - - bearerAuth: [] + - bearer: [] summary: Associates the user with the provided Hedera token. responses: '200': @@ -7690,7 +8293,7 @@ paths: Associates the user with the provided Hedera token. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Associates the user with the provided Hedera token. parameters: - in: path @@ -7731,7 +8334,7 @@ paths: required: true description: Token ID. security: - - bearerAuth: [] + - bearer: [] summary: Associate the user with the provided Hedera token. responses: '202': @@ -7754,7 +8357,7 @@ paths: Disassociates the user with the provided Hedera token. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Disassociates the user with the provided Hedera token. parameters: - in: path @@ -7801,7 +8404,7 @@ paths: required: true description: Username. security: - - bearerAuth: [] + - bearer: [] summary: Sets the KYC flag for the user. responses: '200': @@ -7834,7 +8437,7 @@ paths: Sets the KYC flag for the user. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Sets the KYC flag for the user. parameters: - in: path @@ -7887,7 +8490,7 @@ paths: required: true description: Username. security: - - bearerAuth: [] + - bearer: [] summary: Unsets the KYC flag for the user. responses: '200': @@ -7920,7 +8523,7 @@ paths: Unsets the KYC flag for the user. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Unsets the KYC flag for the user. parameters: - in: path @@ -7973,7 +8576,7 @@ paths: required: true description: Username. security: - - bearerAuth: [] + - bearer: [] summary: Freeze transfers of the specified token for the user. responses: '200': @@ -8019,7 +8622,7 @@ paths: required: true description: Username. security: - - bearerAuth: [] + - bearer: [] summary: Unfreezes transfers of the specified token for the user. responses: '200': @@ -8052,7 +8655,7 @@ paths: Freezes transfers of the specified token for the user. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Freeze transfers of the specified token for the user. parameters: - in: path @@ -8092,7 +8695,7 @@ paths: Unfreezes transfers of the specified token for the user. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Unfreezes transfers of the specified token for the user. parameters: - in: path @@ -8132,7 +8735,7 @@ paths: Returns user information for the selected token. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] parameters: - in: path name: tokenId @@ -8201,16 +8804,17 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_9 + tags: *ref_10 security: - bearer: [] + - bearer: [] /themes: get: tags: - themes description: Returns all themes. security: - - bearerAuth: [] + - bearer: [] summary: Return a list of all themes. responses: '200': @@ -8236,7 +8840,7 @@ paths: - themes description: Creates a new theme. security: - - bearerAuth: [] + - bearer: [] summary: Creates a new theme. requestBody: description: Object that contains theme configuration. @@ -8279,7 +8883,7 @@ paths: schema: $ref: '#/components/schemas/Theme' security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -8309,7 +8913,7 @@ paths: required: true description: Theme ID. security: - - bearerAuth: [] + - bearer: [] summary: Deletes the theme. responses: '200': @@ -8334,7 +8938,7 @@ paths: - themes description: Imports new theme from the provided zip file into the local DB. security: - - bearerAuth: [] + - bearer: [] summary: Imports new theme from a zip file. requestBody: description: A zip file that contains the theme to be imported. @@ -8374,7 +8978,7 @@ paths: required: true description: Selected theme ID. security: - - bearerAuth: [] + - bearer: [] summary: Returns a zip file containing the theme. responses: '200': @@ -8397,7 +9001,7 @@ paths: Requests all VP documents. Only users with the Auditor role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Returns a list of all VP documents. parameters: - in: query @@ -8469,7 +9073,7 @@ paths: required: true description: Hash or ID of a VP document. security: - - bearerAuth: [] + - bearer: [] summary: Returns a trustchain for a VP document. responses: '200': @@ -8496,7 +9100,7 @@ paths: Creates a new policy by wizard. Only users with the Standard Registry role are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Creates a new policy. requestBody: description: Object that contains wizard configuration. @@ -8633,6 +9237,8 @@ paths: application/json: schema: type: boolean + '401': + description: Unauthorized '500': description: Internal server error. content: @@ -8641,6 +9247,8 @@ paths: $ref: '#/components/schemas/InternalServerErrorDTO' tags: - wizard + security: + - bearer: [] /wizard/{policyId}/config: post: tags: @@ -8656,7 +9264,7 @@ paths: required: true description: Policy identifier. security: - - bearerAuth: [] + - bearer: [] summary: Get policy config. requestBody: description: Object that contains wizard configuration. @@ -8694,7 +9302,7 @@ paths: responses: '401': description: Unauthorized - tags: &ref_10 + tags: &ref_11 - branding security: - bearer: [] @@ -8704,7 +9312,7 @@ paths: responses: '200': description: '' - tags: *ref_10 + tags: *ref_11 /suggestions: post: operationId: SuggestionsApi_policySuggestions @@ -8738,11 +9346,12 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_11 + tags: &ref_12 - suggestions security: - bearer: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] /suggestions/config: post: operationId: SuggestionsApi_setPolicySuggestionsConfig @@ -8772,10 +9381,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_11 + tags: *ref_12 security: - bearer: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] get: operationId: SuggestionsApi_getPolicySuggestionsConfig summary: Get suggestions config @@ -8798,10 +9408,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_11 + tags: *ref_12 security: - bearer: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] /notifications: get: operationId: NotificationsApi_getAllNotifications @@ -8814,6 +9425,8 @@ paths: headers: X-Total-Count: description: Count of notifications + schema: + type: integer content: application/json: schema: @@ -8828,11 +9441,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_12 + tags: &ref_13 - notifications security: - bearer: [] - - bearerAuth: [] + - bearer: [] /notifications/new: get: operationId: NotificationsApi_getNewNotifications @@ -8856,10 +9469,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_12 + tags: *ref_13 security: - bearer: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] /notifications/progresses: get: operationId: NotificationsApi_getProgresses @@ -8883,10 +9497,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_12 + tags: *ref_13 security: - bearer: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] /notifications/read/all: post: operationId: NotificationsApi_readAll @@ -8910,10 +9525,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_12 + tags: *ref_13 security: - bearer: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] /notifications/delete/{notificationId}: delete: operationId: NotificationsApi_delete @@ -8940,10 +9556,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_12 + tags: *ref_13 security: - bearer: [] - - bearerAuth: [] + - bearer: [] + - bearer: [] /projects/search: post: operationId: ProjectsAPI_projectSearch @@ -8977,11 +9594,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_13 + tags: &ref_14 - projects /projects/compare/documents: post: - operationId: ProjectsAPI_compareDocuments + operationId: ProjectsAPI_compareDocumentsV2 summary: Compare documents. description: Compare documents. parameters: [] @@ -9008,14 +9625,14 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/CompareDocumentsDTO' + $ref: '#/components/schemas/CompareDocumentsDTOV2' '500': description: Internal server error. content: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_13 + tags: *ref_14 /projects/properties: get: operationId: ProjectsAPI_getPolicyProperties @@ -9037,7 +9654,7 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_13 + tags: *ref_14 /record/{policyId}/status: get: operationId: RecordApi_getRecordStatus @@ -9069,10 +9686,10 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_14 + tags: &ref_15 - record security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/recording/start: post: @@ -9112,9 +9729,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/recording/stop: post: @@ -9155,9 +9772,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/recording/actions: get: @@ -9192,9 +9809,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/running/start: post: @@ -9234,9 +9851,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/running/stop: post: @@ -9276,9 +9893,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/running/results: get: @@ -9311,9 +9928,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/running/details: get: @@ -9346,9 +9963,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/running/fast-forward: post: @@ -9388,9 +10005,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/running/retry: post: @@ -9430,9 +10047,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /record/{policyId}/running/skip: post: @@ -9472,9 +10089,9 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: *ref_14 + tags: *ref_15 security: - - bearerAuth: [] + - bearer: [] - bearer: [] /ai-suggestions/ask: get: @@ -9484,8 +10101,9 @@ paths: parameters: - name: q required: true - in: path + in: query description: The question of choosing a methodology + example: Find me large scale projects schema: type: string responses: @@ -9501,7 +10119,7 @@ paths: application/json: schema: $ref: '#/components/schemas/InternalServerErrorDTO' - tags: &ref_15 + tags: &ref_16 - ai-suggestions /ai-suggestions/rebuild-vector: put: @@ -9512,7 +10130,7 @@ paths: responses: '200': description: '' - tags: *ref_15 + tags: *ref_16 /schemas/type/{type}: get: tags: @@ -9526,7 +10144,7 @@ paths: required: true description: JSON type. security: - - bearerAuth: [] + - bearer: [] summary: Returns schema by type. responses: '200': @@ -9567,7 +10185,7 @@ paths: description: Tag from the selected policy. summary: Requests block ID from a policy by tag. security: - - bearerAuth: [] + - bearer: [] responses: '200': description: Successful operation. @@ -9594,7 +10212,7 @@ paths: - policies description: Sends data to the specified block. security: - - bearerAuth: [] + - bearer: [] summary: Sends data to the specified block. parameters: - in: path @@ -9640,7 +10258,7 @@ paths: Requests block data by tag. Only users with a role that described in block are allowed to make the request. security: - - bearerAuth: [] + - bearer: [] summary: Requests block data. parameters: - in: path @@ -9687,7 +10305,7 @@ paths: type: string format: binary security: - - bearerAuth: [] + - bearer: [] responses: '201': description: Created. @@ -9710,7 +10328,7 @@ paths: - artifacts description: Upload artifact. For users with the Standard Registry role only. security: - - bearerAuth: [] + - bearer: [] requestBody: content: multipart/form-data: @@ -9756,7 +10374,7 @@ paths: - artifacts description: Returns all artifacts. security: - - bearerAuth: [] + - bearer: [] summary: Returns all artifacts. parameters: - in: query @@ -9815,7 +10433,7 @@ paths: - artifacts description: Upload artifact. For users with the Standard Registry role only. security: - - bearerAuth: [] + - bearer: [] requestBody: content: multipart/form-data: @@ -9861,7 +10479,7 @@ paths: - artifacts description: Delete artifact. security: - - bearerAuth: [] + - bearer: [] summary: Delete artifact. parameters: - in: path @@ -9893,7 +10511,7 @@ paths: - tags description: Creates new tag. security: - - bearerAuth: [] + - bearer: [] summary: Creates new tag. requestBody: description: Object that contains tag information. @@ -9933,7 +10551,7 @@ info: the heart of the Guardian solution is a sophisticated Policy Workflow Engine (PWE) that enables applications to offer a requirements-based tokenization implementation. - version: 2.21.1 + version: 2.24.1 contact: name: API developer url: https://envisionblockchain.com @@ -9947,7 +10565,7 @@ servers: description: version 1.0 components: securitySchemes: - bearerAuth: + bearer: type: http scheme: bearer bearerFormat: JWT @@ -10834,6 +11452,18 @@ components: type: object roles: type: object + blocks: + type: object + tokens: + type: object + migrateState: + type: boolean + migrateRetirePools: + type: boolean + editedVCs: + type: object + retireContractId: + type: string required: - policies - vcs @@ -10841,6 +11471,12 @@ components: - schemas - groups - roles + - blocks + - tokens + - migrateState + - migrateRetirePools + - editedVCs + - retireContractId PolicyCategoryDTO: type: object properties: @@ -11088,6 +11724,16 @@ components: - title - companyName - sectoralScope + CompareDocumentsDTOV2: + type: object + properties: + projects: + $ref: '#/components/schemas/CompareDocumentsDTO' + presentations: + $ref: '#/components/schemas/CompareDocumentsDTO' + required: + - projects + - presentations PropertiesDTO: type: object properties: @@ -11200,6 +11846,27 @@ components: - right - total - documents + RegisteredUsersDTO: + type: object + properties: + username: + type: string + did: + type: string + parent: + type: string + role: + type: string + policyRoles: + type: array + items: + type: string + required: + - username + - did + - parent + - role + - policyRoles ToolDTO: type: object properties: @@ -11240,27 +11907,6 @@ components: - messageId - codeVersion - createDate - RegisteredUsersDTO: - type: object - properties: - username: - type: string - did: - type: string - parent: - type: string - role: - type: string - policyRoles: - type: array - items: - type: string - required: - - username - - did - - parent - - role - - policyRoles Credentials: type: object required: diff --git a/docs/.gitbook/assets/swagger (4).yaml b/docs/.gitbook/assets/swagger (4).yaml new file mode 100644 index 0000000000..954c5cfe6e --- /dev/null +++ b/docs/.gitbook/assets/swagger (4).yaml @@ -0,0 +1,14262 @@ +openapi: 3.0.0 +paths: + /accounts/session: + get: + operationId: AccountApi_getSession + summary: Returns current session of the user. + description: Returns current user session. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsSessionResponseDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_0 + - accounts + security: + - bearer: [] + /accounts/register: + post: + operationId: AccountApi_register + summary: Registers a new user account. + description: Object that contain username, password and role (optional) fields. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RegisterUserDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsResponseDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + /accounts/login: + post: + operationId: AccountApi_login + summary: Logs user into the system. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LoginUserDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsSessionResponseDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + /accounts/access-token: + post: + operationId: AccountApi_getAccessToken + summary: Returns access token. + description: Returns access token. + parameters: [] + responses: + '200': + description: Successful operation. + tags: *ref_0 + /accounts: + get: + operationId: AccountApi_getAllAccounts + summary: Returns a list of users, excluding Standard Registry and Auditors. + description: >- + Returns all users except those with roles Standard Registry and Auditor. + Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsResponseDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + security: + - bearer: [] + /accounts/standard-registries: + get: + operationId: AccountApi_getStandardRegistries + summary: Returns all Standard Registries. + description: Returns all Standard Registries. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/AccountsResponseDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + security: + - bearer: [] + /accounts/standard-registries/aggregated: + get: + operationId: AccountApi_getAggregatedStandardRegistries + summary: Returns all Standard Registries aggregated with polices and vcDocuments. + description: Returns all Standard Registries aggregated with polices and vcDocuments + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AggregatedDTOItem' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + security: + - bearer: [] + /accounts/balance: + get: + operationId: AccountApi_getBalance + summary: Returns user's Hedera account balance. + description: Requests current Hedera account balance. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BalanceResponseDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_0 + security: + - bearer: [] + /analytics/search/policies: + post: + operationId: AnalyticsApi_searchPolicies + summary: Search policies. + description: >- + Search policies. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterSearchPoliciesDTO' + examples: + Filter: + value: + policyId: '000000000000000000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SearchPoliciesDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_1 + - analytics + security: + - bearer: [] + /analytics/compare/policies: + post: + operationId: AnalyticsApi_comparePolicies + summary: Compare policies. + description: >- + Compare policies. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterPoliciesDTO' + examples: + Filter1: + value: + policyId1: '000000000000000000000001' + policyId2: '000000000000000000000001' + eventsLvl: '0' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + Filter2: + value: + policyIds: + - '000000000000000000000001' + - '000000000000000000000001' + eventsLvl: '0' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ComparePoliciesDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/modules: + post: + operationId: AnalyticsApi_compareModules + summary: Compare modules. + description: >- + Compare modules. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterModulesDTO' + examples: + Filter: + value: + moduleId1: '000000000000000000000001' + moduleId2: '000000000000000000000001' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareModulesDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/schemas: + post: + operationId: AnalyticsApi_compareSchemas + summary: Compare schemas. + description: >- + Compare schemas. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterSchemasDTO' + examples: + Filter: + value: + schemaId1: '000000000000000000000001' + schemaId2: '000000000000000000000001' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareSchemasDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/documents: + post: + operationId: AnalyticsApi_compareDocuments + summary: Compare documents. + description: >- + Compare documents. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterDocumentsDTO' + examples: + Filter1: + value: + documentId1: '000000000000000000000001' + documentId2: '000000000000000000000001' + Filter2: + value: + documentIds: + - '000000000000000000000001' + - '000000000000000000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareDocumentsDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/tools: + post: + operationId: AnalyticsApi_compareTools + summary: Compare tools. + description: >- + Compare tools. Only users with the Standard Registry role are allowed to + make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterToolsDTO' + examples: + Filter1: + value: + toolId1: '000000000000000000000001' + toolId2: '000000000000000000000001' + Filter2: + value: + toolIds: + - '000000000000000000000001' + - '000000000000000000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareToolsDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/policies/export: + post: + operationId: AnalyticsApi_comparePoliciesExport + summary: Compare policies. + description: >- + Compare policies. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: type + required: true + in: query + description: File type + example: csv + schema: + type: string + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterPoliciesDTO' + examples: + Filter1: + value: + policyId1: '000000000000000000000001' + policyId2: '000000000000000000000001' + eventsLvl: '0' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + Filter2: + value: + policyIds: + - '000000000000000000000001' + - '000000000000000000000001' + eventsLvl: '0' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/modules/export: + post: + operationId: AnalyticsApi_compareModulesExport + summary: Compare modules. + description: >- + Compare modules. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: type + required: true + in: query + description: File type + example: csv + schema: + type: string + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterModulesDTO' + examples: + Filter: + value: + moduleId1: '000000000000000000000001' + moduleId2: '000000000000000000000001' + propLvl: '0' + childrenLvl: '0' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/schemas/export: + post: + operationId: AnalyticsApi_compareSchemasExport + summary: Compare schemas. + description: >- + Compare schemas. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: type + required: true + in: query + description: File type + example: csv + schema: + type: string + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterSchemasDTO' + examples: + Filter: + value: + schemaId1: '000000000000000000000001' + schemaId2: '000000000000000000000001' + idLvl: '0' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/documents/export: + post: + operationId: AnalyticsApi_compareDocumentsExport + summary: Compare documents. + description: >- + Compare documents. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: type + required: true + in: query + description: File type + example: csv + schema: + type: string + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterDocumentsDTO' + examples: + Filter1: + value: + documentId1: '000000000000000000000001' + documentId2: '000000000000000000000001' + Filter2: + value: + documentIds: + - '000000000000000000000001' + - '000000000000000000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/compare/tools/export: + post: + operationId: AnalyticsApi_compareToolsExport + summary: Compare tools. + description: >- + Compare tools. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: type + required: true + in: query + description: File type + example: csv + schema: + type: string + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterToolsDTO' + examples: + Filter1: + value: + toolId1: '000000000000000000000001' + toolId2: '000000000000000000000001' + Filter2: + value: + toolIds: + - '000000000000000000000001' + - '000000000000000000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /analytics/search/blocks: + post: + operationId: AnalyticsApi_searchBlocks + summary: Search same blocks. + description: >- + Search same blocks. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterSearchBlocksDTO' + examples: + Filter: + value: + uuid: '' + config: {} + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SearchBlocksDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_1 + security: + - bearer: [] + /artifacts: + get: + operationId: ArtifactApi_getArtifacts + summary: Returns all artifacts. + description: Returns all artifacts. + parameters: + - name: id + required: false + in: query + description: Artifact identifier + example: '000000000000000000000001' + schema: + type: string + - name: type + required: false + in: query + description: Tool|Policy + example: policy + schema: + enum: + - tool + - policy + type: string + - name: policyId + required: false + in: query + description: Policy identifier + example: '000000000000000000000001' + schema: + type: string + - name: toolId + required: false + in: query + description: Tool identifier + example: '000000000000000000000001' + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ArtifactDTOItem' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_2 + - artifacts + security: + - bearer: [] + /artifacts/{parentId}: + post: + operationId: ArtifactApi_uploadArtifacts + summary: Upload artifact. + description: Upload artifact. For users with the Standard Registry role only. + parameters: + - name: parentId + required: true + in: path + description: Parent ID + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Form data with artifacts. + content: + multipart/form-data: + schema: + type: array + items: + type: object + properties: + artifacts: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ArtifactDTOItem' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /artifacts/{artifactId}: + delete: + operationId: ArtifactApi_deleteArtifact + summary: Delete artifact. + description: Delete artifact. + parameters: + - name: artifactId + required: true + in: path + description: Artifact ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_2 + security: + - bearer: [] + /contracts: + get: + operationId: ContractsApi_getContracts + summary: Return a list of all contracts. + description: Returns all contracts. + parameters: + - name: type + required: false + in: query + description: Contract type + example: RETIRE + schema: + enum: + - WIPE + - RETIRE + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Contracts. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ContractDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_3 + - contracts + security: + - bearer: [] + post: + operationId: ContractsApi_createContract + summary: Create contract. + description: >- + Create smart-contract. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ContractConfigDTO' + responses: + '201': + description: Created contract. + content: + application/json: + schema: + $ref: '#/components/schemas/ContractDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/import: + post: + operationId: ContractsApi_importContract + summary: Import contract. + description: >- + Import smart-contract. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + contractId: + type: string + description: Hedera Identifier + example: 0.0.1 + description: + type: string + required: + - contractId + responses: + '200': + description: Imported contract. + content: + application/json: + schema: + $ref: '#/components/schemas/ContractDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/{contractId}/permissions: + get: + operationId: ContractsApi_contractPermissions + summary: Get contract permissions. + description: >- + Get smart-contract permissions. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Contract permissions. + content: + application/json: + schema: + type: number + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/{contractId}: + delete: + operationId: ContractsApi_removeContract + summary: Remove contract. + description: >- + Remove smart-contract. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/requests: + get: + operationId: ContractsApi_getWipeRequests + summary: Return a list of all wipe requests. + description: >- + Returns all wipe requests. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: false + in: query + description: Contract identifier + example: 0.0.1 + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/WiperRequestDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/{contractId}/requests/enable: + post: + operationId: ContractsApi_enableWipeRequests + summary: Enable wipe requests. + description: >- + Enable wipe contract requests. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/{contractId}/requests/disable: + post: + operationId: ContractsApi_disableWipeRequests + summary: Disable wipe requests. + description: >- + Disable wipe contract requests. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/requests/{requestId}/approve: + post: + operationId: ContractsApi_approveWipeRequest + summary: Approve wipe request. + description: >- + Approve wipe contract request. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: requestId + required: true + in: path + description: Request identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/requests/{requestId}/reject: + delete: + operationId: ContractsApi_rejectWipeRequest + summary: Reject wipe request. + description: >- + Reject wipe contract request. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: requestId + required: true + in: path + description: Request identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: ban + required: false + in: query + description: Reject and ban + example: true + schema: + type: boolean + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/{contractId}/requests: + delete: + operationId: ContractsApi_clearWipeRequests + summary: Clear wipe requests. + description: >- + Clear wipe contract requests. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/{contractId}/admin/{hederaId}: + post: + operationId: ContractsApi_wipeAddAdmin + summary: Add wipe admin. + description: >- + Add wipe contract admin. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + delete: + operationId: ContractsApi_wipeRemoveAdmin + summary: Remove wipe admin. + description: >- + Remove wipe contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/{contractId}/manager/{hederaId}: + post: + operationId: ContractsApi_wipeAddManager + summary: Add wipe manager. + description: >- + Add wipe contract manager. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + delete: + operationId: ContractsApi_wipeRemoveManager + summary: Remove wipe manager. + description: >- + Remove wipe contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/wipe/{contractId}/wiper/{hederaId}: + post: + operationId: ContractsApi_wipeAddWiper + summary: Add wipe wiper. + description: >- + Add wipe contract wiper. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + delete: + operationId: ContractsApi_wipeRemoveWiper + summary: Remove wipe wiper. + description: >- + Remove wipe contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/{contractId}/pools/sync: + post: + operationId: ContractsApi_retireSyncPools + summary: Sync retire pools. + description: >- + Sync retire contract pools. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Sync date. + content: + application/json: + schema: + $ref: '#/components/schemas/Date' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/requests: + get: + operationId: ContractsApi_getRetireRequests + summary: Return a list of all retire requests. + description: Returns all retire requests. + parameters: + - name: contractId + required: false + in: query + description: Contract identifier + example: 0.0.1 + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RetireRequestDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/pools: + get: + operationId: ContractsApi_getRetirePools + summary: Return a list of all retire pools. + description: Returns all retire pools. + parameters: + - name: contractId + required: false + in: query + description: Contract identifier + example: 0.0.1 + schema: + type: string + - name: tokens + required: false + in: query + description: Tokens + example: 0.0.1,0.0.2,0.0.3 + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RetirePoolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/{contractId}/requests: + delete: + operationId: ContractsApi_clearRetireRequests + summary: Clear retire requests. + description: >- + Clear retire contract requests. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/{contractId}/pools: + delete: + operationId: ContractsApi_clearRetirePools + summary: Clear retire pools. + description: >- + Clear retire contract pools. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + post: + operationId: ContractsApi_setRetirePool + summary: Set retire pool. + description: >- + Set retire contract pool. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RetirePoolTokenDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RetirePoolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/pools/{poolId}: + delete: + operationId: ContractsApi_unsetRetirePool + summary: Unset retire pool. + description: >- + Unset retire contract pool. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: poolId + required: true + in: path + description: Pool Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/requests/{requestId}: + delete: + operationId: ContractsApi_unsetRetireRequest + summary: Unset retire request. + description: >- + Unset retire contract request. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: requestId + required: true + in: path + description: Request Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/pools/{poolId}/retire: + post: + operationId: ContractsApi_retire + summary: Retire tokens. + description: Retire tokens. + parameters: + - name: poolId + required: true + in: path + description: Pool Identifier + example: 652745597a7b53526de37c05 + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RetireRequestTokenDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/requests/{requestId}/approve: + post: + operationId: ContractsApi_approveRetire + summary: Approve retire request. + description: >- + Approve retire contract request. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: requestId + required: true + in: path + description: Request identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/requests/{requestId}/cancel: + delete: + operationId: ContractsApi_cancelRetireRequest + summary: Cancel retire request. + description: Cancel retire contract request. + parameters: + - name: requestId + required: true + in: path + description: Request identifier + example: 652745597a7b53526de37c05 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire/{contractId}/admin/{hederaId}: + post: + operationId: ContractsApi_retireAddAdmin + summary: Add retire admin. + description: >- + Add retire contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + delete: + operationId: ContractsApi_retireRemoveAdmin + summary: Remove wipe admin. + description: >- + Remove wipe contract admin. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: contractId + required: true + in: path + description: Contract identifier + example: 652745597a7b53526de37c05 + schema: + type: string + - name: hederaId + required: true + in: path + description: Hedera identifier + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /contracts/retire: + get: + operationId: ContractsApi_getRetireVCs + summary: Return a list of all retire vcs. + description: Returns all retire vcs. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_3 + security: + - bearer: [] + /demo/registered-users: + get: + operationId: DemoApi_registeredUsers + summary: Returns list of registered users. + description: Returns list of registered users. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RegisteredUsersDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_4 + - demo + /demo/random-key: + get: + operationId: DemoApi_randomKey + summary: Generate demo key. + description: Generate demo key. + parameters: [] + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearer: [] + /demo/push/random-key: + get: + operationId: DemoApi_pushRandomKey + summary: Generate demo key. + description: Generate demo key. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_4 + security: + - bearer: [] + /external: + post: + operationId: ExternalApi_receiveExternalData + summary: Sends data from an external source. + description: Sends data from an external source. + parameters: [] + requestBody: + required: true + description: Object that contains a VC Document. + content: + application/json: + schema: + $ref: '#/components/schemas/ExternalDocumentDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: + - external + /ipfs/file: + post: + operationId: IpfsApi_postFile + summary: Add file from ipfs. + description: Add file from ipfs. + parameters: [] + requestBody: + required: true + description: Binary data. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_5 + - ipfs + security: + - bearer: [] + /ipfs/file/dry-run/{policyId}: + post: + operationId: IpfsApi_postFileDryRun + summary: Add file from ipfs for dry run mode. + description: Add file from ipfs for dry run mode. + parameters: + - name: policyId + required: true + in: path + description: Policy id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Binary data. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearer: [] + /ipfs/file/{cid}: + get: + operationId: IpfsApi_getFile + summary: Get file from ipfs. + description: Get file from ipfs. + parameters: + - name: cid + required: true + in: path + description: File cid + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearer: [] + /ipfs/file/{cid}/dry-run: + get: + operationId: IpfsApi_getFileDryRun + summary: Get file from ipfs for dry run mode. + description: Get file from ipfs for dry run mode. + parameters: + - name: cid + required: true + in: path + description: File cid + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_5 + security: + - bearer: [] + /logs: + post: + operationId: LoggerApi_getLogs + summary: Return a list of all logs. + description: >- + Return a list of all logs. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/LogFilterDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/LogResultDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_6 + - logs + security: + - bearer: [] + /logs/attributes: + get: + operationId: LoggerApi_getAttributes + summary: Return a list of attributes. + description: >- + Return a list of attributes. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: name + required: false + in: query + description: Name + example: Search + schema: + type: number + - name: existingAttributes + required: false + in: query + description: Existing attributes + example: + - WORKER + schema: + type: array + items: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_6 + security: + - bearer: [] + /map/key: + get: + operationId: MapApi_getKey + summary: Return map key. + description: Return map key. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_7 + - map + /map/sh: + get: + operationId: MapApi_getSentinelKey + summary: Return map key. + description: Return map key. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_7 + /metrics: + get: + operationId: MetricsApi_getMetrics + parameters: [] + responses: + '200': + description: '' + tags: + - metrics + /modules: + post: + operationId: ModulesApi_postModules + summary: Creates a new module. + description: >- + Creates a new module. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Module config. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + responses: + '200': + description: Created module. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_8 + - modules + security: + - bearer: [] + get: + operationId: ModulesApi_getModules + summary: Return a list of all modules. + description: >- + Returns all modules. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ModuleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/schemas: + get: + operationId: ModulesApi_getModuleSchemas + summary: Return a list of all module schemas. + description: >- + Returns all module schemas. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: topicId + required: false + in: query + description: Topic id + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + post: + operationId: ModulesApi_postSchemas + summary: Creates a new module schema. + description: >- + Creates a new module schema. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Schema config. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + responses: + '201': + description: Created schema. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/{uuid}: + delete: + operationId: ModulesApi_deleteModule + summary: Deletes the module. + description: >- + Deletes the module with the provided module ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: uuid + required: true + in: path + description: Module Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + get: + operationId: ModulesApi_getModule + summary: Retrieves module configuration. + description: >- + Retrieves module configuration for the specified module ID. Only users + with the Standard Registry role are allowed to make the request. + parameters: + - name: uuid + required: true + in: path + description: Module Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + put: + operationId: ModulesApi_putModule + summary: Updates module configuration. + description: >- + Updates module configuration for the specified module ID. Only users + with the Standard Registry role are allowed to make the request. + parameters: + - name: uuid + required: true + in: path + description: Module Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + requestBody: + required: true + description: Module config. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/menu: + get: + operationId: ModulesApi_getMenu + summary: Return a list of modules. + description: >- + Returns modules menu. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: Modules. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ModuleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/{uuid}/export/file: + get: + operationId: ModulesApi_moduleExportFile + summary: >- + Return module and its artifacts in a zip file format for the specified + module. + description: >- + Returns a zip file containing the published module and all associated + artifacts, i.e. schemas and VCs. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: uuid + required: true + in: path + description: Module Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: File. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/{uuid}/export/message: + get: + operationId: ModulesApi_moduleExportMessage + summary: Return Heder message ID for the specified published module. + description: >- + Returns the Hedera message ID for the specified module published onto + IPFS. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: uuid + required: true + in: path + description: Module Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportMessageDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/import/message: + post: + operationId: ModulesApi_moduleImportMessage + summary: Imports new module from IPFS. + description: >- + Imports new module and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Created module. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/import/file: + post: + operationId: ModulesApi_moduleImportFile + summary: Imports new module from a zip file. + description: >- + Imports new module and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: File. + content: + application/json: + schema: + type: string + responses: + '200': + description: Created module. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/import/message/preview: + post: + operationId: ModulesApi_moduleImportMessagePreview + summary: Imports new module from IPFS. + description: >- + Imports new module and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Module preview. + content: + application/json: + schema: + $ref: '#/components/schemas/ModulePreviewDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/import/file/preview: + post: + operationId: ModulesApi_moduleImportFilePreview + summary: Imports new module from a zip file. + description: >- + Imports new module and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: File. + content: + application/json: + schema: + type: string + responses: + '200': + description: Module preview. + content: + application/json: + schema: + $ref: '#/components/schemas/ModulePreviewDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/{uuid}/publish: + put: + operationId: ModulesApi_publishModule + summary: Publishes the module onto IPFS. + description: >- + Publishes the module with the specified (internal) module ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - name: uuid + required: true + in: path + description: Module Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + requestBody: + required: true + description: Module. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /modules/validate: + post: + operationId: ModulesApi_validateModule + summary: Validates selected module. + description: >- + Validates selected module. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Module config. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleDTO' + responses: + '200': + description: Validation result. + content: + application/json: + schema: + $ref: '#/components/schemas/ModuleValidationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_8 + security: + - bearer: [] + /tools: + post: + operationId: ToolsApi_createNewTool + summary: Creates a new tool. + description: >- + Creates a new tool. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_9 + - tools + security: + - bearer: [] + get: + operationId: ToolsApi_getTools + summary: Return a list of all tools. + description: >- + Returns all tools. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/push: + post: + operationId: ToolsApi_createNewToolAsync + summary: Creates a new tool. + description: >- + Creates a new tool. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/{id}: + delete: + operationId: ToolsApi_deleteTool + summary: >- + Deletes the tool with the provided tool ID. Only users with the Standard + Registry role are allowed to make the request. + description: Deletes the tool. + parameters: + - name: id + required: true + in: path + description: Tool ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + get: + operationId: ToolsApi_getToolById + summary: Retrieves tool configuration. + description: >- + Retrieves tool configuration for the specified tool ID. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + put: + operationId: ToolsApi_updateTool + summary: Updates tool configuration. + description: >- + Updates tool configuration for the specified tool ID. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Tool configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/{id}/publish: + put: + operationId: ToolsApi_publishTool + summary: Publishes the tool onto IPFS. + description: >- + Publishes the tool with the specified (internal) tool ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Tool configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolValidationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/{id}/push/publish: + put: + operationId: ToolsApi_publishToolAsync + summary: Publishes the tool onto IPFS. + description: >- + Publishes the tool with the specified (internal) tool ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Tool configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/validate: + post: + operationId: ToolsApi_validateTool + summary: Validates selected tool. + description: >- + Validates selected tool. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Tool configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + responses: + '200': + description: Validation result. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolValidationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/{id}/export/file: + get: + operationId: ToolsApi_toolExportFile + summary: >- + Return tool and its artifacts in a zip file format for the specified + tool. + description: >- + Returns a zip file containing the published tool and all associated + artifacts, i.e. schemas and VCs. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: id + required: true + in: path + description: Tool ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. Response zip file. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/{id}/export/message: + get: + operationId: ToolsApi_toolExportMessage + summary: Return Heder message ID for the specified published tool. + description: >- + Returns the Hedera message ID for the specified tool published onto + IPFS. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: id + required: true + in: path + description: Tool ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportMessageDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/import/message/preview: + post: + operationId: ToolsApi_toolImportMessagePreview + summary: Imports new tool from IPFS. + description: >- + Imports new tool and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Tool preview. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolPreviewDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/import/message: + post: + operationId: ToolsApi_toolImportMessage + summary: Imports new tool from IPFS. + description: >- + Imports new tool and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/import/file/preview: + post: + operationId: ToolsApi_toolImportFilePreview + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: File. + content: + application/json: + schema: + type: string + responses: + '200': + description: Module preview. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolPreviewDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/import/file: + post: + operationId: ToolsApi_toolImportFile + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: File. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/import/file-metadata: + post: + operationId: ToolsApi_toolImportFileWithMetadata + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Form data with tool file and metadata. + content: + multipart/form-data: + schema: + type: object + properties: + file: + type: string + format: binary + metadata: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/push/import/file: + post: + operationId: ToolsApi_toolImportFileAsync + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: A zip file containing tool config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/push/import/file-metadata: + post: + operationId: ToolsApi_toolImportFileWithMetadataAsync + summary: Imports new tool from a zip file. + description: >- + Imports new tool and all associated artifacts, such as schemas and VCs, + from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Form data with tool file and metadata. + content: + multipart/form-data: + schema: + type: object + properties: + file: + type: string + format: binary + metadata: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/push/import/message: + post: + operationId: ToolsApi_toolImportMessageAsync + summary: Imports new tool from IPFS. + description: >- + Imports new tool and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /tools/menu/all: + get: + operationId: ToolsApi_getMenu + summary: Return a list of tools. + description: >- + Returns tools menu. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: Modules. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ToolDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_9 + security: + - bearer: [] + /profiles/{username}: + get: + operationId: ProfileApi_getProfile + summary: Returns user account info. + description: >- + Returns user account information. For users with the Standard Registry + role it also returns address book and VC document information. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to fetch the information + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ProfileDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_10 + - profiles + security: + - bearer: [] + put: + operationId: ProfileApi_setUserProfile + summary: Sets Hedera credentials for the user. + description: >- + Sets Hedera credentials for the user. For users with the Standard + Registry role it also creates an address book. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to update the information. + example: username + schema: + type: string + requestBody: + required: true + description: Object that contains the Hedera account data. + content: + application/json: + schema: + $ref: '#/components/schemas/CredentialsDTO' + responses: + '200': + description: Created. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_10 + security: + - bearer: [] + /profiles/push/{username}: + put: + operationId: ProfileApi_setUserProfileAsync + summary: Sets Hedera credentials for the user. + description: >- + Sets Hedera credentials for the user. For users with the Standard + Registry role it also creates an address book. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to update the information. + example: username + schema: + type: string + requestBody: + required: true + description: Object that contains the Hedera account data. + content: + application/json: + schema: + $ref: '#/components/schemas/CredentialsDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_10 + security: + - bearer: [] + /profiles/{username}/balance: + get: + operationId: ProfileApi_getUserBalance + summary: Returns user's Hedera account balance. + description: >- + Requests Hedera account balance. Only users with the Installer role are + allowed to make the request. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to fetch the balance. + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_10 + security: + - bearer: [] + /profiles/restore/{username}: + put: + operationId: ProfileApi_restoreUserProfile + summary: Restore user data (policy, DID documents, VC documents). + description: Restore user data (policy, DID documents, VC documents). + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to restore the information. + example: username + schema: + type: string + requestBody: + required: true + description: Object that contains the Hedera account data. + content: + application/json: + schema: + $ref: '#/components/schemas/CredentialsDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_10 + security: + - bearer: [] + /profiles/restore/topics/{username}: + put: + operationId: ProfileApi_restoreTopic + summary: List of available recovery topics. + description: List of available recovery topics. + parameters: + - name: username + required: true + in: path + description: The name of the user for whom to restore the information. + example: username + schema: + type: string + requestBody: + required: true + description: Object that contains the Hedera account data. + content: + application/json: + schema: + $ref: '#/components/schemas/CredentialsDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_10 + security: + - bearer: [] + /profiles/did-document/validate: + post: + operationId: ProfileApi_validateDidDocument + summary: Validate DID document format. + description: Validate DID document format. + parameters: [] + requestBody: + required: true + description: DID Document. + content: + application/json: + schema: + $ref: '#/components/schemas/DidDocumentDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/DidDocumentStatusDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_10 + security: + - bearer: [] + /profiles/did-keys/validate: + post: + operationId: ProfileApi_validateDidKeys + summary: Validate DID document keys. + description: Validate DID document keys. + parameters: [] + requestBody: + required: true + description: DID Document and keys. + content: + application/json: + schema: + $ref: '#/components/schemas/DidDocumentWithKeyDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/DidKeyStatusDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_10 + security: + - bearer: [] + /policies: + get: + operationId: PolicyApi_getPolicies + summary: Return a list of all policies. + description: Returns all policies. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_11 + - policies + security: + - bearer: [] + post: + operationId: PolicyApi_createPolicy + summary: Creates a new policy. + description: >- + Creates a new policy. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/migrate-data: + post: + operationId: PolicyApi_migrateData + summary: Migrate policy data. + description: >- + Migrate policy data. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Migration config. + content: + application/json: + schema: + $ref: '#/components/schemas/MigrationConfigDTO' + responses: + '200': + description: Errors while migration. + content: + application/json: + schema: + type: array + items: + type: object + properties: + error: + type: string + id: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push/migrate-data: + post: + operationId: PolicyApi_migrateDataAsync + summary: Migrate policy data asynchronous. + description: >- + Migrate policy data asynchronous. Only users with the Standard Registry + role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Migration configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/MigrationConfigDTO' + responses: + '202': + description: Created task. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push: + post: + operationId: PolicyApi_createPolicyAsync + summary: Creates a new policy. + description: >- + Creates a new policy. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push/{policyId}: + post: + operationId: PolicyApi_updatePolicyAsync + summary: Clones policy. + description: >- + Clones policy. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + delete: + operationId: PolicyApi_deletePolicyAsync + summary: Remove policy. + description: >- + Remove policy. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}: + get: + operationId: PolicyApi_getPolicy + summary: Retrieves policy configuration. + description: >- + Retrieves policy configuration for the specified policy ID. Only users + with the Standard Registry role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + put: + operationId: PolicyApi_updatePolicy + summary: Updates policy configuration. + description: >- + Updates policy configuration for the specified policy ID. Only users + with the Standard Registry role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + responses: + '200': + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/publish: + put: + operationId: PolicyApi_publishPolicy + summary: Publishes the policy onto IPFS. + description: >- + Publishes the policy with the specified (internal) policy ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PoliciesValidationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push/{policyId}/publish: + put: + operationId: PolicyApi_publishPolicyAsync + summary: Publishes the policy onto IPFS. + description: >- + Publishes the policy with the specified (internal) policy ID onto IPFS, + sends a message featuring its IPFS CID into the corresponding Hedera + topic. Only users with the Standard Registry role are allowed to make + the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/dry-run: + put: + operationId: PolicyApi_dryRunPolicy + summary: Dry Run policy. + description: >- + Run policy without making any persistent changes or executing + transaction. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/PoliciesValidationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/discontinue: + put: + operationId: PolicyApi_discontinuePolicy + summary: Discontinue policy. + description: >- + Discontinue policy. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Discontinue details. + content: + application/json: + schema: + type: object + properties: + date: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/draft: + put: + operationId: PolicyApi_draftPolicy + summary: Return policy to editing. + description: >- + Return policy to editing. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/validate: + post: + operationId: PolicyApi_validatePolicy + summary: Validates policy. + description: >- + Validates selected policy. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Policy configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + responses: + '200': + description: Validation result. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyValidationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/navigation: + get: + operationId: PolicyApi_getPolicyNavigation + summary: Returns a policy navigation. + description: Returns a policy navigation. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/groups: + get: + operationId: PolicyApi_getPolicyGroups + summary: Returns a list of groups the user is a member of. + description: Returns a list of groups the user is a member of. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + post: + operationId: PolicyApi_setPolicyGroups + summary: Makes the selected group active. + description: >- + Makes the selected group active. if UUID is not set then returns the + user to the default state. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Group + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/documents: + get: + operationId: PolicyApi_getPolicyDocuments + summary: Get policy documents. + description: >- + Get policy documents. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: type + required: false + in: query + description: Document type. + example: VC + schema: + enum: + - VC + - VP + type: string + - name: includeDocument + required: false + in: query + description: Include document field. + example: true + schema: + type: boolean + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Documents. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/data: + get: + operationId: PolicyApi_downloadPolicyData + summary: Get policy data. + description: >- + Get policy data. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Policy data. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/data: + post: + operationId: PolicyApi_uploadPolicyData + summary: Upload policy data. + description: >- + Upload policy data. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Policy data file + content: + application/json: + schema: + type: string + format: binary + responses: + '200': + description: Uploaded policy. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/tag-block-map: + get: + operationId: PolicyApi_getTagBlockMap + summary: Get policy tag block map. + description: >- + Get policy tag block map. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Policy tag block map. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/virtual-keys: + get: + operationId: PolicyApi_downloadVirtualKeys + summary: Get policy virtual keys. + description: >- + Get policy virtual keys. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Policy virtual keys. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + post: + operationId: PolicyApi_uploadVirtualKeys + summary: Upload policy virtual keys. + description: >- + Upload policy virtual keys. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Virtual keys file + content: + application/json: + schema: + type: string + format: binary + responses: + '200': + description: Operation completed. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/blocks: + get: + operationId: PolicyApi_getPolicyBlocks + summary: Retrieves data for the policy root block. + description: >- + Returns data from the root policy block. Only users with the Standard + Registry and Installer role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BlockDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/blocks/{uuid}: + get: + operationId: PolicyApi_getBlockData + summary: Requests block data. + description: >- + Requests block data. Only users with a role that described in block are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: uuid + required: true + in: path + description: Block Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BlockDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + post: + operationId: PolicyApi_setBlockData + summary: Sends data to the specified block. + description: Sends data to the specified block. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: uuid + required: true + in: path + description: Block Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + requestBody: + required: true + description: Data + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BlockDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/tag/{tagName}/blocks: + post: + operationId: PolicyApi_setBlocksByTagName + summary: Sends data to the specified block. + description: Sends data to the specified block. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: tagName + required: true + in: path + description: Block name (Tag) + example: block-tag + schema: + type: string + requestBody: + required: true + description: Data + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BlockDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + get: + operationId: PolicyApi_getBlocksByTagName + summary: Requests block data. + description: >- + Requests block data by tag. Only users with a role that described in + block are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: tagName + required: true + in: path + description: Block name (Tag) + example: block-tag + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BlockDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/tag/{tagName}: + get: + operationId: PolicyApi_getBlockByTagName + summary: Requests block config. + description: >- + Requests block data by tag. Only users with a role that described in + block are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: tagName + required: true + in: path + description: Block name (Tag) + example: block-tag + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BlockDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/blocks/{uuid}/parents: + get: + operationId: PolicyApi_getBlockParents + summary: Requests block's parents. + description: >- + Requests block's parents. Only users with a role that described in block + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: uuid + required: true + in: path + description: Block Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/BlockDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/export/file: + get: + operationId: PolicyApi_getPolicyExportFile + summary: >- + Return policy and its artifacts in a zip file format for the specified + policy. + description: >- + Returns a zip file containing the published policy and all associated + artifacts, i.e. schemas and VCs. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/export/message: + get: + operationId: PolicyApi_getPolicyExportMessage + summary: Return Heder message ID for the specified published policy. + description: >- + Returns the Hedera message ID for the specified policy published onto + IPFS. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportMessageDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/export/xlsx: + get: + operationId: PolicyApi_getPolicyExportXlsx + summary: >- + Return policy and its artifacts in a xlsx file format for the specified + policy. + description: >- + Returns a xlsx file containing the published policy and all associated + artifacts, i.e. schemas and VCs. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/import/message: + post: + operationId: PolicyApi_importPolicyFromMessage + summary: Imports new policy from IPFS. + description: >- + Imports new policy and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: versionOfTopicId + required: false + in: query + description: The topic ID of policy version. + example: 0.0.00000001 + schema: + type: string + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Created policy. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push/import/message: + post: + operationId: PolicyApi_importPolicyFromMessageAsync + summary: Imports new policy from IPFS. + description: >- + Imports new policy and all associated artifacts from IPFS into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: versionOfTopicId + required: false + in: query + description: The topic ID of policy version. + example: 0.0.00000001 + schema: + type: string + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/import/message/preview: + post: + operationId: PolicyApi_importMessage + summary: Policy preview from IPFS. + description: >- + Previews the policy from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Policy preview. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyPreviewDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push/import/message/preview: + post: + operationId: PolicyApi_importFromMessagePreview + summary: Policy preview from IPFS. + description: >- + Previews the policy from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Message. + content: + application/json: + schema: + $ref: '#/components/schemas/ImportMessageDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/import/file: + post: + operationId: PolicyApi_importPolicyFromFile + summary: Imports new policy from a zip file. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: versionOfTopicId + required: false + in: query + description: The topic ID of policy version. + example: 0.0.00000001 + schema: + type: string + requestBody: + required: true + description: A zip file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Created policy. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/import/file-metadata: + post: + operationId: PolicyApi_importPolicyFromFileWithMetadata + summary: Imports new policy from a zip file with metadata. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: versionOfTopicId + required: false + in: query + description: The topic ID of policy version. + example: 0.0.00000001 + schema: + type: string + requestBody: + required: true + description: Form data with policy file and metadata. + content: + multipart/form-data: + schema: + type: object + properties: + policyFile: + type: string + format: binary + metadata: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push/import/file: + post: + operationId: PolicyApi_importPolicyFromFileAsync + summary: Imports new policy from a zip file. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: versionOfTopicId + required: false + in: query + description: The topic ID of policy version. + example: 0.0.00000001 + schema: + type: string + requestBody: + required: true + description: A zip file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push/import/file-metadata: + post: + operationId: PolicyApi_importPolicyFromFileWithMetadataAsync + summary: Imports new policy from a zip file with metadata. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided zip file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: versionOfTopicId + required: false + in: query + description: The topic ID of policy version. + example: 0.0.00000001 + schema: + type: string + requestBody: + required: true + description: Form data with policy file and metadata. + content: + multipart/form-data: + schema: + type: object + properties: + policyFile: + type: string + format: binary + metadata: + type: string + format: binary + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/import/file/preview: + post: + operationId: PolicyApi_importPolicyFromFilePreview + summary: Policy preview from a zip file. + description: >- + Previews the policy from a zip file without loading it into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + requestBody: + required: true + description: A zip file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Policy preview. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyPreviewDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/import/xlsx: + post: + operationId: PolicyApi_importPolicyFromXlsx + summary: Imports new policy from a xlsx file. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided xlsx file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: policyId + required: true + in: query + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: A xlsx file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/push/import/xlsx: + post: + operationId: PolicyApi_importPolicyFromXlsxAsync + summary: Imports new policy from a xlsx file. + description: >- + Imports new policy and all associated artifacts, such as schemas and + VCs, from the provided xlsx file into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: policyId + required: true + in: query + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: A xlsx file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/import/xlsx/preview: + post: + operationId: PolicyApi_importPolicyFromXlsxPreview + summary: Policy preview from a xlsx file. + description: >- + Previews the policy from a xlsx file without loading it into the local + DB. Only users with the Standard Registry role are allowed to make the + request. + parameters: [] + requestBody: + required: true + description: A xlsx file containing policy config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/blocks/about: + get: + operationId: PolicyApi_getBlockAbout + summary: Returns block descriptions. + description: >- + Returns block descriptions. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + responses: + '200': + description: Block descriptions. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/dry-run/users: + get: + operationId: PolicyApi_getDryRunUsers + summary: Returns virtual users. + description: >- + Returns virtual users. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Virtual users. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/dry-run/user: + post: + operationId: PolicyApi_setDryRunUser + summary: Creates virtual users. + description: >- + Creates virtual users. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Virtual users. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/dry-run/login: + post: + operationId: PolicyApi_loginDryRunUser + summary: Change active virtual user. + description: >- + Change active virtual user. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Credentials. + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Virtual users. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/dry-run/restart: + post: + operationId: PolicyApi_restartDryRun + summary: Clear dry-run state. + description: >- + Clear dry-run state. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: . + content: + application/json: + schema: + type: string + responses: + '200': + description: . + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/dry-run/transactions: + get: + operationId: PolicyApi_getDryRunTransactions + summary: Get dry-run details (Transactions). + description: >- + Get dry-run details (Transactions). Only users with the Standard + Registry role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Transactions. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/dry-run/artifacts: + get: + operationId: PolicyApi_getDryRunArtifacts + summary: Get dry-run details (Artifacts). + description: >- + Get dry-run details (Artifacts). Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Artifacts. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/dry-run/ipfs: + get: + operationId: PolicyApi_getDryRunIpfs + summary: Get dry-run details (Files). + description: >- + Get dry-run details (Files). Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 20 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Files. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/{policyId}/multiple: + get: + operationId: PolicyApi_getMultiplePolicies + summary: Requests policy links. + description: >- + Requests policy links. Only users with a role that described in block + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + post: + operationId: PolicyApi_setMultiplePolicies + summary: Creates policy link. + description: >- + Creates policy link. Only users with a role that described in block are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: '' + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + security: + - bearer: [] + /policies/methodologies/categories: + get: + operationId: PolicyApi_getPolicyCategoriesAsync + summary: Get all categories + description: Get all categories + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyCategoryDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + /policies/methodologies/search: + post: + operationId: PolicyApi_getPoliciesByCategory + summary: Get filtered policies + description: Get policies by categories and text + parameters: [] + requestBody: + required: true + description: Filters + content: + application/json: + schema: + type: string + examples: + Filter1: + value: + categoryIds: + - '000000000000000000000001' + - '000000000000000000000001' + text: abc + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_11 + /schema/{schemaId}: + get: + operationId: SingleSchemaApi_getSchema + summary: Returns schema by schema ID. + description: >- + Returns schema by schema ID. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_12 + - schema + security: + - bearer: [] + /schema/{schemaId}/parents: + get: + operationId: SingleSchemaApi_getSchemaParents + summary: Returns all parent schemas. + description: Returns all parent schemas. + parameters: + - name: schemaId + required: true + in: path + description: Schema identifier + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_12 + security: + - bearer: [] + /schema/{schemaId}/tree: + get: + operationId: SingleSchemaApi_getSchemaTree + summary: Returns schema tree. + description: Returns schema tree. + parameters: + - name: schemaId + required: true + in: path + description: Schema identifier + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + properties: + name: + type: string + type: + type: string + children: + type: array + items: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_12 + security: + - bearer: [] + /schemas: + get: + operationId: SchemaApi_getSchemasPage + summary: Return a list of all schemas. + description: Returns all schemas. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: category + required: false + in: query + description: Schema category + example: POLICY + schema: + type: string + - name: policyId + required: false + in: query + description: Policy id + example: '000000000000000000000001' + schema: + type: string + - name: moduleId + required: false + in: query + description: Module id + example: '000000000000000000000001' + schema: + type: string + - name: toolId + required: false + in: query + description: Tool id + example: '000000000000000000000001' + schema: + type: string + - name: topicId + required: false + in: query + description: Topic id + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_13 + - schemas + security: + - bearer: [] + put: + operationId: SchemaApi_setSchema + summary: Updates the schema. + description: >- + Updates the schema. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains a valid schema. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{topicId}: + get: + operationId: SchemaApi_getSchemasPageByTopicId + summary: Return a list of all schemas. + description: Returns all schemas. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: category + required: false + in: query + description: Schema category + example: POLICY + schema: + type: string + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + post: + operationId: SchemaApi_createNewSchema + summary: Creates a new schema. + description: >- + Creates a new schema. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: Object that contains a valid schema. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/type/{schemaType}: + get: + operationId: SchemaApi_getSchemaByType + summary: Finds the schema using the json document type. + description: Finds the schema using the json document type. + parameters: + - name: schemaType + required: true + in: path + description: Type + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/list/all: + get: + operationId: SchemaApi_getAll + summary: Returns a list of schemas. + description: >- + Returns a list of schemas. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/list/sub: + get: + operationId: SchemaApi_getSub + summary: Returns a list of schemas. + description: >- + Returns a list of schemas. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: category + required: false + in: query + description: Schema category + example: POLICY + schema: + type: string + - name: topicId + required: false + in: query + description: Topic Id + example: 0.0.1 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/push/copy: + post: + operationId: SchemaApi_copySchemaAsync + summary: Copy schema. + description: >- + Copy schema. Only users with the Standard Registry role are allowed to + make the request. + parameters: [] + requestBody: + required: true + description: Object that contains a valid schema. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/push/{topicId}: + post: + operationId: SchemaApi_createNewSchemaAsync + summary: Creates a new schema. + description: >- + Creates a new schema. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: Object that contains a valid schema. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{schemaId}: + delete: + operationId: SchemaApi_deleteSchema + summary: Deletes the schema with the provided schema ID. + description: >- + Deletes the schema with the provided schema ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{schemaId}/publish: + put: + operationId: SchemaApi_publishSchema + summary: Publishes the schema with the provided schema ID. + description: >- + Publishes the schema with the provided (internal) schema ID onto IPFS, + sends a message featuring IPFS CID into the corresponding Hedera topic. + Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains version. + content: + application/json: + schema: + $ref: '#/components/schemas/VersionSchemaDTO' + examples: + Version: + value: + version: 1.0.0 + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/push/{schemaId}/publish: + put: + operationId: SchemaApi_publishSchemaAsync + summary: Publishes the schema with the provided schema ID. + description: >- + Publishes the schema with the provided (internal) schema ID onto IPFS, + sends a message featuring IPFS CID into the corresponding Hedera topic. + Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains version. + content: + application/json: + schema: + $ref: '#/components/schemas/VersionSchemaDTO' + examples: + Version: + value: + version: 1.0.0 + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/import/message/preview: + post: + operationId: SchemaApi_importFromMessagePreview + summary: Previews the schema from IPFS without loading it into the local DB. + description: >- + Previews the schema from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains version. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageSchemaDTO' + examples: + Message: + value: + messageId: '0000000000.000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/push/import/message/preview: + post: + operationId: SchemaApi_importFromMessagePreviewAsync + summary: Previews the schema from IPFS without loading it into the local DB. + description: >- + Previews the schema from IPFS without loading it into the local DB. Only + users with the Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains version. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageSchemaDTO' + examples: + Message: + value: + messageId: '0000000000.000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/import/file/preview: + post: + operationId: SchemaApi_importFromFilePreview + summary: Previews the schema from a zip file. + description: >- + Previews the schema from a zip file. Only users with the Standard + Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: A zip file containing schema to be imported. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{topicId}/import/message: + post: + operationId: SchemaApi_importFromMessage + summary: Imports new schema from IPFS into the local DB. + description: >- + Imports new schema from IPFS into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: Object that contains version. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageSchemaDTO' + examples: + Message: + value: + messageId: '0000000000.000000001' + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/push/{topicId}/import/message: + post: + operationId: SchemaApi_importFromMessageAsync + summary: Imports new schema from IPFS into the local DB. + description: >- + Imports new schema from IPFS into the local DB. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: Object that contains version. + content: + application/json: + schema: + $ref: '#/components/schemas/MessageSchemaDTO' + examples: + Message: + value: + messageId: '0000000000.000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{topicId}/import/file: + post: + operationId: SchemaApi_importToTopicFromFile + summary: Imports new schema from a zip file into the local DB. + description: >- + Imports new schema from a zip file into the local DB. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: A zip file containing schema to be imported. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/push/{topicId}/import/file: + post: + operationId: SchemaApi_importToTopicFromFileAsync + summary: Imports new schema from a zip file into the local DB. + description: >- + Imports new schema from a zip file into the local DB. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: A zip file containing schema to be imported. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{schemaId}/export/message: + get: + operationId: SchemaApi_exportMessage + summary: Returns Hedera message IDs of the published schemas. + description: >- + Returns Hedera message IDs of the published schemas, these messages + contain IPFS CIDs of these schema files. Only users with the Standard + Registry role are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ExportSchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{schemaId}/export/file: + get: + operationId: SchemaApi_exportToFile + summary: Returns schema files for the schema. + description: >- + Returns schema files for the schema. Only users with the Standard + Registry role are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. Response zip file. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/system/{username}: + post: + operationId: SchemaApi_postSystemSchema + summary: Creates a new system schema. + description: >- + Creates a new system schema. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: username + required: true + in: path + description: username + example: username + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SystemSchemaDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + get: + operationId: SchemaApi_getSystemSchema + summary: Return a list of all system schemas. + description: >- + Returns all system schemas. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: username + required: true + in: path + description: username + example: username + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/system/{schemaId}: + delete: + operationId: SchemaApi_deleteSystemSchema + summary: Deletes the system schema with the provided schema ID. + description: >- + Deletes the system schema with the provided schema ID. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + put: + operationId: SchemaApi_setSystemSchema + summary: Updates the system schema. + description: >- + Updates the system schema. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: Object that contains a valid schema. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/system/{schemaId}/active: + put: + operationId: SchemaApi_activeSystemSchema + summary: >- + Makes the selected scheme active. Other schemes of the same type become + inactive + description: >- + Makes the selected scheme active. Other schemes of the same type become + inactive Only users with the Standard Registry role are allowed to make + the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/system/entity/{schemaEntity}: + get: + operationId: SchemaApi_getSchemaEntity + summary: Finds the schema using the schema type. + description: Finds the schema using the schema type. + parameters: + - name: schemaEntity + required: true + in: path + description: Entity name + example: STANDARD_REGISTRY + schema: + type: string + enum: + - STANDARD_REGISTRY + - USER + - POLICY + - MINT_TOKEN + - WIPE_TOKEN + - MINT_NFTOKEN + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{schemaId}/export/xlsx: + get: + operationId: SchemaApi_getPolicyExportXlsx + summary: Return schemas in a xlsx file format for the specified policy. + description: >- + Returns a xlsx file containing schemas. Only users with the Standard + Registry role are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/{topicId}/import/xlsx: + post: + operationId: SchemaApi_importPolicyFromXlsx + summary: Imports new schema from a xlsx file into the local DB. + description: >- + Imports new schema from a xlsx file into the local DB. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: A xlsx file containing schema config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/push/{topicId}/import/xlsx: + post: + operationId: SchemaApi_importPolicyFromXlsxAsync + summary: Imports new schema from a xlsx file into the local DB. + description: >- + Imports new schema from a xlsx file into the local DB. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: topicId + required: true + in: path + description: Topic Id + example: 0.0.1 + schema: + type: string + requestBody: + required: true + description: A xlsx file containing schema config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/import/xlsx/preview: + post: + operationId: SchemaApi_importPolicyFromXlsxPreview + summary: Previews the schema from a xlsx file. + description: >- + Previews the schema from a xlsx file. Only users with the Standard + Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: A xlsx file containing schema config. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /schemas/export/template: + get: + operationId: SchemaApi_exportTemplate + summary: Returns a list of schemas. + description: >- + Returns a list of schemas. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_13 + security: + - bearer: [] + /settings: + post: + operationId: SettingsApi_updateSettings + summary: Set settings. + description: Set settings. For users with the Standard Registry role only. + parameters: [] + requestBody: + required: true + description: Settings. + content: + application/json: + schema: + $ref: '#/components/schemas/SettingsDTO' + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_14 + - settings + security: + - bearer: [] + get: + operationId: SettingsApi_getSettings + summary: Returns current settings. + description: >- + Returns current settings. For users with the Standard Registry role + only. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/SettingsDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearer: [] + /settings/environment: + get: + operationId: SettingsApi_getEnvironment + summary: Returns current environment name. + description: Returns current environment name. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearer: [] + /settings/about: + get: + operationId: SettingsApi_getAbout + summary: Returns package version. + description: Returns package version. For users with the Standard Registry role only. + parameters: [] + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_14 + security: + - bearer: [] + /tags: + post: + operationId: TagsApi_setTags + summary: Creates new tag. + description: Creates new tag. + parameters: [] + requestBody: + required: true + description: Object that contains tag information. + content: + application/json: + schema: + $ref: '#/components/schemas/TagDTO' + responses: + '200': + description: Created tag. + content: + application/json: + schema: + $ref: '#/components/schemas/TagDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_15 + - tags + security: + - bearer: [] + /tags/search: + post: + operationId: TagsApi_searchTags + summary: Search tags. + description: Search tags. + parameters: [] + requestBody: + required: true + description: Object that contains filters + content: + application/json: + schema: + $ref: '#/components/schemas/TagFilterDTO' + examples: + Single: + value: + entity: PolicyDocument + target: '0000000000.000000001' + Multiple: + value: + entity: PolicyDocument + targets: + - '0000000000.000000001' + - '0000000000.000000001' + responses: + '200': + description: Created tag. + content: + application/json: + schema: + $ref: '#/components/schemas/TagMapDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + /tags/{uuid}: + delete: + operationId: TagsApi_deleteTag + summary: Delete tag. + description: Delete tag. + parameters: + - name: uuid + required: true + in: path + description: Tag identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + /tags/synchronization: + post: + operationId: TagsApi_synchronizationTags + summary: Synchronization of tags with an external network. + description: Synchronization of tags with an external network. + parameters: [] + requestBody: + required: true + description: Object that contains filters + content: + application/json: + schema: + $ref: '#/components/schemas/TagFilterDTO' + examples: + Single: + value: + entity: PolicyDocument + target: '0000000000.000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TagMapDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + /tags/schemas: + get: + operationId: TagsApi_getSchemas + summary: Return a list of all tag schemas. + description: >- + Returns all tag schemas. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + post: + operationId: TagsApi_postSchemas + summary: Creates a new tag schema. + description: >- + Creates a new tag schema. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Schema config. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + responses: + '201': + description: Created schema. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + /tags/schemas/{schemaId}: + delete: + operationId: TagsApi_deleteSchema + summary: Deletes the schema. + description: >- + Deletes the schema with the provided schema ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema Identifier + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + put: + operationId: TagsApi_updateSchema + summary: Updates schema configuration. + description: >- + Updates schema configuration for the specified schema ID. Only users + with the Standard Registry role are allowed to make the request. + parameters: + - name: schemaId + required: true + in: path + description: Schema Identifier + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Schema config. + content: + application/json: + schema: + $ref: '#/components/schemas/SchemaDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + /tags/schemas/{schemaId}/publish: + put: + operationId: TagsApi_publishTag + summary: Publishes the schema. + description: >- + Publishes the schema with the provided (internal) schema ID onto IPFS, + sends a message featuring IPFS CID into the corresponding Hedera topic. + Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: schemaId + required: true + in: path + description: Schema Identifier + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + /tags/schemas/published: + get: + operationId: TagsApi_getPublished + summary: Return a list of all published schemas. + description: >- + Return a list of all published schemas. Only users with the Standard + Registry role are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_15 + security: + - bearer: [] + /tasks/{taskId}: + get: + operationId: TaskApi_getTask + summary: Returns task statuses by Id. + description: Returns task statuses by Id. + parameters: + - name: taskId + required: true + in: path + description: Task Id + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskStatusDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: + - tasks + security: + - bearer: [] + /tokens: + get: + operationId: TokensApi_getTokens + summary: Return a list of tokens. + description: >- + Returns all tokens. For the Standard Registry role it returns only the + list of tokens, for other users it also returns token balances as well + as the KYC, Freeze, and Association statuses. Not allowed for the + Auditor role. + parameters: + - name: policyId + required: false + in: query + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: status + required: false + in: query + description: Token status + example: All + schema: + enum: + - Associated + - All + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/TokenDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_16 + - tokens + security: + - bearer: [] + post: + operationId: TokensApi_newToken + summary: Creates a new token. + description: >- + Creates a new token. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains token information. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/TokenDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + put: + operationId: TokensApi_updateToken + summary: Update token. + description: >- + Update token. Only users with the Standard Registry role are allowed to + make the request. + parameters: [] + requestBody: + required: true + description: Object that contains token information. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenDTO' + responses: + '200': + description: Updated token. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/push: + post: + operationId: TokensApi_pushTokenAsync + summary: Creates a new token. + description: >- + Creates a new token. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains token information. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + put: + operationId: TokensApi_updateTokenAsync + summary: Update token. + description: >- + Update token. Only users with the Standard Registry role are allowed to + make the request. + parameters: [] + requestBody: + required: true + description: Object that contains token information. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/push/{tokenId}: + delete: + operationId: TokensApi_deleteTokenAsync + summary: Deletes the token with the provided schema ID. + description: >- + Deletes the token with the provided schema ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/{tokenId}/associate: + put: + operationId: TokensApi_associateToken + summary: Associates the user with the provided Hedera token. + description: >- + Associates the user with the provided Hedera token. Only users with the + Installer role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfoDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/push/{tokenId}/associate: + put: + operationId: TokensApi_associateTokenAsync + summary: Associates the user with the provided Hedera token. + description: >- + Associates the user with the provided Hedera token. Only users with the + Installer role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/{tokenId}/dissociate: + put: + operationId: TokensApi_dissociateToken + summary: Associate the user with the provided Hedera token. + description: >- + Disassociates the user with the provided Hedera token. Only users with + the Installer role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfoDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/push/{tokenId}/dissociate: + put: + operationId: TokensApi_dissociateTokenAsync + summary: Associate the user with the provided Hedera token. + description: >- + Disassociates the user with the provided Hedera token. Only users with + the Installer role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/{tokenId}/{username}/grant-kyc: + put: + operationId: TokensApi_grantKyc + summary: Sets the KYC flag for the user. + description: >- + Sets the KYC flag for the user. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfoDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/push/{tokenId}/{username}/grant-kyc: + put: + operationId: TokensApi_grantKycAsync + summary: Sets the KYC flag for the user. + description: >- + Sets the KYC flag for the user. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/{tokenId}/{username}/revoke-kyc: + put: + operationId: TokensApi_revokeKyc + summary: Unsets the KYC flag for the user. + description: >- + Unsets the KYC flag for the user. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfoDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/push/{tokenId}/{username}/revoke-kyc: + put: + operationId: TokensApi_revokeKycAsync + summary: Unsets the KYC flag for the user. + description: >- + Unsets the KYC flag for the user. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/{tokenId}/{username}/freeze: + put: + operationId: TokensApi_freezeToken + summary: Freeze transfers of the specified token for the user. + description: >- + Freezes transfers of the specified token for the user. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfoDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/{tokenId}/{username}/unfreeze: + put: + operationId: TokensApi_unfreezeToken + summary: Unfreezes transfers of the specified token for the user. + description: >- + Unfreezes transfers of the specified token for the user. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfoDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/push/{tokenId}/{username}/freeze: + put: + operationId: TokensApi_freezeTokenAsync + summary: Freeze transfers of the specified token for the user. + description: >- + Freezes transfers of the specified token for the user. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/push/{tokenId}/{username}/unfreeze: + put: + operationId: TokensApi_unfreezeTokenAsync + summary: Unfreezes transfers of the specified token for the user. + description: >- + Unfreezes transfers of the specified token for the user. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/{tokenId}/{username}/info: + get: + operationId: TokensApi_getTokenInfo + summary: Returns user information for the selected token. + description: >- + Returns user information for the selected token. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + - name: username + required: true + in: path + description: Username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TokenInfoDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/{tokenId}/serials: + get: + operationId: TokensApi_getTokenSerials + summary: Return token serials. + description: Returns token serials of current user. + parameters: + - name: tokenId + required: true + in: path + description: Token ID + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Token serials. + content: + application/json: + schema: + type: array + items: + type: number + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /tokens/menu/all: + get: + operationId: TokensApi_getMenu + summary: Return a list of tokens. + description: >- + Returns tokens menu. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: Modules. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/TokenDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_16 + security: + - bearer: [] + /themes: + post: + operationId: ThemesApi_setThemes + summary: Creates a new theme. + description: >- + Creates a new theme. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains a theme. + content: + application/json: + schema: + $ref: '#/components/schemas/ThemeDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ThemeDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_17 + - themes + security: + - bearer: [] + get: + operationId: ThemesApi_getThemes + summary: Returns a list of all themes. + description: >- + Returns a list of all themes. Only users with the Standard Registry role + are allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ThemeDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_17 + security: + - bearer: [] + /themes/{themeId}: + put: + operationId: ThemesApi_updateTheme + summary: Updates theme configuration. + description: >- + Updates theme configuration for the specified theme ID. Only users with + the Standard Registry role are allowed to make the request. + parameters: + - name: themeId + required: true + in: path + description: Theme Identifier + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains a theme. + content: + application/json: + schema: + $ref: '#/components/schemas/ThemeDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ThemeDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_17 + security: + - bearer: [] + delete: + operationId: ThemesApi_deleteTheme + summary: Deletes the theme. + description: >- + Deletes the theme with the provided theme ID. Only users with the + Standard Registry role are allowed to make the request. + parameters: + - name: themeId + required: true + in: path + description: Theme Identifier + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_17 + security: + - bearer: [] + /themes/import/file: + post: + operationId: ThemesApi_importTheme + summary: Imports new theme from a zip file. + description: >- + Imports new theme from the provided zip file into the local DB. Only + users with the Standard Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: A zip file containing theme to be imported. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/ThemeDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_17 + security: + - bearer: [] + /themes/{themeId}/export/file: + get: + operationId: ThemesApi_exportTheme + summary: Returns a zip file containing the theme. + description: >- + Returns a zip file containing the theme. Only users with the Standard + Registry role are allowed to make the request. + parameters: + - name: themeId + required: true + in: path + description: Theme Identifier + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. Response zip file. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_17 + security: + - bearer: [] + /trust-chains: + get: + operationId: TrustChainsApi_getTrustChains + summary: Returns a list of all VP documents. + description: >- + Returns a list of all VP documents. Only users with the Standard + Registry role are allowed to make the request. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: policyId + required: false + in: query + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + - name: policyOwner + required: false + in: query + description: Policy Owner + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + schema: + type: string + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/VpDocumentDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_18 + - trust-chains + security: + - bearer: [] + /trust-chains/{hash}: + get: + operationId: TrustChainsApi_getTrustChainByHash + summary: Builds and returns a trustchain, from the VP to the root VC document. + description: >- + Builds and returns a trustchain, from the VP to the root VC document. + Only users with the Standard Registry role are allowed to make the + request. + parameters: + - name: hash + required: true + in: path + description: Hash + example: hash + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: object + properties: + chain: + type: array + items: + type: object + properties: + id: + type: string + type: + type: string + tag: + type: string + label: + type: string + schema: + type: string + owner: + type: string + document: + type: object + required: + - id + - type + - tag + - label + - schema + - owner + - document + userMap: + type: array + items: + type: object + properties: + did: + type: string + username: + type: string + required: + - did + - username + required: + - chain + - userMap + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_18 + security: + - bearer: [] + /wizard/policy: + post: + operationId: WizardApi_setPolicy + summary: Creates a new policy. + description: >- + Creates a new policy by wizard. Only users with the Standard Registry + role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains wizard configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/WizardConfigDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/WizardResultDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_19 + - wizard + security: + - bearer: [] + /wizard/push/policy: + post: + operationId: WizardApi_setPolicyAsync + summary: Creates a new policy. + description: >- + Creates a new policy by wizard. Only users with the Standard Registry + role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains wizard configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/WizardConfigAsyncDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_19 + security: + - bearer: [] + /wizard/{policyId}/config: + post: + operationId: WizardApi_setPolicyConfig + summary: Get policy config. + description: >- + Get policy config by wizard. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains wizard configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/WizardConfigDTO' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/WizardPreviewDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_19 + security: + - bearer: [] + /branding: + post: + operationId: BrandingApi_setBranding + summary: Update branding. + description: >- + Update branding. Only users with the Standard Registry role are allowed + to make the request. + parameters: [] + requestBody: + required: true + description: Object that contains config. + content: + application/json: + schema: + $ref: '#/components/schemas/BrandingDTO' + responses: + '200': + description: Successful operation. + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_20 + - branding + security: + - bearer: [] + get: + operationId: BrandingApi_getBranding + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/BrandingDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_20 + /suggestions: + post: + operationId: SuggestionsApi_policySuggestions + summary: Get next and nested suggested block types + description: >- + Get next and nested suggested block types. Only users with the Standard + Registry role are allowed to make the request. + parameters: [] + requestBody: + required: true + description: Data. + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsInputDTO' + responses: + '200': + description: >- + Successful operation. Suggested next and nested block types + respectively. + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsOutputDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_21 + - suggestions + security: + - bearer: [] + /suggestions/config: + post: + operationId: SuggestionsApi_setPolicySuggestionsConfig + summary: Set suggestions config + description: >- + Set suggestions config. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + requestBody: + required: true + description: Suggestions config. + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsConfigDTO' + responses: + '201': + description: Successful operation. Response setted suggestions config. + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsConfigDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_21 + security: + - bearer: [] + get: + operationId: SuggestionsApi_getPolicySuggestionsConfig + summary: Get suggestions config + description: >- + Get suggestions config. Only users with the Standard Registry role are + allowed to make the request. + parameters: [] + responses: + '200': + description: Successful operation. Response suggestions config. + content: + application/json: + schema: + $ref: '#/components/schemas/SuggestionsConfigDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_21 + security: + - bearer: [] + /notifications: + get: + operationId: NotificationsApi_getAllNotifications + summary: Get all notifications + description: Returns all notifications. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. Returns notifications and count. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NotificationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_22 + - notifications + security: + - bearer: [] + /notifications/new: + get: + operationId: NotificationsApi_getNewNotifications + summary: Get new notifications + description: Returns new notifications. + parameters: [] + responses: + '200': + description: Successful operation. Returns new notifications. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NotificationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_22 + security: + - bearer: [] + /notifications/progresses: + get: + operationId: NotificationsApi_getProgresses + summary: Get progresses + description: Returns progresses. + parameters: [] + responses: + '200': + description: Successful operation. Returns progresses. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ProgressDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_22 + security: + - bearer: [] + /notifications/read/all: + post: + operationId: NotificationsApi_readAll + summary: Read all notifications + description: Returns new notifications. + parameters: [] + responses: + '200': + description: Successful operation. Returns notifications. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NotificationDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_22 + security: + - bearer: [] + /notifications/delete/{notificationId}: + delete: + operationId: NotificationsApi_delete + summary: Delete notifications up to this point + description: Returns deleted notifications count. + parameters: + - name: notificationId + required: true + in: path + description: Notification Identifier + example: 00000000-0000-0000-0000-000000000000 + schema: + type: string + responses: + '200': + description: Successful operation. Returns deleted notifications count. + content: + application/json: + schema: + type: number + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_22 + security: + - bearer: [] + /projects/search: + post: + operationId: ProjectsAPI_projectSearch + summary: Search projects + description: Search projects by filters + parameters: [] + requestBody: + required: true + description: The question of choosing a methodology + content: + application/json: + schema: + type: string + examples: + q: + value: >- + What methodology can I use for production of electricity using + renewable energy technologies? + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/ProjectDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_23 + - projects + /projects/compare/documents: + post: + operationId: ProjectsAPI_compareDocumentsV2 + summary: Compare documents. + description: Compare documents. + parameters: [] + requestBody: + required: true + description: Filters. + content: + application/json: + schema: + $ref: '#/components/schemas/FilterDocumentsDTO' + examples: + Filter1: + value: + documentId1: '000000000000000000000001' + documentId2: '000000000000000000000001' + Filter2: + value: + documentIds: + - '000000000000000000000001' + - '000000000000000000000001' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/CompareDocumentsV2DTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_23 + /projects/properties: + get: + operationId: ProjectsAPI_getPolicyProperties + summary: Get all properties + description: Get all properties + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PropertiesDTO' + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_23 + /record/{policyId}/status: + get: + operationId: RecordApi_getRecordStatus + summary: Get recording or running status. + description: >- + Get recording or running status. Only users with the Standard Registry + role are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RecordStatusDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_24 + - record + security: + - bearer: [] + /record/{policyId}/recording/start: + post: + operationId: RecordApi_startRecord + summary: Start recording. + description: >- + Start recording. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/recording/stop: + post: + operationId: RecordApi_stopRecord + summary: Stop recording. + description: >- + Stop recording. Only users with the Standard Registry role are allowed + to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: string + format: binary + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/recording/actions: + get: + operationId: RecordApi_getRecordActions + summary: Get recorded actions. + description: >- + Get recorded actions. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RecordActionDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/running/start: + post: + operationId: RecordApi_runRecord + summary: Run record from a zip file. + description: >- + Run record from a zip file. Only users with the Standard Registry role + are allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: A zip file containing record to be run. + content: + application/json: + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/running/stop: + post: + operationId: RecordApi_stopRunning + summary: Stop running. + description: >- + Stop running. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/running/results: + get: + operationId: RecordApi_getRecordResults + summary: Get running results. + description: >- + Get running results. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RunningResultDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/running/details: + get: + operationId: RecordApi_getRecordDetails + summary: Get running details. + description: >- + Get running details. Only users with the Standard Registry role are + allowed to make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + $ref: '#/components/schemas/RunningDetailsDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/running/fast-forward: + post: + operationId: RecordApi_fastForward + summary: Fast Forward. + description: >- + Fast Forward. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/running/retry: + post: + operationId: RecordApi_retryStep + summary: Retry step. + description: >- + Retry step. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /record/{policyId}/running/skip: + post: + operationId: RecordApi_skipStep + summary: Skip step. + description: >- + Skip step. Only users with the Standard Registry role are allowed to + make the request. + parameters: + - name: policyId + required: true + in: path + description: Policy Id + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Object that contains options + content: + application/json: + schema: + $ref: '#/components/schemas/Object' + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_24 + security: + - bearer: [] + /ai-suggestions/ask: + get: + operationId: AISuggestionsAPI_getAIAnswer + summary: Get methodology suggestion + description: Returns AI response to the current question + parameters: + - name: q + required: true + in: query + description: The question of choosing a methodology + example: Find me large scale projects + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + example: ACM0001, ACM0002, ACM0006, ACM0007, ACM0018 + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_25 + - ai-suggestions + /ai-suggestions/rebuild-vector: + put: + operationId: AISuggestionsAPI_rebuildVector + summary: Rebuild AI vector + description: Rebuilds vector based on policy data in the DB + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_25 + /permissions: + get: + operationId: PermissionsApi_getPermissions + summary: Return a list of all permissions. + description: Returns all permissions. + parameters: [] + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PermissionsDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: &ref_26 + - permissions + security: + - bearer: [] + /permissions/roles: + get: + operationId: PermissionsApi_getRoles + summary: Return a list of all roles. + description: Returns all roles. + parameters: + - name: name + required: false + in: query + description: Filter by role name + example: name + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/RoleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + post: + operationId: PermissionsApi_createRole + summary: Creates new role. + description: Creates new role. + parameters: [] + requestBody: + required: true + description: Object that contains role information. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleDTO' + responses: + '200': + description: Created role. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + /permissions/roles/{id}: + put: + operationId: PermissionsApi_updateRole + summary: Updates role configuration. + description: Updates role configuration for the specified role ID. + parameters: + - name: id + required: true + in: path + description: Role Identifier + example: '000000000000000000000001' + schema: + type: string + requestBody: + required: true + description: Role configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleDTO' + responses: + '200': + description: Role configuration. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + delete: + operationId: PermissionsApi_deleteModule + summary: Deletes the role. + description: Deletes the role with the provided role ID. + parameters: + - name: id + required: true + in: path + description: Role Identifier + example: '000000000000000000000001' + schema: + type: string + responses: + '200': + description: Successful operation. + content: + application/json: + schema: + type: boolean + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + /permissions/roles/default: + post: + operationId: PermissionsApi_setDefaultRole + summary: Set default role. + description: Set the role as default for new users. + parameters: [] + requestBody: + required: true + description: Object that contains role information. + content: + application/json: + schema: + type: object + properties: + id: + type: string + description: Role Identifier + example: '000000000000000000000001' + required: + - id + examples: + Default: + value: + id: '000000000000000000000001' + responses: + '200': + description: Created role. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + /permissions/users: + get: + operationId: PermissionsApi_getUsers + summary: Return a list of all users. + description: Returns all users. + parameters: + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: role + required: false + in: query + description: Filter by role + example: '000000000000000000000001' + schema: + type: string + - name: status + required: false + in: query + description: Filter by status + example: Active + schema: + enum: + - Active + - Inactive + type: string + - name: username + required: false + in: query + description: Filter by username + example: username + schema: + type: string + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/UserDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + /permissions/users/{username}: + get: + operationId: PermissionsApi_getUser + summary: Updates user permissions. + description: Updates user permissions for the specified username. + parameters: + - name: username + required: true + in: path + description: User Identifier + example: username + schema: + type: string + responses: + '200': + description: User permissions. + content: + application/json: + schema: + $ref: '#/components/schemas/UserDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + put: + operationId: PermissionsApi_updateUser + summary: Updates user permissions. + description: Updates user permissions for the specified username. + parameters: + - name: username + required: true + in: path + description: User Identifier + example: username + schema: + type: string + requestBody: + required: true + description: User permissions. + content: + application/json: + schema: + type: array + items: + type: string + examples: + Roles: + value: + - '000000000000000000000001' + - '000000000000000000000001' + responses: + '200': + description: User permissions. + content: + application/json: + schema: + $ref: '#/components/schemas/UserDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + /permissions/users/{username}/policies: + get: + operationId: PermissionsApi_getAssignedPolicies + summary: Return a list of all roles. + description: Returns all roles. + parameters: + - name: username + required: true + in: path + description: User Identifier + example: username + schema: + type: string + - name: pageIndex + required: false + in: query + description: >- + The number of pages to skip before starting to collect the result + set + example: 0 + schema: + type: number + - name: pageSize + required: false + in: query + description: The numbers of items to return + example: 20 + schema: + type: number + - name: status + required: false + in: query + description: Filter by status + example: Active + schema: + enum: + - ALL + - DRAFT + - DRY-RUN + - PUBLISH_ERROR + - DISCONTINUED + - PUBLISH + type: string + responses: + '200': + description: Successful operation. + headers: + X-Total-Count: + schema: + type: integer + description: Total items in the collection. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + /permissions/users/{username}/policies/assign: + post: + operationId: PermissionsApi_assignPolicy + summary: Assign policy. + description: Assign policy. + parameters: + - name: username + required: true + in: path + description: User Identifier + example: username + schema: + type: string + requestBody: + required: true + description: Options. + content: + application/json: + schema: + $ref: '#/components/schemas/AssignPolicyDTO' + responses: + '200': + description: Assigned policy. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + /permissions/users/{username}/delegate: + put: + operationId: PermissionsApi_delegateRole + summary: Delegate user permissions. + description: Delegate user permissions for the specified username. + parameters: + - name: username + required: true + in: path + description: User Identifier + example: username + schema: + type: string + requestBody: + required: true + description: User permissions. + content: + application/json: + schema: + type: array + items: + type: string + examples: + Roles: + value: + - '000000000000000000000001' + - '000000000000000000000001' + responses: + '200': + description: User permissions. + content: + application/json: + schema: + $ref: '#/components/schemas/UserDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] + /permissions/users/{username}/policies/delegate: + post: + operationId: PermissionsApi_delegatePolicy + summary: Delegate policy. + description: Delegate policy. + parameters: + - name: username + required: true + in: path + description: User Identifier + example: username + schema: + type: string + requestBody: + required: true + description: Options. + content: + application/json: + schema: + $ref: '#/components/schemas/AssignPolicyDTO' + responses: + '200': + description: Assigned policy. + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyDTO' + '401': + description: Unauthorized. + '403': + description: Forbidden. + '500': + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/InternalServerErrorDTO' + tags: *ref_26 + security: + - bearer: [] +info: + title: Guardian + description: >- + The Guardian is a modular open-source solution that includes best-in-class + identity management and decentralized ledger technology (DLT) libraries. At + the heart of the Guardian solution is a sophisticated Policy Workflow Engine + (PWE) that enables applications to offer a requirements-based tokenization + implementation. + version: 2.25.0 + contact: + name: API developer + url: https://envisionblockchain.com + email: info@envisionblockchain.com + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html +tags: [] +servers: + - url: /api/v1 + description: version 1.0 +components: + securitySchemes: + bearer: + type: http + scheme: bearer + bearerFormat: JWT + schemas: + AccountsSessionResponseDTO: + type: object + properties: + username: + type: string + role: + type: string + accessToken: + type: string + required: + - username + - role + - accessToken + InternalServerErrorDTO: + type: object + properties: + code: + type: number + example: 500 + message: + type: string + example: Error message + required: + - code + - message + AccountsResponseDTO: + type: object + properties: + username: + type: string + role: + type: string + did: + type: string + required: + - username + - role + - did + RegisterUserDTO: + type: object + properties: + username: + type: string + password: + type: string + password_confirmation: + type: string + role: + type: string + required: + - username + - password + - password_confirmation + - role + LoginUserDTO: + type: object + properties: + username: + type: string + password: + type: string + required: + - username + - password + CredentialSubjectDTO: + type: object + properties: + geography: + type: string + law: + type: string + tags: + type: string + ISIC: + type: string + '@context': + type: array + items: + type: string + id: + type: string + type: + type: string + required: + - geography + - law + - tags + - ISIC + - '@context' + - id + - type + ProofDTO: + type: object + properties: + type: + type: string + created: + format: date-time + type: string + verificationMethod: + type: string + proofPurpose: + type: string + jws: + type: string + required: + - type + - created + - verificationMethod + - proofPurpose + - jws + VcDocumentDTO: + type: object + properties: + id: + type: string + type: + type: array + items: + type: string + issuer: + type: string + issuanceDate: + format: date-time + type: string + '@context': + type: array + items: + type: string + credentialSubject: + $ref: '#/components/schemas/CredentialSubjectDTO' + proof: + $ref: '#/components/schemas/ProofDTO' + required: + - id + - type + - issuer + - issuanceDate + - '@context' + - credentialSubject + - proof + PolicyDTO: + type: object + properties: + id: + type: string + example: '000000000000000000000001' + uuid: + type: string + example: 00000000-0000-0000-0000-000000000000 + name: + type: string + example: Policy name + description: + type: string + example: Description + topicDescription: + type: string + example: Description + policyTag: + type: string + example: Tag + status: + type: string + enum: + - DRY-RUN + - DRAFT + - PUBLISH_ERROR + - PUBLISH + - DISCONTINUED + example: DRAFT + creator: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + owner: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + topicId: + type: string + example: 0.0.1 + messageId: + type: string + example: '0000000000.000000001' + codeVersion: + type: string + example: 1.0.0 + createDate: + type: string + example: '1900-01-01T00:00:00.000Z' + version: + type: string + example: 1.0.0 + config: + type: object + userRole: + type: string + example: Installer + userRoles: + example: + - Installer + type: array + items: + type: string + userGroup: + type: object + example: + uuid: 00000000-0000-0000-0000-000000000000 + role: Installer + groupLabel: Label + groupName: Name + active: true + userGroups: + example: + - uuid: 00000000-0000-0000-0000-000000000000 + role: Installer + groupLabel: Label + groupName: Name + active: true + type: array + items: + type: object + policyRoles: + example: + - Registrant + type: array + items: + type: string + policyNavigation: + example: + - role: Registrant + steps: + - block: Block tag + level: 1 + name: Step name + type: array + items: + type: object + policyTopics: + example: + - name: Project + description: Project + memoObj: topic + static: false + type: any + type: array + items: + type: object + policyTokens: + example: + - tokenName: Token name + tokenSymbol: Token symbol + tokenType: non-fungible + decimals: '' + changeSupply: true + enableAdmin: true + enableFreeze: true + enableKYC: true + enableWipe: true + templateTokenTag: token_template_0 + type: array + items: + type: object + policyGroups: + example: + - name: Group name + creator: Registrant + groupAccessType: Private + groupRelationshipType: Multiple + members: + - Registrant + type: array + items: + type: object + categories: + type: array + items: + type: string + projectSchema: + type: string + example: 00000000-0000-0000-0000-000000000000 + required: + - id + - uuid + - name + - description + - topicDescription + - policyTag + - status + - creator + - owner + - topicId + - messageId + - codeVersion + - createDate + - version + - config + - userRole + - userRoles + - userGroup + - userGroups + - policyRoles + - policyNavigation + - policyTopics + - policyTokens + - policyGroups + - categories + - projectSchema + AggregatedDTOItem: + type: object + properties: + did: + type: string + hederaAccountId: + type: string + vcDocument: + $ref: '#/components/schemas/VcDocumentDTO' + policies: + $ref: '#/components/schemas/PolicyDTO' + required: + - did + - hederaAccountId + - vcDocument + - policies + UserDTO: + type: object + properties: + username: + type: string + example: username + role: + type: string + enum: &ref_35 + - STANDARD_REGISTRY + - USER + - AUDITOR + example: USER + permissionsGroup: + example: &ref_36 + - {} + type: array + items: + type: string + permissions: + example: &ref_37 + - POLICIES_POLICY_READ + type: array + items: + type: string + did: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + parent: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + hederaAccountId: + type: string + example: 0.0.1 + required: + - username + - role + - permissions + BalanceResponseDTO: + type: object + properties: + balance: + type: number + unit: + type: string + user: + $ref: '#/components/schemas/UserDTO' + required: + - balance + - unit + - user + FilterSearchPoliciesDTO: + type: object + properties: + policyId: + type: string + example: '000000000000000000000001' + required: + - policyId + SearchPoliciesDTO: + type: object + properties: + target: + type: object + result: + type: object + required: + - target + - result + FilterPoliciesDTO: + type: object + properties: + idLvl: + oneOf: &ref_27 + - type: string + - type: number + enum: &ref_28 + - 0 + - 1 + example: 0 + eventsLvl: + oneOf: &ref_29 + - type: string + - type: number + enum: &ref_30 + - 0 + - 1 + example: 0 + propLvl: + oneOf: &ref_31 + - type: string + - type: number + enum: &ref_32 + - 0 + - 1 + - 2 + example: 0 + childrenLvl: + oneOf: &ref_33 + - type: string + - type: number + enum: &ref_34 + - 0 + - 1 + - 2 + example: 0 + policyId1: + type: string + example: '000000000000000000000001' + policyId2: + type: string + example: '000000000000000000000001' + policyIds: + example: + - '000000000000000000000001' + - '000000000000000000000001' + type: array + items: + type: string + required: + - idLvl + - eventsLvl + - propLvl + - childrenLvl + - policyId1 + - policyId2 + - policyIds + ComparePoliciesDTO: + type: object + properties: + blocks: + type: object + groups: + type: object + left: + type: object + right: + type: object + roles: + type: object + tokens: + type: object + topics: + type: object + total: + type: object + required: + - blocks + - groups + - left + - right + - roles + - tokens + - topics + - total + FilterModulesDTO: + type: object + properties: + idLvl: + oneOf: *ref_27 + enum: *ref_28 + example: 0 + eventsLvl: + oneOf: *ref_29 + enum: *ref_30 + example: 0 + propLvl: + oneOf: *ref_31 + enum: *ref_32 + example: 0 + childrenLvl: + oneOf: *ref_33 + enum: *ref_34 + example: 0 + moduleId1: + type: string + example: '000000000000000000000001' + moduleId2: + type: string + example: '000000000000000000000001' + required: + - idLvl + - eventsLvl + - propLvl + - childrenLvl + - moduleId1 + - moduleId2 + CompareModulesDTO: + type: object + properties: + blocks: + type: object + left: + type: object + right: + type: object + inputEvents: + type: object + outputEvents: + type: object + variables: + type: object + total: + type: object + required: + - blocks + - left + - right + - inputEvents + - outputEvents + - variables + - total + FilterSchemasDTO: + type: object + properties: + schemaId1: + type: string + example: '000000000000000000000001' + schemaId2: + type: string + example: '000000000000000000000001' + idLvl: + oneOf: + - type: string + - type: number + enum: + - 0 + - 1 + example: 0 + required: + - schemaId1 + - schemaId2 + - idLvl + CompareSchemasDTO: + type: object + properties: + fields: + type: object + left: + type: object + right: + type: object + total: + type: object + required: + - fields + - left + - right + - total + FilterDocumentsDTO: + type: object + properties: + idLvl: + oneOf: *ref_27 + enum: *ref_28 + example: 0 + eventsLvl: + oneOf: *ref_29 + enum: *ref_30 + example: 0 + propLvl: + oneOf: *ref_31 + enum: *ref_32 + example: 0 + childrenLvl: + oneOf: *ref_33 + enum: *ref_34 + example: 0 + documentId1: + type: string + example: '000000000000000000000001' + documentId2: + type: string + example: '000000000000000000000001' + documentIds: + example: + - '000000000000000000000001' + - '000000000000000000000001' + type: array + items: + type: string + required: + - idLvl + - eventsLvl + - propLvl + - childrenLvl + - documentId1 + - documentId2 + - documentIds + CompareDocumentsDTO: + type: object + properties: + documents: + type: object + left: + type: object + right: + type: object + total: + type: object + required: + - documents + - left + - right + - total + FilterToolsDTO: + type: object + properties: + idLvl: + oneOf: *ref_27 + enum: *ref_28 + example: 0 + eventsLvl: + oneOf: *ref_29 + enum: *ref_30 + example: 0 + propLvl: + oneOf: *ref_31 + enum: *ref_32 + example: 0 + childrenLvl: + oneOf: *ref_33 + enum: *ref_34 + example: 0 + toolId1: + type: string + example: '000000000000000000000001' + toolId2: + type: string + example: '000000000000000000000001' + toolIds: + example: + - '000000000000000000000001' + - '000000000000000000000001' + type: array + items: + type: string + required: + - idLvl + - eventsLvl + - propLvl + - childrenLvl + - toolId1 + - toolId2 + - toolIds + CompareToolsDTO: + type: object + properties: + blocks: + type: object + left: + type: object + right: + type: object + inputEvents: + type: object + outputEvents: + type: object + variables: + type: object + total: + type: object + required: + - blocks + - left + - right + - inputEvents + - outputEvents + - variables + - total + FilterSearchBlocksDTO: + type: object + properties: + id: + type: string + example: 00000000-0000-0000-0000-000000000000 + config: + type: object + required: + - id + - config + SearchBlocksDTO: + type: object + properties: + name: + type: string + description: + type: string + version: + type: string + owner: + type: string + topicId: + type: string + messageId: + type: string + hash: + type: string + chains: + type: object + required: + - name + - description + - version + - owner + - topicId + - messageId + - hash + - chains + ArtifactDTOItem: + type: object + properties: + id: + type: string + name: + type: string + uuid: + type: string + extention: + type: string + type: + type: string + required: + - id + - name + - uuid + - extention + - type + ContractDTO: + type: object + properties: + id: + type: string + contractId: + type: string + description: + type: string + owner: + type: string + permissions: + type: number + topicId: + type: string + type: + type: string + enum: + - WIPE + - RETIRE + syncRequestsDate: + format: date-time + type: string + syncPoolsDate: + format: date-time + type: string + lastSyncEventTimeStamp: + type: string + wipeContractIds: + type: array + items: + type: string + required: + - id + - contractId + - description + - owner + - permissions + - topicId + - type + - syncRequestsDate + - syncPoolsDate + - lastSyncEventTimeStamp + - wipeContractIds + ContractConfigDTO: + type: object + properties: + type: + type: string + description: + type: string + required: + - type + - description + WiperRequestDTO: + type: object + properties: + id: + type: string + contractId: + type: string + user: + type: string + required: + - id + - contractId + - user + RetireRequestDTO: + type: object + properties: + id: + type: string + contractId: + type: string + tokens: + type: object + properties: + token: + type: string + count: + type: number + serials: + type: array + items: + type: number + decimals: + type: number + type: + enum: + - non-fungible + - fungible + tokenSymbol: + type: string + tokenIds: + type: array + items: + type: string + user: + type: string + required: + - id + - contractId + - tokens + - tokenIds + - user + Date: + type: object + properties: {} + RetirePoolDTO: + type: object + properties: + id: + type: string + contractId: + type: string + tokens: + type: object + properties: + token: + type: string + contract: + type: string + count: + type: number + decimals: + type: number + type: + enum: + - non-fungible + - fungible + tokenSymbol: + type: string + tokenIds: + type: array + items: + type: string + immediately: + type: boolean + enabled: + type: boolean + required: + - id + - contractId + - tokens + - tokenIds + - immediately + - enabled + RetirePoolTokenDTO: + type: object + properties: + token: + type: string + count: + type: number + required: + - token + - count + RetireRequestTokenDTO: + type: object + properties: + token: + type: string + count: + type: number + serials: + type: array + items: + type: string + required: + - token + - count + - serials + RegisteredUsersDTO: + type: object + properties: + username: + type: string + did: + type: string + parent: + type: string + role: + type: string + policyRoles: + type: array + items: + type: string + required: + - username + - did + - parent + - role + - policyRoles + TaskDTO: + type: object + properties: + taskId: + type: string + description: Task Id + example: 00000000-0000-0000-0000-000000000000 + expectation: + type: number + description: Expected count of task phases + example: 0 + required: + - taskId + - expectation + VCDocumentDTO: + type: object + properties: + id: + type: string + nullable: false + '@context': + type: array + items: + type: string + type: + type: array + items: + type: string + credentialSubject: + type: array + items: + type: object + issuer: + type: object + issuanceDate: + type: string + proof: + type: object + nullable: true + required: + - id + - '@context' + - type + - credentialSubject + - issuer + - issuanceDate + - proof + ExternalDocumentDTO: + type: object + properties: + owner: + type: string + policyTag: + type: string + document: + nullable: false + allOf: + - $ref: '#/components/schemas/VCDocumentDTO' + required: + - owner + - policyTag + - document + LogFilterDTO: + type: object + properties: + type: + type: string + nullable: true + startDate: + type: string + nullable: true + endDate: + type: string + nullable: true + attributes: + nullable: true + type: array + items: + type: string + message: + type: string + nullable: true + pageSize: + type: number + nullable: true + pageIndex: + type: number + nullable: true + sortDirection: + type: string + nullable: true + required: + - type + - startDate + - endDate + - attributes + - message + - pageSize + - pageIndex + - sortDirection + LogResultDTO: + type: object + properties: + totalCount: + type: number + logs: + type: array + items: + type: object + required: + - totalCount + - logs + ModuleDTO: + type: object + properties: + id: + type: string + nullable: false + uuid: + type: string + nullable: false + type: + type: string + nullable: false + name: + type: string + nullable: false + description: + type: string + nullable: false + status: + type: string + nullable: false + creator: + type: string + nullable: false + owner: + type: string + nullable: false + topicId: + type: string + nullable: false + messageId: + type: string + nullable: false + codeVersion: + type: string + nullable: false + createDate: + type: string + nullable: false + config: + type: object + nullable: true + required: + - id + - uuid + - type + - name + - description + - status + - creator + - owner + - topicId + - messageId + - codeVersion + - createDate + - config + SchemaDTO: + type: object + properties: + id: + type: string + example: '000000000000000000000001' + uuid: + type: string + example: 00000000-0000-0000-0000-000000000000 + name: + type: string + example: Schema name + description: + type: string + example: Description + entity: + type: string + enum: + - NONE + - VC + - EVC + - STANDARD_REGISTRY + - USER + - POLICY + - MINT_TOKEN + - RETIRE + - WIPE_TOKEN + - MINT_NFTOKEN + - ISSUER + - USER_ROLE + - CHUNK + - ACTIVITY_IMPACT + - TOKEN_DATA_SOURCE + - ROLE + - USER_PERMISSIONS + example: POLICY + iri: + type: string + example: 00000000-0000-0000-0000-000000000000 + status: + type: string + enum: + - DRAFT + - PUBLISHED + - UNPUBLISHED + - ERROR + example: DRAFT + topicId: + type: string + example: 0.0.1 + version: + type: string + example: 1.0.0 + owner: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + messageId: + type: string + example: '0000000000.000000001' + category: + type: string + enum: + - POLICY + - MODULE + - SYSTEM + - TAG + - TOOL + example: POLICY + documentURL: + type: string + example: ipfs://AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + contextURL: + type: string + example: ipfs://AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + document: + type: object + context: + type: object + required: + - id + - uuid + - name + - description + - entity + - iri + - status + - topicId + - version + - owner + - messageId + - category + - documentURL + - contextURL + - document + - context + ExportMessageDTO: + type: object + properties: + uuid: + type: string + name: + type: string + description: + type: string + messageId: + type: string + owner: + type: string + required: + - uuid + - name + - description + - messageId + - owner + ImportMessageDTO: + type: object + properties: + messageId: + type: string + metadata: + type: object + nullable: true + required: + - messageId + - metadata + ModulePreviewDTO: + type: object + properties: + module: + nullable: false + allOf: + - $ref: '#/components/schemas/ModuleDTO' + messageId: + type: string + schemas: + nullable: true + type: array + items: + type: object + tags: + nullable: true + type: array + items: + type: object + moduleTopicId: + type: string + nullable: true + required: + - module + - messageId + - schemas + - tags + - moduleTopicId + BlockErrorsDTO: + type: object + properties: + id: + type: string + name: + type: string + errors: + type: array + items: + type: string + isValid: + type: boolean + required: + - id + - name + - errors + - isValid + ValidationErrorsDTO: + type: object + properties: + blocks: + nullable: true + type: array + items: + $ref: '#/components/schemas/BlockErrorsDTO' + errors: + nullable: true + type: array + items: + type: string + required: + - blocks + - errors + ModuleValidationDTO: + type: object + properties: + module: + nullable: false + allOf: + - $ref: '#/components/schemas/ModuleDTO' + results: + nullable: false + allOf: + - $ref: '#/components/schemas/ValidationErrorsDTO' + required: + - module + - results + BlockDTO: + type: object + properties: + id: + type: string + blockType: + type: string + blocks: + type: array + items: + $ref: '#/components/schemas/BlockDTO' + required: + - id + - blockType + - blocks + ToolDTO: + type: object + properties: + id: + type: string + example: '000000000000000000000001' + uuid: + type: string + example: 00000000-0000-0000-0000-000000000000 + name: + type: string + example: Tool name + description: + type: string + example: Description + status: + type: string + enum: + - DRAFT + - PUBLISHED + - PUBLISH_ERROR + example: NEW + creator: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + owner: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + topicId: + type: string + example: 0.0.1 + messageId: + type: string + example: '0000000000.000000001' + codeVersion: + type: string + example: 1.0.0 + createDate: + type: string + example: '1900-01-01T00:00:00.000Z' + config: + $ref: '#/components/schemas/BlockDTO' + required: + - id + - uuid + - name + - description + - status + - creator + - owner + - topicId + - messageId + - codeVersion + - createDate + - config + ToolValidationDTO: + type: object + properties: + tool: + $ref: '#/components/schemas/ToolDTO' + results: + $ref: '#/components/schemas/ValidationErrorsDTO' + required: + - tool + - results + ToolPreviewDTO: + type: object + properties: + tool: + $ref: '#/components/schemas/ToolDTO' + schemas: + type: array + items: + type: object + tags: + type: array + items: + type: object + tools: + type: array + items: + $ref: '#/components/schemas/ToolDTO' + required: + - tool + - schemas + - tags + - tools + ProfileDTO: + type: object + properties: + username: + type: string + example: username + role: + type: string + enum: *ref_35 + example: USER + permissionsGroup: + example: *ref_36 + type: array + items: + type: string + permissions: + example: *ref_37 + type: array + items: + type: string + did: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + parent: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + hederaAccountId: + type: string + example: 0.0.1 + confirmed: + type: boolean + example: true + failed: + type: boolean + example: true + topicId: + type: string + example: 0.0.1 + parentTopicId: + type: string + example: 0.0.1 + didDocument: + type: object + nullable: true + vcDocument: + type: object + nullable: true + required: + - username + - role + - permissions + SubjectDTO: + type: object + properties: + '@context': + nullable: true + type: array + items: + type: string + id: + type: string + nullable: true + type: + type: string + nullable: true + required: + - '@context' + DidDocumentDTO: + type: object + properties: + id: + type: string + nullable: false + context: + nullable: true + type: array + items: + type: string + alsoKnownAs: + nullable: true + type: array + items: + type: string + controller: + nullable: true + type: array + items: + type: string + verificationMethod: + nullable: true + type: array + items: + type: object + authentication: + nullable: true + type: array + items: + type: object + assertionMethod: + nullable: true + type: array + items: + type: object + keyAgreement: + nullable: true + type: array + items: + type: object + capabilityInvocation: + nullable: true + type: array + items: + type: object + capabilityDelegation: + nullable: true + type: array + items: + type: object + service: + nullable: true + type: array + items: + type: object + required: + - id + - context + - alsoKnownAs + - controller + - verificationMethod + - authentication + - assertionMethod + - keyAgreement + - capabilityInvocation + - capabilityDelegation + - service + DidKeyDTO: + type: object + properties: + id: + type: string + nullable: false + key: + type: string + nullable: false + required: + - id + - key + CredentialsDTO: + type: object + properties: + entity: + type: string + nullable: false + hederaAccountId: + type: string + nullable: false + hederaAccountKey: + type: string + nullable: false + parent: + type: string + nullable: true + vcDocument: + nullable: true + allOf: + - $ref: '#/components/schemas/SubjectDTO' + didDocument: + nullable: true + allOf: + - $ref: '#/components/schemas/DidDocumentDTO' + didKeys: + nullable: true + type: array + items: + $ref: '#/components/schemas/DidKeyDTO' + required: + - entity + - hederaAccountId + - hederaAccountKey + DidDocumentStatusDTO: + type: object + properties: + valid: + type: boolean + nullable: false + error: + type: string + nullable: true + didDocument: + type: object + nullable: false + required: + - valid + - error + - didDocument + DidKeyStatusDTO: + type: object + properties: + id: + type: string + nullable: false + key: + type: string + nullable: false + valid: + type: boolean + nullable: false + required: + - id + - key + - valid + DidDocumentWithKeyDTO: + type: object + properties: + document: + nullable: false + allOf: + - $ref: '#/components/schemas/DidDocumentDTO' + keys: + nullable: false + type: array + items: + $ref: '#/components/schemas/DidKeyDTO' + required: + - document + - keys + MigrationConfigPoliciesDTO: + type: object + properties: + src: + type: string + dst: + type: string + required: + - src + - dst + MigrationConfigDTO: + type: object + properties: + policies: + $ref: '#/components/schemas/MigrationConfigPoliciesDTO' + vcs: + type: array + items: + type: string + vps: + type: array + items: + type: string + schemas: + type: object + groups: + type: object + roles: + type: object + blocks: + type: object + tokens: + type: object + migrateState: + type: boolean + migrateRetirePools: + type: boolean + editedVCs: + type: object + retireContractId: + type: string + required: + - policies + - vcs + - vps + - schemas + - groups + - roles + - blocks + - tokens + - migrateState + - migrateRetirePools + - editedVCs + - retireContractId + PoliciesValidationDTO: + type: object + properties: + policies: + type: array + items: + $ref: '#/components/schemas/PolicyDTO' + isValid: + type: string + errors: + $ref: '#/components/schemas/ValidationErrorsDTO' + required: + - policies + - isValid + - errors + PolicyValidationDTO: + type: object + properties: + policy: + $ref: '#/components/schemas/PolicyDTO' + results: + $ref: '#/components/schemas/ValidationErrorsDTO' + required: + - policy + - results + Object: + type: object + properties: {} + PolicyPreviewDTO: + type: object + properties: + module: + $ref: '#/components/schemas/PolicyDTO' + messageId: + type: string + example: '0000000000.000000001' + schemas: + type: array + items: + type: object + tags: + type: array + items: + type: object + moduleTopicId: + type: string + example: 0.0.1 + required: + - module + - messageId + - schemas + - tags + - moduleTopicId + PolicyCategoryDTO: + type: object + properties: + id: + type: string + example: '000000000000000000000001' + name: + type: string + example: Large-Scale + type: + type: string + example: PROJECT_SCALE + required: + - id + - name + - type + VersionSchemaDTO: + type: object + properties: + version: + type: string + example: 1.0.0 + required: + - version + MessageSchemaDTO: + type: object + properties: + messageId: + type: string + example: '0000000000.000000001' + required: + - messageId + ExportSchemaDTO: + type: object + properties: + id: + type: string + example: '000000000000000000000001' + name: + type: string + example: Schema name + description: + type: string + example: Description + version: + type: string + example: 1.0.0 + owner: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + messageId: + type: string + example: '0000000000.000000001' + required: + - id + - name + - description + - version + - owner + - messageId + SystemSchemaDTO: + type: object + properties: + name: + type: string + example: Schema name + entity: + type: string + enum: + - STANDARD_REGISTRY + - USER + example: STANDARD_REGISTRY + required: + - name + - entity + SettingsDTO: + type: object + properties: + ipfsStorageApiKey: + type: string + operatorId: + type: string + operatorKey: + type: string + required: + - ipfsStorageApiKey + - operatorId + - operatorKey + TagDTO: + type: object + properties: + uuid: + type: string + example: 00000000-0000-0000-0000-000000000000 + name: + type: string + example: Tag label + description: + type: string + example: Description + owner: + type: string + example: DID + date: + type: string + example: '1900-01-01T00:00:00.000Z' + entity: + type: string + enum: + - Schema + - Policy + - Token + - Module + - Contract + - PolicyDocument + example: PolicyDocument + status: + type: string + enum: + - Draft + - Published + - History + example: Published + operation: + type: string + enum: + - Create + - Delete + example: Create + topicId: + type: string + example: 0.0.1 + messageId: + type: string + example: '0000000000.000000001' + policyId: + type: string + example: '000000000000000000000001' + uri: + type: string + example: ipfs://AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + target: + type: string + example: '0000000000.000000001' + localTarget: + type: string + example: '000000000000000000000001' + document: + type: object + required: + - uuid + - name + - description + - owner + - date + - entity + - status + - operation + - topicId + - messageId + - policyId + - uri + - target + - localTarget + - document + TagFilterDTO: + type: object + properties: + entity: + type: string + enum: + - Schema + - Policy + - Token + - Module + - Contract + - PolicyDocument + example: PolicyDocument + target: + type: string + example: '0000000000.000000001' + targets: + example: '0000000000.000000001' + type: array + items: + type: string + required: + - entity + - target + - targets + TagMapDTO: + type: object + properties: + entity: + type: string + enum: + - Schema + - Policy + - Token + - Module + - Contract + - PolicyDocument + example: PolicyDocument + target: + type: string + example: '0000000000.000000001' + refreshDate: + type: string + example: '1900-01-01T00:00:00.000Z' + tags: + type: array + items: + $ref: '#/components/schemas/TagDTO' + required: + - entity + - target + - refreshDate + - tags + StatusDTO: + type: object + properties: + message: + type: string + description: Text + type: + type: string + description: Type + enum: + - Processing + - Completed + - Info + example: Info + required: + - message + - type + TaskStatusDTO: + type: object + properties: + action: + type: string + description: Task type + example: Create policy + userId: + type: string + description: User Id + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + expectation: + type: number + description: Expected count of task phases + example: 0 + taskId: + type: string + description: Task Id + example: 00000000-0000-0000-0000-000000000000 + date: + type: string + description: Date + example: '1900-01-01T00:00:00.000Z' + statuses: + type: array + items: + $ref: '#/components/schemas/StatusDTO' + result: + type: object + error: + type: object + required: + - action + - userId + - expectation + - taskId + - date + - statuses + - result + - error + TokenDTO: + type: object + properties: + tokenId: + type: string + example: 0.0.1 + tokenName: + type: string + example: Token name + tokenSymbol: + type: string + example: Token symbol + tokenType: + type: string + enum: + - fungible + - non-fungible + example: non-fungible + initialSupply: + type: string + example: '0' + decimals: + type: string + example: '0' + changeSupply: + type: boolean + description: Add Supply key + example: true + enableAdmin: + type: boolean + description: Add Admin key + example: true + enableFreeze: + type: boolean + description: Add Freeze key + example: true + enableKYC: + type: boolean + description: Add KYC key + example: true + enableWipe: + type: boolean + description: Add Wipe key + example: true + required: + - tokenId + - tokenName + - tokenSymbol + - tokenType + - initialSupply + - decimals + - changeSupply + - enableAdmin + - enableFreeze + - enableKYC + - enableWipe + TokenInfoDTO: + type: object + properties: + id: + type: string + example: '000000000000000000000001' + tokenId: + type: string + example: 0.0.1 + tokenName: + type: string + example: Token name + tokenSymbol: + type: string + example: Token symbol + tokenType: + type: string + enum: + - fungible + - non-fungible + example: non-fungible + decimals: + type: string + example: '0' + associated: + type: boolean + description: '' + example: true + frozen: + type: boolean + description: '' + example: true + kyc: + type: boolean + description: '' + example: true + balance: + type: string + description: User balance + example: '0' + enableAdmin: + type: boolean + description: There is an Admin key + example: true + enableFreeze: + type: boolean + description: There is an Freeze key + example: true + enableKYC: + type: boolean + description: There is an KYC key + example: true + enableWipe: + type: boolean + description: There is an Wipe key + example: true + required: + - id + - tokenId + - tokenName + - tokenSymbol + - tokenType + - decimals + - associated + - frozen + - kyc + - balance + - enableAdmin + - enableFreeze + - enableKYC + - enableWipe + ThemeRoleDTO: + type: object + properties: + description: + type: string + example: Description + text: + type: string + description: Text color + pattern: (^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$) + example: '#000000' + background: + type: string + description: Background color + pattern: (^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$) + example: '#000000' + border: + type: string + description: Border color + pattern: (^#[0-9a-f]{3}$)|(^#[0-9a-f]{6}$)|(^#[0-9a-f]{8}$) + example: '#000000' + shape: + type: string + description: Object shape + enum: + - '0' + - '1' + - '2' + - '3' + - '4' + - '5' + example: '0' + borderWidth: + type: string + description: Border width + enum: + - 0px + - 1px + - 2px + - 3px + - 4px + - 5px + - 6px + - 7px + example: 2px + filterType: + type: string + description: Filter by type + enum: + - type + - api + - role + example: type + filterValue: + oneOf: + - type: string + - type: array + items: + type: string + required: + - description + - text + - background + - border + - shape + - borderWidth + - filterType + - filterValue + ThemeDTO: + type: object + properties: + id: + type: string + example: '000000000000000000000001' + uuid: + type: string + example: 00000000-0000-0000-0000-000000000000 + name: + type: string + example: Theme name + rules: + type: array + items: + $ref: '#/components/schemas/ThemeRoleDTO' + required: + - id + - uuid + - name + - rules + VpDTO: + type: object + properties: + '@context': + type: array + items: + type: string + id: + type: string + example: 00000000-0000-0000-0000-000000000000 + type: + type: array + items: + type: string + verifiableCredential: + type: array + items: + type: object + proof: + type: object + required: + - '@context' + - id + - type + - verifiableCredential + - proof + VpDocumentDTO: + type: object + properties: + id: + type: string + example: '000000000000000000000001' + policyId: + type: string + example: '000000000000000000000001' + hash: + type: string + example: hash + signature: + type: number + example: 0 + status: + type: string + enum: + - NEW + - ISSUE + - REVOKE + - SUSPEND + - RESUME + - FAILED + example: NEW + tag: + type: string + example: Block tag + type: + type: string + example: Document type + createDate: + type: string + example: '1900-01-01T00:00:00.000Z' + updateDate: + type: string + example: '1900-01-01T00:00:00.000Z' + owner: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + document: + $ref: '#/components/schemas/VpDTO' + required: + - id + - policyId + - hash + - signature + - status + - tag + - type + - createDate + - updateDate + - owner + - document + WizardConfigDTO: + type: object + properties: + roles: + type: array + items: + type: string + policy: + type: string + properties: + name: + type: string + description: + type: string + topicDescription: + type: string + policyTag: + type: string + schemas: + properties: + name: + type: string + iri: + type: string + isApproveEnable: + type: boolean + isMintSchema: + type: boolean + mintOptions: + type: object + properties: + tokenId: + type: string + rule: + type: string + dependencySchemaIri: + type: string + relationshipsSchemaIri: + type: string + initialRolesFor: + type: array + items: + type: string + rolesConfig: + type: array + items: + type: object + properties: + role: + type: string + isApprover: + type: boolean + isCreator: + type: boolean + gridColumns: + type: array + items: + type: object + properties: + field: + type: string + title: + type: string + type: array + items: + type: string + trustChain: + properties: + role: + type: string + mintSchemaIri: + type: string + viewOnlyOwnDocuments: + type: boolean + type: array + items: + type: string + required: + - roles + - policy + - schemas + - trustChain + WizardResultDTO: + type: object + properties: + policyId: + type: string + wizardConfig: + $ref: '#/components/schemas/WizardConfigDTO' + required: + - policyId + - wizardConfig + WizardConfigAsyncDTO: + type: object + properties: + saveState: + type: boolean + wizardConfig: + $ref: '#/components/schemas/WizardConfigDTO' + required: + - saveState + - wizardConfig + WizardPreviewDTO: + type: object + properties: + policyConfig: + $ref: '#/components/schemas/PolicyDTO' + wizardConfig: + $ref: '#/components/schemas/WizardConfigDTO' + required: + - policyConfig + - wizardConfig + BrandingDTO: + type: object + properties: + headerColor: + type: string + primaryColor: + type: string + companyName: + type: string + companyLogoUrl: + type: string + loginBannerUrl: + type: string + faviconUrl: + type: string + headerColor1: + type: string + termsAndConditions: + type: string + required: + - headerColor + - primaryColor + - companyName + - companyLogoUrl + - loginBannerUrl + - faviconUrl + - headerColor1 + - termsAndConditions + SuggestionsInputDTO: + type: object + properties: + blockType: + type: string + children: + nullable: true + type: array + items: + type: object + required: + - blockType + - children + SuggestionsOutputDTO: + type: object + properties: + next: + type: string + nested: + type: string + required: + - next + - nested + SuggestionsConfigItemDTO: + type: object + properties: + id: + type: string + type: + type: string + enum: + - Policy + - Module + index: + type: number + required: + - id + - type + - index + SuggestionsConfigDTO: + type: object + properties: + items: + $ref: '#/components/schemas/SuggestionsConfigItemDTO' + required: + - items + NotificationDTO: + type: object + properties: + title: + type: string + message: + type: string + type: + type: string + enum: + - INFO + - ERROR + - WARN + - SUCCESS + action: + type: string + enum: + - POLICY_CONFIGURATION + - POLICY_VIEW + - POLICIES_PAGE + - SCHEMAS_PAGE + - TOKENS_PAGE + - PROFILE_PAGE + result: + type: object + read: + type: boolean + old: + type: boolean + required: + - title + - message + - type + - action + - result + - read + - old + ProgressDTO: + type: object + properties: + action: + type: string + message: + type: string + progress: + type: number + type: + type: string + enum: + - INFO + - ERROR + - WARN + - SUCCESS + taskId: + type: string + required: + - action + - message + - progress + - type + - taskId + ProjectDTO: + type: object + properties: + id: + type: string + policyId: + type: string + policyName: + type: string + registered: + type: string + title: + type: string + companyName: + type: string + sectoralScope: + type: string + required: + - id + - policyId + - policyName + - registered + - title + - companyName + - sectoralScope + CompareDocumentsV2DTO: + type: object + properties: + projects: + $ref: '#/components/schemas/CompareDocumentsDTO' + presentations: + $ref: '#/components/schemas/CompareDocumentsDTO' + required: + - projects + - presentations + PropertiesDTO: + type: object + properties: + id: + type: string + title: + type: string + value: + type: string + required: + - id + - title + - value + RecordStatusDTO: + type: object + properties: + type: + type: string + policyId: + type: string + uuid: + type: string + status: + type: string + required: + - type + - policyId + - uuid + - status + RecordActionDTO: + type: object + properties: + uuid: + type: string + policyId: + type: string + method: + type: string + action: + type: string + time: + type: string + user: + type: string + target: + type: string + required: + - uuid + - policyId + - method + - action + - time + - user + - target + ResultInfoDTO: + type: object + properties: + tokens: + type: number + documents: + type: number + required: + - tokens + - documents + ResultDocumentDTO: + type: object + properties: + type: + type: string + schema: + type: string + rate: + type: string + documents: + type: object + required: + - type + - schema + - rate + - documents + RunningResultDTO: + type: object + properties: + info: + $ref: '#/components/schemas/ResultInfoDTO' + total: + type: number + documents: + $ref: '#/components/schemas/ResultDocumentDTO' + required: + - info + - total + - documents + RunningDetailsDTO: + type: object + properties: + left: + type: object + right: + type: object + total: + type: number + documents: + type: object + required: + - left + - right + - total + - documents + RoleDTO: + type: object + properties: + uuid: + type: string + example: 00000000-0000-0000-0000-000000000000 + name: + type: string + example: Name + description: + type: string + example: Description + owner: + type: string + example: >- + #did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001 + permissions: + type: string + enum: &ref_38 + - ANALYTIC_POLICY_READ + - ANALYTIC_MODULE_READ + - ANALYTIC_TOOL_READ + - ANALYTIC_SCHEMA_READ + - ANALYTIC_DOCUMENT_READ + - ARTIFACTS_FILE_READ + - ARTIFACTS_FILE_CREATE + - ARTIFACTS_FILE_DELETE + - CONTRACTS_CONTRACT_READ + - CONTRACTS_CONTRACT_EXECUTE + - CONTRACTS_CONTRACT_MANAGE + - MODULES_MODULE_READ + - MODULES_MODULE_CREATE + - MODULES_MODULE_UPDATE + - MODULES_MODULE_DELETE + - MODULES_MODULE_REVIEW + - POLICIES_POLICY_READ + - POLICIES_POLICY_CREATE + - POLICIES_POLICY_UPDATE + - POLICIES_POLICY_DELETE + - POLICIES_POLICY_REVIEW + - POLICIES_POLICY_EXECUTE + - POLICIES_POLICY_MANAGE + - SCHEMAS_SCHEMA_READ + - SCHEMAS_SCHEMA_CREATE + - SCHEMAS_SCHEMA_UPDATE + - SCHEMAS_SCHEMA_DELETE + - SCHEMAS_SCHEMA_REVIEW + - TOOLS_TOOL_READ + - TOOLS_TOOL_CREATE + - TOOLS_TOOL_UPDATE + - TOOLS_TOOL_DELETE + - TOOLS_TOOL_REVIEW + - TOKENS_TOKEN_READ + - TOKENS_TOKEN_CREATE + - TOKENS_TOKEN_UPDATE + - TOKENS_TOKEN_DELETE + - TOKENS_TOKEN_EXECUTE + - TOKENS_TOKEN_MANAGE + - TAGS_TAG_READ + - TAGS_TAG_CREATE + - SUGGESTIONS_SUGGESTIONS_READ + - SUGGESTIONS_SUGGESTIONS_UPDATE + - PERMISSIONS_ROLE_READ + - PERMISSIONS_ROLE_CREATE + - PERMISSIONS_ROLE_UPDATE + - PERMISSIONS_ROLE_DELETE + - PERMISSIONS_ROLE_MANAGE + - ACCESS_POLICY_ALL + - ACCESS_POLICY_ASSIGNED + - ACCESS_POLICY_PUBLISHED + - ACCESS_POLICY_ASSIGNED_AND_PUBLISHED + - DELEGATION_ROLE_MANAGE + example: + - POLICIES_POLICY_READ + required: + - uuid + - name + - description + - owner + - permissions + PermissionsDTO: + type: object + properties: + name: + type: string + enum: *ref_38 + example: ANALYTIC_POLICY_READ + category: + type: string + enum: + - ACCOUNTS + - SESSION + - PROFILES + - ANALYTIC + - ARTIFACTS + - POLICIES + - BRANDING + - CONTRACTS + - DEMO + - IPFS + - LOG + - MODULES + - SETTINGS + - SUGGESTIONS + - TAGS + - SCHEMAS + - TOKENS + - AUDIT + - TOOLS + - PERMISSIONS + - ACCESS + - DELEGATION + example: ANALYTIC + entity: + type: string + enum: + - ACCOUNT + - STANDARD_REGISTRY + - USER + - BALANCE + - RESTORE + - RECORD + - POLICY + - TOOL + - DOCUMENT + - SCHEMA + - MODULE + - FILE + - CONFIG + - CONTRACT + - WIPE_REQUEST + - WIPE_ADMIN + - WIPE_MANAGER + - WIPER + - POOL + - RETIRE_REQUEST + - RETIRE_ADMIN + - PERMISSIONS + - KEY + - LOG + - MIGRATION + - SETTINGS + - SUGGESTIONS + - TAG + - SYSTEM_SCHEMA + - THEME + - TOKEN + - TRUST_CHAIN + - ROLE + example: POLICY + action: + type: string + enum: + - ALL + - READ + - CREATE + - UPDATE + - DELETE + - REVIEW + - AUDIT + - EXECUTE + - MANAGE + - ASSIGNED + - PUBLISHED + - ASSIGNED_AND_PUBLISHED + example: READ + disabled: + type: boolean + example: false + dependOn: + example: + - POLICIES_POLICY_READ + type: array + items: + type: string + required: + - name + - category + - entity + - action + - disabled + - dependOn + AssignPolicyDTO: + type: object + properties: + policyIds: + example: + - '000000000000000000000001' + type: array + items: + type: string + assign: + type: boolean + example: true + required: + - policyIds + - assign diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index 08de700092..26a7f5be8c 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -51,6 +51,8 @@ * [➗ MRV Splitting Logic](guardian/architecture/mrv-splitting-logic.md) * [🔑 Internal (with Vault)Signing Sequence Diagram](guardian/architecture/internal-with-vault-signing-sequence-diagram.md) * [🔥 FireBlocks Signing Sequence Diagram](guardian/architecture/fireblocks-signing-sequence-diagram.md) +* [📇 Global Indexer](guardian/global-indexer/README.md) + * [💻 Indexer User Guide](guardian/global-indexer/indexer-user-guide.md) * [🗄️ Standard Registry](guardian/standard-registry/README.md) * [🛠️ Schemas](guardian/standard-registry/schemas/README.md) * [📂 Available Schema Types](guardian/standard-registry/schemas/available-schema-types.md) @@ -361,8 +363,8 @@ * [📁 Project Comparison](guardian/standard-registry/project-comparison/README.md) * [💻 Project Comparison using UI](guardian/standard-registry/project-comparison/project-comparison-using-ui.md) * [⚙️ Project Comparison APIs](guardian/standard-registry/project-comparison/project-comparison-apis/README.md) - * [Comparing Documents](guardian/standard-registry/project-comparison/project-comparison-apis/comparing-documents.md) - * [Retrieves all categories](guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-categories.md) + * [Comparing Project Data Documents](guardian/standard-registry/project-comparison/project-comparison-apis/comparing-documents.md) + * [Comparing VP Documents - V1](guardian/standard-registry/project-comparison/project-comparison-apis/comparing-vp-documents-v1.md) * [Retrieves all Properties](guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-properties.md) * [Search Projects by filters](guardian/standard-registry/project-comparison/project-comparison-apis/search-projects-by-filters.md) * [🔑 Selective Disclosure](guardian/standard-registry/selective-disclosure/README.md) @@ -415,6 +417,22 @@ * [🔥 FireBlocks Raw Signing](guardian/standard-registry/fireblocks-raw-signing/README.md) * [Fireblocks signing in Guardian UI](guardian/standard-registry/fireblocks-raw-signing/fireblocks-signing-in-guardian-ui.md) * [Getting Keys from FireBlocks UI](guardian/standard-registry/fireblocks-raw-signing/getting-keys-from-fireblocks-ui.md) + * [🙍 Roles & Permissions](guardian/standard-registry/roles-and-permissions/README.md) + * [💻 Roles and Permissions User Guide](guardian/standard-registry/roles-and-permissions/roles-and-permissions-user-guide.md) + * [⚙️ APIs related to Roles & Permissions](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/README.md) + * [Returns list of all permissions](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-permissions.md) + * [Returns list of all roles](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-roles.md) + * [Creates a New Role](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/creates-a-new-role.md) + * [Updates Role Configuration](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-role-configuration.md) + * [Deletes Role](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/deletes-role.md) + * [Setting Default Role](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/setting-default-role.md) + * [Returns list of all users for whom the current user can change the role](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-users-for-whom-the-current-user-can-change-the-role.md) + * [Retrieves information about the user (roles, permissions assigned policies)](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/retrieves-information-about-the-user-roles-permissions-assigned-policies.md) + * [Updates User Roles (only SR)](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-user-roles-only-sr.md) + * [Returns list of all Policies](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-policies.md) + * [Assigns Policies to a User - Only SR](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/assigns-policies-to-a-user-only-sr.md) + * [Updates user roles (for ordinary uses)](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-user-roles-for-ordinary-uses.md) + * [Assigns policies to a user (for ordinary users)](guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/assigns-policies-to-a-user-for-ordinary-users.md) * [📁 TrustChain](guardian/standard-registry/trustchain/README.md) * [⚙️ TrustChain APIs](guardian/standard-registry/trustchain/trustchain-apis/README.md) * [Requesting](guardian/standard-registry/trustchain/trustchain-apis/requesting.md) @@ -575,6 +593,7 @@ * [🥇 Carbon Sequestration through Accelerated Carbonation of Concrete Aggregate](guardian/demo-guide/carbon-offsets/gold-standard-carbon-sequestration-through-accelerated-carbonation-of-concrete-aggregate.md) * [🏭 AMS-I.D: Grid Connected Renewable Electricity Generation – v.18.0](guardian/demo-guide/carbon-offsets/ams-i.d-grid-connected-renewable-electricity-generation-v.18.0.md) * [🏭 PWRM0002 : Plastic Waste Recycling Methodology](guardian/demo-guide/carbon-offsets/pwrm0002-plastic-waste-recycling.md) + * [🍚 Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation](guardian/demo-guide/carbon-offsets/methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md) * [🏭 Carbon Emissions](guardian/demo-guide/carbon-emissions/README.md) * [🏡 Remote Work GHG Policy](guardian/demo-guide/carbon-emissions/remote-work-ghg-policy/README.md) * [📖 Introduction to Remote Work GHG](guardian/demo-guide/carbon-emissions/remote-work-ghg-policy/introduction-to-remote-work-ghg.md) diff --git a/docs/guardian/architecture/architecture-2.md b/docs/guardian/architecture/architecture-2.md index f1f3fe024a..0e3179fa4a 100644 --- a/docs/guardian/architecture/architecture-2.md +++ b/docs/guardian/architecture/architecture-2.md @@ -4,4 +4,4 @@ description: This Diagram represents all the micro services at a very high level # 🔺 High Level Architecture -
+
diff --git a/docs/guardian/architecture/fireblocks-signing-sequence-diagram.md b/docs/guardian/architecture/fireblocks-signing-sequence-diagram.md index 93497e22ec..e8ec044e23 100644 --- a/docs/guardian/architecture/fireblocks-signing-sequence-diagram.md +++ b/docs/guardian/architecture/fireblocks-signing-sequence-diagram.md @@ -1,3 +1,3 @@ # 🔥 FireBlocks Signing Sequence Diagram -
+
diff --git a/docs/guardian/architecture/schema-architecture.md b/docs/guardian/architecture/schema-architecture.md index fbe53c60b3..573add52d7 100644 --- a/docs/guardian/architecture/schema-architecture.md +++ b/docs/guardian/architecture/schema-architecture.md @@ -1,3 +1,13 @@ # 👏 Policies,Projects and Topics Mapping Architecture +**Note:** + +Guardian data migration is supported for published Policy instances which are yet to generate any data, i.e. are 'empty'. + +As visible from the below Topic Architecture diagram, for each published Policy instance, irrespective of it being a new version of existing Policy or a new Policy altogether, a corresponding new Topic is created in Hedera. This action is coupled with a notification message sent to an appropriate topic, for the former it is the 'new version' message which is posted into the top-level original Policy Topic, for the latter it is the 'new policy' message which is posted into the Standard Registry Topic. + +When Policy instance data is migrated into a new Policy instance, Guardian traverses all corresponding Topics and reposts all the messages, and resubmits all the previously generated documents into the new Topic structure (belonging to the new Policy instance). The documents may also be re-signed by the new Standard Registry if they have been modified (extended) during migration. Each of the messages and documents refer to original message/document in the corresponding "evidence" section of the document JSON. + +Thus, the newly migrated data is useable as a stand-alone data tree and is backward compatible with all existing Guardian and 3rd party tools, while at the same time the original trail of documents is referenced and accessible which allows for incontrovertible trail of evidence for data provenance. +
diff --git a/docs/guardian/demo-guide/carbon-offsets/gold-standard-carbon-sequestration-through-accelerated-carbonation-of-concrete-aggregate.md b/docs/guardian/demo-guide/carbon-offsets/gold-standard-carbon-sequestration-through-accelerated-carbonation-of-concrete-aggregate.md index c5abdad9a8..6375762226 100644 --- a/docs/guardian/demo-guide/carbon-offsets/gold-standard-carbon-sequestration-through-accelerated-carbonation-of-concrete-aggregate.md +++ b/docs/guardian/demo-guide/carbon-offsets/gold-standard-carbon-sequestration-through-accelerated-carbonation-of-concrete-aggregate.md @@ -1,4 +1,4 @@ -# 🥇 Gold Standard Carbon Sequestration through Accelerated Carbonation of Concrete Aggregate +# 🥇 Carbon Sequestration through Accelerated Carbonation of Concrete Aggregate ## Table of Contents @@ -83,7 +83,7 @@ Carbon sequestration projects play a crucial role in addressing global climate c ### Policy Workflow -
+
### Policy Guide diff --git a/docs/guardian/demo-guide/carbon-offsets/methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md b/docs/guardian/demo-guide/carbon-offsets/methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md new file mode 100644 index 0000000000..d94664d92a --- /dev/null +++ b/docs/guardian/demo-guide/carbon-offsets/methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md @@ -0,0 +1,170 @@ +# 🍚 Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation + +## Table of Contents + +[Introduction](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#introduction) + +[Key Features](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#key-features) + +[Potential Impact and Benefits](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#potential-impact-and-benefits) + +[Demo Video](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#demo-video) + +[Policy Workflow](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#policy-workflow) + +[Policy Guide](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#policy-guide) + +[Available Roles](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#available-roles) + +[Important Documents & Schemas](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#important-documents-and-schemas) + +[Token (Verified Emission Reductions)](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#token-verified-emission-reductions) + +[Step By Step](methane-emission-reduction-by-adjusted-water-management-practice-in-rice-cultivation.md#step-by-step) + +## Introduction + +The Methane Emission Reduction in Rice Cultivation methodology offers a comprehensive approach to mitigating greenhouse gas emissions associated with rice production. Rice cultivation accounts for approximately 8% of agricultural greenhouse gas emissions globally, primarily due to methane emissions. This methodology addresses this issue by implementing various measures to reduce methane generation during rice cultivation. + +## Key Features + +* Water Regime Optimization: By transitioning from continuously flooded conditions to intermittently flooded conditions or shortening the period of flooded conditions, this methodology reduces the anaerobic decomposition of organic matter, thereby lowering methane emissions. +* Alternate Wetting and Drying (AWD) Method: AWD method allows for periodic drying and re-flooding of rice fields, creating aerobic conditions that inhibit methane production. +* Aerobic Rice Cultivation Methods: Adopting aerobic rice cultivation techniques further promotes aerobic conditions in the soil, minimizing methane emissions. +* Direct-Seeded Rice (DSR) Cultivation: Switching from transplanted to direct-seeded rice helps in reducing methane emissions by altering the water management practices and organic matter decomposition dynamics. + +## Potential Impact and Benefits + +* Implementing this methodology not only contributes to mitigating climate change by reducing methane emissions but also offers additional benefits: +* Income Generation for Farmers: By participating in emission reduction activities, farmers can generate additional income through the sale of carbon credits, contributing to their livelihoods. +* Corporate Sustainability Goals: Companies can use purchased carbon credits to offset their emissions and meet sustainability targets, including Scope 3 emissions related to their supply chains. +* Global Food Security: Sustainable rice production practices help safeguard local economies and ensure food security for millions of people worldwide, without compromising agricultural productivity. + +## Demo Video + +[Youtube](https://www.youtube.com/watch?v=UjngB\_hnUUs) + +## Policy Workflow + +
+ + + +
+ +## Policy Guide + +This policy is published to Hedera network and can either be imported via Github (.policy file) or IPFS timestamp. + +## Available Roles + +* **Project Proponent** - The project proponent is responsible for executing the emission reduction project. The project proponent must adhere to the requirements outlined by Gold Standard’s Methodology for Methane Emission Reduction by Adjusted Water Management Practice in Rice Cultivation. Upon successful verification, the project proponent receives VERs as an incentive for their emission reduction activities. +* **Gold Standard Verification and Validation Body (GS-VVB)** - The VVB plays a critical role in independently verifying and validating the project data submitted by the project proponent. They thoroughly assess the project's emission reductions potential, methodologies, and adherence to the policy guidelines. Based on their evaluation, the VVB either approves or rejects the project for registration and certification. +* **Registry (Gold Standard)** – With Gold Standard as the registry they take on responsibilities that encompass project intake, pipeline management, and final review of project descriptions and monitoring reports. This process ensures that emissions reduction projects meet the highest standards before credits are issued. + +## Important Documents & Schemas + +1. Key Project Information - Key Information regarding the project activities and project developers. +2. Project Design Document - The project design document (PDD) is used by project developers to submit documentation for certification purposes. +3. Stakeholder Consultation – The aim of the stakeholder consultation is to meaningfully engage stakeholders and collect feedback. +4. Emission Reductions – The standard and simplified emission reductions form will collect all data that is required to calculate the projects reductions. +5. Annual Report - An annual report will be submitted with the monitoring report. This annual report will collect information about any changes that have occurred. +6. Monitoring Report – This monitoring report will cover information from all previous schemas allowing the project developer to make updates as needed. + +## Token (Verified Emission Reductions) + +Verified Emission Reductions (VER), each Gold Standard VER represents one metric ton of carbon dioxide equivalent (CO2e) emissions that the project has reduced or removed. + +## Step by Step + +1. Log in as the Standard Registry and import the policy either by file or through IPFS timestamp by selecting the third button at the top right. + +
+ +
+ +
+ +
+ +2. Once the policy has successfully imported, you will be redirected to the policy configurator. To start using the policy you must first change the status of the policy from “Draft” to “Dry Run” or “Publish”, then select the “Register” or “Go” button. This can be done through the policy configurator page or though the “Manage Policies” page. + +
+ +
+ +
+ +3. Create additional users by clicking the “Create User” button. + +
+ +4. Once the users have been created go to each one and assign the appropriate role (i.e. Project Proponent, VVB, Technical Advisory Committee and NGO Supporters). + +
+ +5. The VVB can provide their name or the name they would like users to see when reviewing projects. + +
+ +6. Log in as the SR and select the “Approve VVB” tab to view the documents submitted by the VVB. The SR can approve their request by clicking on the “Approve" button. + +
+ +7. Log in as the Project Proponent and create a new project by clicking on the "New Project" button. + +
+ +8. You can input all the project details and data associated with the project in the “New Project” form. + +
+ +9. The next step is to access the SR profile and include the project in the ”Project pipeline”. This can be achieved by navigating to the "Project Pipeline" tab and clicking on the "List" option. + +
+ +10. The Project Proponent assigns the VVB to verify it by navigating to the “Projects” tab and selecting the dropdown under “Assign”. + +
+ +11. After successfully assigning the VVB to the project, the next step is to access the VVB profile and click on the "validate" option located in the "Projects" tab. After clicking on the "Validate" button, the VVb needs to add a comment. + +
+ +
+ +12. Log in as Project Proponent and create a monitoring report by clicking on the “Add Report” button then fill out the monitoring report form. + +
+ +
+ +13. Log in as the VVB and click the “Monitoring Reports” tab to review the document submitted by the Project Proponent. After reviewing the monitoring report by selecting “View Document”, the VVB can select “Verify”. + +
+ +14. Log in as the SR to review the monitoring report by selecting the “View Document” button in the “Monitoring Reports” tab. The SR can approve the monitoring report by selecting “Approve”. + +
+ +15. After reviewing the monitoring report, the Technical Advisory Committee can provide comments. Log in as theTechnical Advisory Committee and create a comment by clicking on the “Comment” button in the “Monitoring Reports” tab. + +
+ +16. Similarly, you can leave comments for the “NGO supporter” profile. Log in as the NGO supporter and create a comment by clicking on the “Comment” button in the “Monitoring Reports” tab. + +
+ +17. The SR after approval of the monitoring report can start the minting process by clicking on the “mint” button. + +
+ +18. Once the minting process is completed, you can view the token amount by navigating to the “Token History” tab + +
+ +19. The TrustChain can also be viewed by clicking on the “View TrustChain” button. + +
+ +
diff --git a/docs/guardian/global-indexer/README.md b/docs/guardian/global-indexer/README.md new file mode 100644 index 0000000000..8383339e8f --- /dev/null +++ b/docs/guardian/global-indexer/README.md @@ -0,0 +1,2 @@ +# 📇 Global Indexer + diff --git a/docs/guardian/global-indexer/indexer-user-guide.md b/docs/guardian/global-indexer/indexer-user-guide.md new file mode 100644 index 0000000000..855d68ae5f --- /dev/null +++ b/docs/guardian/global-indexer/indexer-user-guide.md @@ -0,0 +1,158 @@ +# 💻 Indexer User Guide + +Indexer provides a global search facility on the landing page, and other pages’ headers. It allows users to find information by matching string values. + +For example ‘Project Description’ will find all entities which include ‘Project’ word or ‘Description’ word. + +To find an exact phrase you need to use double quotes, e.g. type something like ‘“Project Description”’. Words can be excluded by typing ‘-’ symbol in the request. All searched entities have metadata in Hedera messages, search looks at policy message IDs, schema names, schema message IDs, VC/VP document content/values, schema properties, schema field names, etc… + +### Landing page includes following information: + +* _Registries_, _Methodologies_, _Total Documents_, _Total Issuance_. All cards are clickable. Also there is an ability to check charts with count and date. +* Project Locations section : shows locations of projects on the world map, all points are clickable. + +![image4.png](<../../.gitbook/assets/0 (14).png>) + +![image8.png](<../../.gitbook/assets/1 (16).png>) + +### Indexer UI sections: + +Accounts, Methodologies, Documents, Others. + +Sections have specific grids for displaying data and filters: + +* Accounts: + + * Standard Registries + * Registry Users + + +* Methodologies: + + * Policies + * Tools + * Modules + * Schemas + * Tokens + * Roles + + +* Documents: + + * DIDs + * VCs + * VPs + + +* Others: + * NFTs + * Topics + * Contracts + +Example of the grid displaying data is seen on the screenshot below: + +![](<../../.gitbook/assets/2 (18).png>) + +Majority of the grids provide capability to search by keyword filter, which has some differences in comparison to global search. In the search failed it uses ‘chips’, i.e. type and press ENTER to add values, to search for specified items based on an AND condition. + +For example, searching for. schema by typing ‘Project’ and ‘Description’ will find all schemas which contain ‘Project’ and ‘Description’ strings. + +![image10.png](<../../.gitbook/assets/3 (15).png>) + +Each grid includes special details page: + +* Standard Registry details page have following tabs: + * Overview - a common information. + * Activity - activity of SR (VCs, VPs, Policies, Roles, Tools, Modules, Tokens, Users). All activity cards are clickable and it will navigate the user to the appropriate grid with correctly applied filters. + +![image6.png](<../../.gitbook/assets/4 (13).png>) + +* Raw Data - raw message data. + +![image11.png](<../../.gitbook/assets/5 (16).png>) + +* Policy details page have the following tabs: + * Overview - general information with link to Standard Registry. + +![image7.png](<../../.gitbook/assets/6 (15).png>) + +* Activity - activity in policy (VCs, VPs, Roles, Creating schemas). All activity cards are clickable and it will navigate you to the appropriate table with necessary filters. +* Raw Data - raw message data. + +Tool details has the following tabs: + +* Overview - a common information. +* Content- content of Tool (Using in policies, Tool Schemas). All content cards are clickable and it will navigate you to the appropriate table with necessary filters. +* Raw Data - raw message data. + +Module details has the following tabs: + +* Overview - a common information. +* Raw Data - raw message data. + +Schema details has the following tabs: + +* Overview - a common information with link to policy. +* Document - schema document data. +* Tree - schema tree. All nodes here are clickable, upon clicking they open the associated schema pages. + +![image1.png](<../../.gitbook/assets/7 (15).png>) + +* Activity - schema activity (VCs, VPs) +* Raw Data - raw message data. + +Token details has the following tabs: + +* Overview - a common information with link to NFTs. +* Raw Data - raw token data. + +Role details has the following tabs: + +* Overview - a common information with link to policy. +* Activity - role activity (VCs) +* Raw Data - raw message data. + +DID details has the following tabs: + +* Overview - a common information. +* Document - DID Document +* Raw Data - raw token data. + +VC details has the following tabs: + +* Overview - a common information with link to policy. +* Document - VC document data. It can be represented in two forms JSON and Document form. + +![image2.png](<../../.gitbook/assets/8 (16).png>) + +* History - document history since it was created. +* Relationships - document relationships with links to policy, roles, schemas, standard registry, other documents. + +![image9.png](<../../.gitbook/assets/9 (14).png>) + +* Raw Data - raw message data. + +VP details includes following tabs: + +* Overview - a common information with link to policy. +* Document - VP document data. +* History - document history since it was created. +* Relationships - document relationships with links to policy, roles, schemas, standard registry, other documents. + +![image5.png](<../../.gitbook/assets/10 (15).png>) + +* Raw Data - raw message data. + +NFT details includes following tabs: + +* Overview - a common information. +* History - NFT transactions history since it was minted +* Raw Data - raw NFT data. + +Topic details includes following tabs: + +* Overview - a common information with link to parent topic Id. +* Content - topic content with all entity types such as VCs, VPs, Schema, Policies, Tools, Modules, DIDs, Contracts, etc… +* Raw Data - raw topic data. + +Synchronization of all entity data starts one time per hour, but it can be changed by changing environment variables. diff --git a/docs/guardian/standard-registry/fireblocks-raw-signing/fireblocks-signing-in-guardian-ui.md b/docs/guardian/standard-registry/fireblocks-raw-signing/fireblocks-signing-in-guardian-ui.md index 6a891935dd..5a3a9f8fe8 100644 --- a/docs/guardian/standard-registry/fireblocks-raw-signing/fireblocks-signing-in-guardian-ui.md +++ b/docs/guardian/standard-registry/fireblocks-raw-signing/fireblocks-signing-in-guardian-ui.md @@ -1,6 +1,66 @@ # Fireblocks signing in Guardian UI -1\. Enabling Fireblocks Remote Signing: +## Operations remotely signed by the keys in Fireblocks + +1. **submitMessage** + +All messages sent to Hedera are signed with the Fireblocks keys using [Raw Signing](https://developers.fireblocks.com/docs/raw-message-signing-overview) method. + +## Operations signed by Operator ID/Key + +OPERATOR\_KEY is used for generating DIDs and signing documents as Fireblocks API does not support such operations. + +Additionally OPERATOR\_KEY is used for the following operations: + +• newToken + +• newTopic + +{% hint style="info" %} +**Note:** creation of new topics and/or tokens require freeze/wipe keys as a parameter in the API call. Guardian uses OPERATOR\_KEY. +{% endhint %} + +• wipe + +• grantKyc + +• revokeKyc + +• associate + +• dissociate + +• freeze + +• unfreeze + +• updateToken + +• deleteToken + +{% hint style="info" %} +**Note**: Similarly to the creation of topics/tokens, Hedera SDK API require explicit specification of keys as a parameter. +{% endhint %} + +• transfer + +• transferNFT + +• newAccount + +• newTreasury + +{% hint style="info" %} +**Note**: These operations require specific transaction type not supported by RAW SIGNING. +{% endhint %} + +• balance + +{% hint style="info" %} +**Note**: Guardian uses the account specified in the UI +{% endhint %} + +## Enabling Fireblocks Remote Signing: When creating a user, select the “**Use fireblocks signing**” option and populate the following fields with values from your Fireblocks account configuration: @@ -9,6 +69,6 @@ When creating a user, select the “**Use fireblocks signing**” option and pop * Fireblocks API Key * Fireblocks Private Key -![](../../../.gitbook/assets/0.png) +![](<../../../.gitbook/assets/0 (1).png>) Users, which have been created with this option enabled to remotely sign their Hedera transactions using Fireblocks API instead of via the built-in Guardian signing workflow. diff --git a/docs/guardian/standard-registry/live-project-data-migration/live-project-data-migration-ui.md b/docs/guardian/standard-registry/live-project-data-migration/live-project-data-migration-ui.md index 38a94961d7..574341ffce 100644 --- a/docs/guardian/standard-registry/live-project-data-migration/live-project-data-migration-ui.md +++ b/docs/guardian/standard-registry/live-project-data-migration/live-project-data-migration-ui.md @@ -2,38 +2,50 @@ ## 1. Exporting Policy Data -We have added button "**Export policy data**" for published policies and dry-run policies. +Data migration feature allows transfer of some or all policy artefacts and/or state into another policy (on the same of different Guardian instance) by exporting into and then importing the .data file. -By clicking you will get all policy data in the **.data** file. +To perform export press ‘**Export policy data**’ option in the Policy menu. -Then you can use this file for migrating data to another policy. +The operation is available for dry-run and published policies.
## 2. Importing/Exporting Keys for Dry Run Policies -We have added buttons "**Export/Import virtual keys**" for dry-run policies. +To export/import virtual users’ keys and DID documents for dry-run policies press the corresponding ‘**Export virtual keys**’ or ‘**Import virtual keys**’ menu options. -By clicking you will get virtual user’s keys and DID Documents. - -Then you can import it in another dry-run policy, where data was migrated from current policy. +They can be imported into another dry-run policy, where data was migrated from the current policy.
## 3. Migrating Policy State to Destination Policy -We have added "**Migrate policy state**" flag to migrate data dialog. +If Policy state flag is set in the ‘**Migrate Data**’ dialog, the entire policy state gets migrated into the destination policy. -When you enable it, you will migrate all policy state to destination policy (includes block states - steps, timers, multi-sign, split documents, aggregate documents, etc...) +This includes block states - steps, timers, multi-signs, split documents, aggregate documents, etc... To get information about different steps in the below migration process screen, please refer to [Migration Process](../discontinuing-policy-workflow/apis-related-to-discontinuing-policy-workflow/migratepolicy-data.md)
-## 4. Change VC Document during Migration +## 4. Migrate Retire Pools + +When ‘Migrate retire pools’ flag is selected, the migration process will re-create all selected existing retirement pools, from all contracts created by the ‘current’ instance, in the new retirement contract. The UI allows the user to map policy tokens and select the new retire contract. + +
+ +## 5. Change VC Document during Migration We have added ability to change VC which will be migrated by clicking on "**Edit document**" button under operations column:
+ +When state migration is selected block mapping could be used to optimize the migrations. + +
+ +For Policies with dynamic tokens mapping of token templates might be required. + +
diff --git a/docs/guardian/standard-registry/notifications/user-guide.md b/docs/guardian/standard-registry/notifications/user-guide.md index 71a750915e..b2960f443f 100644 --- a/docs/guardian/standard-registry/notifications/user-guide.md +++ b/docs/guardian/standard-registry/notifications/user-guide.md @@ -9,7 +9,7 @@ Added notification icon and also tooltip with count of unread notifications: -![image4.png](<../../../.gitbook/assets/0 (1) (1) (1).png>) +![image4.png](<../../../.gitbook/assets/0 (1) (1) (1) (1).png>) ### 2. View : diff --git a/docs/guardian/standard-registry/policies/library-of-policy-examples/creating-and-using-roles.md b/docs/guardian/standard-registry/policies/library-of-policy-examples/creating-and-using-roles.md index 910227d63d..2248c2eba3 100644 --- a/docs/guardian/standard-registry/policies/library-of-policy-examples/creating-and-using-roles.md +++ b/docs/guardian/standard-registry/policies/library-of-policy-examples/creating-and-using-roles.md @@ -8,7 +8,7 @@ For a demo example of following steps, here is the policy timestamp: **167516453 1. Switch to the Roles tab -![Roles Tab](<../../../../.gitbook/assets/0 (1) (1) (1) (1).png>) +![Roles Tab](<../../../../.gitbook/assets/0 (1) (1) (1) (1) (1).png>) 2. Create 2 new roles called ‘**Example role 1**_’ and_ ‘_**Example role 2**_’ diff --git a/docs/guardian/standard-registry/policies/library-of-policy-examples/token-operations.md b/docs/guardian/standard-registry/policies/library-of-policy-examples/token-operations.md index e10f04ff34..6ecd7fce75 100644 --- a/docs/guardian/standard-registry/policies/library-of-policy-examples/token-operations.md +++ b/docs/guardian/standard-registry/policies/library-of-policy-examples/token-operations.md @@ -14,7 +14,7 @@ Second step of policy execution is data input and document submission. To enable To enable document submission we will use document input block (**requestVcDocumentBlock**) and document persistence block (**sendToGuardianBlock**) -![creating new\_user\_registration Block](<../../../../.gitbook/assets/0 (1) (1) (1) (1) (1).png>) +![creating new\_user\_registration Block](<../../../../.gitbook/assets/0 (1) (1) (1) (1) (1) (1).png>) **Please see** [**example 2**](data-input-via-forms-using-roles-to-partition-user-activities..md) **for the more in-depth guide of working with documents in Guardian Policies.** diff --git a/docs/guardian/standard-registry/project-comparison/project-comparison-apis/comparing-vp-documents-v1.md b/docs/guardian/standard-registry/project-comparison/project-comparison-apis/comparing-vp-documents-v1.md new file mode 100644 index 0000000000..995cfda9fc --- /dev/null +++ b/docs/guardian/standard-registry/project-comparison/project-comparison-apis/comparing-vp-documents-v1.md @@ -0,0 +1,5 @@ +# Comparing VP Documents - V1 + +{% swagger src="../../../../.gitbook/assets/swagger (2).yaml" path="/projects/compare/documents" method="post" %} +[swagger (2).yaml](<../../../../.gitbook/assets/swagger (2).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-categories.md b/docs/guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-categories.md deleted file mode 100644 index 0a8c5a5f42..0000000000 --- a/docs/guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-categories.md +++ /dev/null @@ -1,20 +0,0 @@ -# Retrieves all categories - -{% swagger method="get" path="" baseUrl="/policies/categories" summary="Get all categories" %} -{% swagger-description %} -Get all categories -{% endswagger-description %} - -{% swagger-response status="200: OK" description="Successful Operation" %} - -{% endswagger-response %} - -{% swagger-response status="500: Internal Server Error" description="Internal Server Error" %} -``` -{ - "code": 0, - "message": "string" -} -``` -{% endswagger-response %} -{% endswagger %} diff --git a/docs/guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-properties.md b/docs/guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-properties.md index f99200ff66..ef3bf7cafd 100644 --- a/docs/guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-properties.md +++ b/docs/guardian/standard-registry/project-comparison/project-comparison-apis/retrieves-all-properties.md @@ -1,20 +1,7 @@ # Retrieves all Properties -{% swagger method="get" path="" baseUrl="/projects/properties" summary="Get all properties" %} -{% swagger-description %} -Get all properties -{% endswagger-description %} +## Get all properties -{% swagger-response status="200: OK" description="Successful Operation" %} - -{% endswagger-response %} - -{% swagger-response status="500: Internal Server Error" description="Internal Server Error" %} -``` -{ - "code": 0, - "message": "string" -} -``` -{% endswagger-response %} +{% swagger src="../../../../.gitbook/assets/swagger (2).yaml" path="/projects/properties" method="get" %} +[swagger (2).yaml](<../../../../.gitbook/assets/swagger (2).yaml>) {% endswagger %} diff --git a/docs/guardian/standard-registry/project-comparison/project-comparison-using-ui.md b/docs/guardian/standard-registry/project-comparison/project-comparison-using-ui.md index 082c92069e..bb100a4897 100644 --- a/docs/guardian/standard-registry/project-comparison/project-comparison-using-ui.md +++ b/docs/guardian/standard-registry/project-comparison/project-comparison-using-ui.md @@ -47,6 +47,12 @@ On this page, users will find a comparative table displaying selected project fi
+### VP Document Comparison + +Document comparison includes examination of the VP documents generated by both projects. This works in the same way as comparing documents from the UI. + +
+ ## 2. Demo Video Coming Soon diff --git a/docs/guardian/standard-registry/roles-and-permissions/README.md b/docs/guardian/standard-registry/roles-and-permissions/README.md new file mode 100644 index 0000000000..e44942ced4 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/README.md @@ -0,0 +1,2 @@ +# 🙍 Roles & Permissions + diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/README.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/README.md new file mode 100644 index 0000000000..eb58911e7c --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/README.md @@ -0,0 +1,2 @@ +# ⚙️ APIs related to Roles & Permissions + diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/assigns-policies-to-a-user-for-ordinary-users.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/assigns-policies-to-a-user-for-ordinary-users.md new file mode 100644 index 0000000000..303bdcc836 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/assigns-policies-to-a-user-for-ordinary-users.md @@ -0,0 +1,5 @@ +# Assigns policies to a user (for ordinary users) + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/users/{username}/policies/delegate" method="post" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/assigns-policies-to-a-user-only-sr.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/assigns-policies-to-a-user-only-sr.md new file mode 100644 index 0000000000..3d1c400eaf --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/assigns-policies-to-a-user-only-sr.md @@ -0,0 +1,5 @@ +# Assigns Policies to a User - Only SR + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/users/{username}/policies/assign" method="post" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/creates-a-new-role.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/creates-a-new-role.md new file mode 100644 index 0000000000..6f9c9e8dcc --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/creates-a-new-role.md @@ -0,0 +1,5 @@ +# Creates a New Role + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/roles" method="post" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/deletes-role.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/deletes-role.md new file mode 100644 index 0000000000..f47684bc26 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/deletes-role.md @@ -0,0 +1,5 @@ +# Deletes Role + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/roles/{id}" method="delete" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/retrieves-information-about-the-user-roles-permissions-assigned-policies.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/retrieves-information-about-the-user-roles-permissions-assigned-policies.md new file mode 100644 index 0000000000..ec85998aa6 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/retrieves-information-about-the-user-roles-permissions-assigned-policies.md @@ -0,0 +1,5 @@ +# Retrieves information about the user (roles, permissions assigned policies) + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/users/{username}" method="get" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-permissions.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-permissions.md new file mode 100644 index 0000000000..636bcd2576 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-permissions.md @@ -0,0 +1,5 @@ +# Returns list of all permissions + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions" method="get" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-policies.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-policies.md new file mode 100644 index 0000000000..90d2d31d42 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-policies.md @@ -0,0 +1,5 @@ +# Returns list of all Policies + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/users/{username}/policies" method="get" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-roles.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-roles.md new file mode 100644 index 0000000000..3ecf03f48f --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-roles.md @@ -0,0 +1,5 @@ +# Returns list of all roles + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/roles" method="get" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-users-for-whom-the-current-user-can-change-the-role.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-users-for-whom-the-current-user-can-change-the-role.md new file mode 100644 index 0000000000..fcbde20fc2 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/returns-list-of-all-users-for-whom-the-current-user-can-change-the-role.md @@ -0,0 +1,5 @@ +# Returns list of all users for whom the current user can change the role + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/users" method="get" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/setting-default-role.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/setting-default-role.md new file mode 100644 index 0000000000..511bd002cc --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/setting-default-role.md @@ -0,0 +1,5 @@ +# Setting Default Role + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/roles/default" method="post" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-role-configuration.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-role-configuration.md new file mode 100644 index 0000000000..52a04f9070 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-role-configuration.md @@ -0,0 +1,5 @@ +# Updates Role Configuration + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/roles/{id}" method="put" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-user-roles-for-ordinary-uses.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-user-roles-for-ordinary-uses.md new file mode 100644 index 0000000000..4835b842d9 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-user-roles-for-ordinary-uses.md @@ -0,0 +1,5 @@ +# Updates user roles (for ordinary uses) + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/users/{username}/delegate" method="put" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-user-roles-only-sr.md b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-user-roles-only-sr.md new file mode 100644 index 0000000000..fd0f1c08cd --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/apis-related-to-roles-and-permissions/updates-user-roles-only-sr.md @@ -0,0 +1,5 @@ +# Updates User Roles (only SR) + +{% swagger src="../../../../.gitbook/assets/swagger (4).yaml" path="/permissions/users/{username}" method="put" %} +[swagger (4).yaml](<../../../../.gitbook/assets/swagger (4).yaml>) +{% endswagger %} diff --git a/docs/guardian/standard-registry/roles-and-permissions/roles-and-permissions-user-guide.md b/docs/guardian/standard-registry/roles-and-permissions/roles-and-permissions-user-guide.md new file mode 100644 index 0000000000..6359b29a08 --- /dev/null +++ b/docs/guardian/standard-registry/roles-and-permissions/roles-and-permissions-user-guide.md @@ -0,0 +1,122 @@ +# 💻 Roles and Permissions User Guide + +Roles and permissions allow for precise configuration of user access rights to Guardian functionality. + +1. **Permissions format: {category}\_{entity}\_{action}** + +* _**POLICIES\_POLICY\_READ**_ – Controls read access to policies +* _**POLICIES\_POLICY\_EXECUTE**_ – Controls access to running policies as a USER. When this access is given to a Guardian user, this user can assume a role within the policy and perform actions in the policy workflow. +* _**TOKENS\_TOKEN\_EXECUTE**_ – Controls access to viewing tokens (balance, associate, disassociate) +* _**POLICIES\_POLICY\_MANAGE**_ – Controls access to running policy as an OWNER. +* _**TOKENS\_TOKEN\_MANAGE**_ – Controls access to managing tokens (balance, grant-kyc, freeze, unfreeze) + +## **1. Managing roles** + +### **1.1 Create** + +Standard Registry user with the corresponding permission (_PERMISSIONS\_ROLE\_CREATE_) can create new roles and populate them with the needed permissions. + +![](<../../../.gitbook/assets/0 (15).png>) + +![](<../../../.gitbook/assets/1 (17).png>) + +\ +Roles consist of a set of permissions which allow uses corresponding actions in the Guardian instance. + +![Рисунок 6](<../../../.gitbook/assets/2 (19).png>) + +### **1.2. Edit** + +
+ +### **1.3 Delete** + +
+ +### **1.4 Default** + +Default role would be applied to all new users automatically upon their registration. + +![Рисунок 8](<../../../.gitbook/assets/5 (17).png>) + +### **2.5 Access** + +Special configuration option (permission) which controls user access access to specific policies. + +* _**ACCESS\_POLICY\_ALL** –_ when set, the user will have access to all policies of the SR +* _**ACCESS\_POLICY\_ASSIGNED –**_ when set, the user will only have access to policies assigned to the user +* _**ACCESS\_POLICY\_PUBLISHED –**_ when set, the user will only have access to published policies of the SR +* _**ACCESS\_POLICY\_ASSIGNED\_AND\_PUBLISHED –**_ when set, the user will only have access to policies assigned to the user, which are also published. + +![](<../../../.gitbook/assets/6 (16).png>) + +### **2.6 Delegate** + +Special permission option which enables uses to transfer their roles (i.e. to delegate, preserving their own rights as per the role as well) to other users.\ +Any user with the permission _**DELEGATION\_ROLE\_MANAGE**_ can enable access to all or a subset of roles and/or policies (but only for those the user has access to), for other users. + +![Рисунок 10](<../../../.gitbook/assets/7 (16).png>) + +## **2. Assigning roles and policies** + +### **2.1 Roles** + +_User Management_ page provides facilities to configure user roles + +![](<../../../.gitbook/assets/8 (17).png>) + +![](<../../../.gitbook/assets/9 (15).png>) + +Administrator can see summary of the permissions from all roles enabled for the user: + +![](<../../../.gitbook/assets/10 (16).png>) + +### **2.2 Policies** + +On the policy page administrator can assign specific policies to be accessible for the user. (If _**ACCESS\_POLICY\_ASSIGNED**_ permission is used.) + +
+ +### **2.3 Delegate** + +Similarly to how SR can configure roles and policies, uses with the _**DELEGATION\_ROLE\_MANAGE**_ permission can delegate its access to policies to other users. the list of the options however is limited by the rules and policies assigned to it by SR and/or other users. + +## **3. Messages** + +When a role is created, edited, or deleted a corresponding message will be posted to the SR’s Hedera topic in the following format: + +``` +{ +"id": "b5aee339-860f-4702-a916-4d4dca93a885", +"status": "ISSUE", +"type": "Guardian-Role-Document", +"action": "create-role", +"lang": "en-US", +"issuer": "did:hedera:testnet:BJDCUTd8gFSaFwW4w7Tw8dbx7DfnkfLjJ14s2dquesS9_0.0.3579393", +"encodedData": false, +"cid": "QmUCXmE3KAe16xHEc9sr8vnPaNESKpzDGH8yKCf6jaDevp", +"uri": "ipfs://QmUCXmE3KAe16xHEc9sr8vnPaNESKpzDGH8yKCf6jaDevp", +"uuid": "6c0c8a7a-afef-40e2-900b-560a60945bfe", +"name": "Role name", +"description": "Role name" +} +``` + +When the list of rules assigned to the user is updated, the following messages posted to the SR’s Hedera topic + +``` +{ +"id": "88865f04-b599-4189-abb0-499de1de2c7d", +"status": "ISSUE", +"type": "User-Permissions", +"action": "set-role", +"lang": "en-US", +"issuer": "did:hedera:testnet:BJDCUTd8gFSaFwW4w7Tw8dbx7DfnkfLjJ14s2dquesS9_0.0.3579393", +"encodedData": false, +"cid": "QmfNFrWcPuoiSqMjGqogqTXRDRMEY6s68wsxU6fXTRLsAF", +"uri": "ipfs://QmfNFrWcPuoiSqMjGqogqTXRDRMEY6s68wsxU6fXTRLsAF", +"user": "did:hedera:testnet:EEGXZeZvcYmWj4e7cyPoDUi7rcRzkGbLBmziRrd7yrQm_0.0.3579393" +} +``` + +The messages are accompanied by assigned VC document with the list of permissions the role contains diff --git a/e2e-tests/cypress/e2e/api-tests/accounts/getSession.cy.js b/e2e-tests/cypress/e2e/api-tests/accounts/getSession.cy.js index 7bf81dfcf3..036941b1a9 100644 --- a/e2e-tests/cypress/e2e/api-tests/accounts/getSession.cy.js +++ b/e2e-tests/cypress/e2e/api-tests/accounts/getSession.cy.js @@ -16,9 +16,7 @@ context('Accounts', { tags: '@accounts' }, () => { expect(response.status).to.eq(STATUS_CODE.OK) expect(response.body).to.have.property('id') expect(response.body).to.have.property('username', 'StandardRegistry') - expect(response.body).to.have.property('password') expect(response.body).to.have.property('did') - expect(response.body).to.have.property('walletToken') expect(response.body).to.have.property('hederaAccountId') expect(response.body).to.have.property('role') }) @@ -50,7 +48,6 @@ context('Accounts', { tags: '@accounts' }, () => { }).then((response) => { expect(response.status).to.eq(200) expect(response.body).to.have.property('id') - expect(response.body).to.have.property('password') expect(response.body.role).eq('USER') }) }) diff --git a/e2e-tests/cypress/e2e/api-tests/accounts/postRegister.cy.js b/e2e-tests/cypress/e2e/api-tests/accounts/postRegister.cy.js index 12e188af76..db34233d32 100644 --- a/e2e-tests/cypress/e2e/api-tests/accounts/postRegister.cy.js +++ b/e2e-tests/cypress/e2e/api-tests/accounts/postRegister.cy.js @@ -182,7 +182,7 @@ context("Accounts", { tags: "@accounts" }, () => { }, failOnStatusCode:false, }).then(response => { - expect(response.status).eql(STATUS_CODE.ERROR); + expect(response.status).eql(STATUS_CODE.CONFLICT); expect(response.body.message).eql("An account with the same name already exists."); }); }); diff --git a/e2e-tests/cypress/support/api/api-const.js b/e2e-tests/cypress/support/api/api-const.js index 6dae67ee76..c42027068b 100644 --- a/e2e-tests/cypress/support/api/api-const.js +++ b/e2e-tests/cypress/support/api/api-const.js @@ -15,6 +15,7 @@ export const STATUS_CODE = { UNAUTHORIZED: 401, FORBIDDEN: 403, NOT_FOUND: 404, + CONFLICT: 409, UNPROCESSABLE: 422, ERROR: 500, }; diff --git a/frontend/package.json b/frontend/package.json index b4bf24ace6..8ec3a79193 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -74,5 +74,5 @@ "test": "ng test", "watch": "ng build --watch --configuration development --output-path ../www-data" }, - "version": "2.24.1" + "version": "2.25.0" } diff --git a/frontend/src/app/app-routing.module.ts b/frontend/src/app/app-routing.module.ts index b62199df1f..a1578394d5 100644 --- a/frontend/src/app/app-routing.module.ts +++ b/frontend/src/app/app-routing.module.ts @@ -1,14 +1,14 @@ import { Injectable, NgModule } from '@angular/core'; -import { CanActivate, Router, RouterModule, Routes } from '@angular/router'; -import { IUser, UserRole } from '@guardian/interfaces'; -import { of } from 'rxjs'; +import { ActivatedRouteSnapshot, CanActivate, Router, RouterModule, RouterStateSnapshot, Routes, UrlTree } from '@angular/router'; +import { IUser, Permissions, UserRole } from '@guardian/interfaces'; +import { Observable, of } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { AuditComponent } from './views/audit/audit.component'; import { HomeComponent } from './views/home/home.component'; import { UserProfileComponent } from './views/user-profile/user-profile.component'; import { LoginComponent } from './views/login/login.component'; import { RegisterComponent } from './views/register/register.component'; -import { RootConfigComponent } from './views/root-config/root-config.component'; +import { RootProfileComponent } from './views/root-profile/root-profile.component'; import { SchemaConfigComponent } from './views/schemas/schemas.component'; import { TokenConfigComponent } from './views/token-config/token-config.component'; import { TrustChainComponent } from './views/trust-chain/trust-chain.component'; @@ -40,120 +40,71 @@ import { ContractConfigComponent } from './modules/contract-engine/configs/contr import { UserContractConfigComponent } from './modules/contract-engine/configs/user-contract-config/user-contract-config.component'; import { AnnotationBlockComponent } from './modules/project-comparison/component/annotation-block/annotation-block.component'; import { ProjectsComparisonTableComponent } from './modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component'; +import { RolesViewComponent } from './views/roles/roles-view.component'; +import { UsersManagementComponent } from './views/user-management/user-management.component'; +import { UsersManagementDetailComponent } from './views/user-management-detail/user-management-detail.component'; -const USER_IS_NOT_RA = "Page is avaliable for admin only"; - -class Guard { - private router: Router; - private auth: AuthService; - private role: UserRole; - private defaultPage: string; +@Injectable({ + providedIn: 'root' +}) +export class PermissionsGuard { constructor( - router: Router, - auth: AuthService, - role: UserRole, - defaultPage: string + private readonly router: Router, + private readonly auth: AuthService ) { - this.router = router; - this.auth = auth - this.role = role; - this.defaultPage = defaultPage } - canActivate() { - return this.auth.sessions().pipe( - map((res: IUser | null) => { - if (res) { - if (res.role != this.role) { - this.router.navigate(['/info'], - { - skipLocationChange: true, - queryParams: { - message: USER_IS_NOT_RA - } - } - ); - return false; - } - return true; - } else { - return this.router.parseUrl(this.defaultPage); - } - }), - catchError(() => { - return of(this.router.parseUrl(this.defaultPage)); - }) - ) + private goToInfo(): boolean { + this.router.navigate(['/info'], { + skipLocationChange: true, + queryParams: { + title: 'Access Restricted', + message: 'You don\'t have permission to view this page.' + } + }); + return false; + } + + private goToDefault(defaultPage: string | undefined): UrlTree { + return this.router.parseUrl(defaultPage || '/login'); } - canActivateChild() { + canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + const roles: string[] | undefined = route.data.roles; + const permissions: string[] | undefined = route.data.permissions; + const defaultPage: string | undefined = route.data.defaultPage; return this.auth.sessions().pipe( - map((res: IUser | null) => { - if (res) { - if (res.role != this.role) { - this.router.navigate(['/info'], - { - skipLocationChange: true, - queryParams: { - message: USER_IS_NOT_RA + map((user: IUser | null) => { + if (user) { + if (roles) { + if (!user.role || roles.indexOf(user.role) === -1) { + return this.goToInfo(); + } + } + if (permissions) { + if (user.permissions) { + for (const permission of user.permissions) { + if (permissions.indexOf(permission) !== -1) { + return true; } } - ); - return false; + } + return this.goToInfo(); } return true; } else { - return this.router.parseUrl(this.defaultPage); + return this.goToDefault(defaultPage); } }), catchError(() => { - return of(this.router.parseUrl(this.defaultPage)); + return of(this.goToDefault(defaultPage)); }) ) } -} - -@Injectable({ - providedIn: 'root' -}) -export class UserGuard extends Guard implements CanActivate { - constructor(router: Router, auth: AuthService) { - super(router, auth, UserRole.USER, '/login'); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class StandardRegistryGuard extends Guard implements CanActivate { - constructor(router: Router, auth: AuthService) { - super(router, auth, UserRole.STANDARD_REGISTRY, '/login'); - } -} -@Injectable({ - providedIn: 'root' -}) -export class AuditorGuard extends Guard implements CanActivate { - constructor(router: Router, auth: AuthService) { - super(router, auth, UserRole.AUDITOR, '/login'); - } -} - -@Injectable({ - providedIn: 'root' -}) -export class ServicesStatusGuard implements CanActivate { - constructor( - private router: Router, - private status: WebSocketService - ) { - } - - canActivate() { - return true; - // return this.status.IsServicesReady(); + canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + return this.canActivate(route, state); } } @@ -163,45 +114,363 @@ const routes: Routes = [ { path: 'task/:id', component: AsyncProgressComponent }, { path: 'notifications', component: NotificationsComponent }, - { path: 'user-profile', component: UserProfileComponent, canActivate: [UserGuard, ServicesStatusGuard] }, - { path: 'policy-search', component: PolicySearchComponent, canActivate: [UserGuard, ServicesStatusGuard] }, - { path: 'tokens-user', component: ListOfTokensUserComponent, canActivate: [UserGuard, ServicesStatusGuard] }, - { path: 'retirement-user', component: UserContractConfigComponent, canActivate: [UserGuard, ServicesStatusGuard] }, + { + path: 'user-profile', + component: UserProfileComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.USER] + } + }, - { path: 'config', component: RootConfigComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, - { path: 'tokens', component: TokenConfigComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, - { path: 'contracts', component: ContractConfigComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, - { path: 'schemas', component: SchemaConfigComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, - { path: 'artifacts', component: ArtifactConfigComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, { - path: 'admin', component: AdminHeaderComponent, canActivate: [StandardRegistryGuard], canActivateChild: [StandardRegistryGuard], + path: 'policy-search', + component: PolicySearchComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.USER] + } + }, + { + path: 'tokens-user', + component: ListOfTokensUserComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.USER + ], + permissions: [ + Permissions.TOKENS_TOKEN_EXECUTE + ] + } + }, + { + path: 'retirement-user', + component: UserContractConfigComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.USER], + permissions: [Permissions.CONTRACTS_CONTRACT_READ] + } + }, + + { + path: 'config', + component: RootProfileComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY] + } + }, + { + path: 'tokens', + component: TokenConfigComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.TOKENS_TOKEN_READ + ] + } + }, + { + path: 'contracts', + component: ContractConfigComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY, UserRole.USER], + permissions: [ + Permissions.CONTRACTS_CONTRACT_READ, + Permissions.CONTRACTS_CONTRACT_CREATE, + Permissions.CONTRACTS_CONTRACT_DELETE, + Permissions.CONTRACTS_WIPE_REQUEST_READ, + Permissions.CONTRACTS_WIPE_REQUEST_UPDATE, + Permissions.CONTRACTS_WIPE_REQUEST_REVIEW, + Permissions.CONTRACTS_WIPE_REQUEST_DELETE, + Permissions.CONTRACTS_WIPE_ADMIN_CREATE, + Permissions.CONTRACTS_WIPE_ADMIN_DELETE, + Permissions.CONTRACTS_WIPE_MANAGER_CREATE, + Permissions.CONTRACTS_WIPE_MANAGER_DELETE, + Permissions.CONTRACTS_WIPER_CREATE, + Permissions.CONTRACTS_WIPER_DELETE, + Permissions.CONTRACTS_POOL_UPDATE, + Permissions.CONTRACTS_POOL_DELETE + ] + } + }, + { + path: 'schemas', + component: SchemaConfigComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.SCHEMAS_SCHEMA_READ, + Permissions.SCHEMAS_SYSTEM_SCHEMA_READ + ] + } + }, + { + path: 'artifacts', + component: ArtifactConfigComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.ARTIFACTS_FILE_READ + ] + } + + }, + { + path: 'admin', component: AdminHeaderComponent, + canActivate: [PermissionsGuard], + canActivateChild: [PermissionsGuard], children: [ { path: 'status', component: ServiceStatusComponent }, { path: 'settings', component: SettingsViewComponent }, { path: 'logs', component: LogsViewComponent }, { path: 'about', component: AboutViewComponent } - ] + ], + data: { + roles: [UserRole.STANDARD_REGISTRY], + permissions: [ + Permissions.SETTINGS_SETTINGS_READ, + Permissions.LOG_LOG_READ + ] + } + }, + { + path: 'status', + component: ServiceStatusComponent + }, + { + path: 'settings', + component: SettingsViewComponent + }, + { + path: 'audit', + component: AuditComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.AUDITOR] + } + }, + { + path: 'trust-chain', + component: TrustChainComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.AUDITOR] + } }, - { path: 'status', component: ServiceStatusComponent }, - { path: 'settings', component: SettingsViewComponent }, - { path: 'audit', component: AuditComponent, canActivate: [AuditorGuard, ServicesStatusGuard] }, - { path: 'trust-chain', component: TrustChainComponent, canActivate: [AuditorGuard, ServicesStatusGuard] }, - { path: 'policy-viewer', component: PoliciesComponent, canActivate: [ServicesStatusGuard] }, - { path: 'policy-viewer/:id', component: PolicyViewerComponent, canActivate: [ServicesStatusGuard] }, - { path: 'policy-configuration', component: PolicyConfigurationComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, - { path: 'modules', component: ModulesListComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, - { path: 'tools', component: ToolsListComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, - { path: 'suggestions', component: SuggestionsConfigurationComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, + { + path: 'policy-viewer', + component: PoliciesComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY, UserRole.USER], + permissions: [ + Permissions.POLICIES_POLICY_READ, + Permissions.POLICIES_POLICY_EXECUTE + ] + } + }, + { + path: 'policy-viewer/:id', + component: PolicyViewerComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY, UserRole.USER], + permissions: [ + Permissions.POLICIES_POLICY_EXECUTE + ] + } + }, + { + path: 'policy-configuration', + component: PolicyConfigurationComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.POLICIES_POLICY_UPDATE + ] + } + }, + { + path: 'module-configuration', + component: PolicyConfigurationComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.MODULES_MODULE_UPDATE + ] + } + }, + { + path: 'tool-configuration', + component: PolicyConfigurationComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.TOOLS_TOOL_READ + ] + } + }, + { + path: 'modules', + component: ModulesListComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.MODULES_MODULE_READ + ] + } + }, + { + path: 'tools', + component: ToolsListComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.TOOLS_TOOL_READ + ] + } + }, + { + path: 'suggestions', + component: SuggestionsConfigurationComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY], + permissions: [Permissions.SUGGESTIONS_SUGGESTIONS_READ] + } + }, + + { + path: 'compare', + component: CompareComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY, UserRole.USER] + } + }, + { + path: 'search', + component: SearchPoliciesComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY], + permissions: [Permissions.POLICIES_POLICY_READ] + } + }, + { + path: 'record-results', + component: RecordResultsComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY], + permissions: [Permissions.POLICIES_RECORD_ALL] + } + }, - { path: 'compare', component: CompareComponent, canActivate: [ServicesStatusGuard] }, - { path: 'search', component: SearchPoliciesComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, - { path: 'record-results', component: RecordResultsComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, + { + path: 'branding', + component: BrandingComponent, + canActivate: [PermissionsGuard], + data: { + roles: [UserRole.STANDARD_REGISTRY], + permissions: [Permissions.BRANDING_CONFIG_UPDATE] + } + }, - { path: 'branding', component: BrandingComponent, canActivate: [StandardRegistryGuard, ServicesStatusGuard] }, + { + path: 'projects', + component: AnnotationBlockComponent, + data: { title: 'GUARDIAN / Project Overview' } + }, + { + path: 'projects/comparison', + component: ProjectsComparisonTableComponent, + data: { title: 'GUARDIAN / Project Comparison' } + }, - {path: 'projects', component: AnnotationBlockComponent, data: {title: 'GUARDIAN / Project Overview'}}, - {path: 'projects/comparison', component: ProjectsComparisonTableComponent, data: {title: 'GUARDIAN / Project Comparison'}}, + { + path: 'roles', + component: RolesViewComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.PERMISSIONS_ROLE_CREATE, + Permissions.PERMISSIONS_ROLE_UPDATE, + Permissions.PERMISSIONS_ROLE_DELETE, + ] + } + }, + { + path: 'user-management', + component: UsersManagementComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.DELEGATION_ROLE_MANAGE, + Permissions.PERMISSIONS_ROLE_MANAGE + ] + } + }, + { + path: 'user-management/:id', + component: UsersManagementDetailComponent, + canActivate: [PermissionsGuard], + data: { + roles: [ + UserRole.STANDARD_REGISTRY, + UserRole.USER + ], + permissions: [ + Permissions.DELEGATION_ROLE_MANAGE, + Permissions.PERMISSIONS_ROLE_MANAGE + ] + } + }, { path: '', component: HomeComponent }, { path: 'info', component: InfoComponent }, diff --git a/frontend/src/app/app.component.scss b/frontend/src/app/app.component.scss index 192971bc38..d01f227bb3 100644 --- a/frontend/src/app/app.component.scss +++ b/frontend/src/app/app.component.scss @@ -31,6 +31,46 @@ body { font-size: 14px; } +::ng-deep .toast-container { + max-height: 70vh; + overflow: auto; + padding-top: 210px; + + &>div { + position: absolute !important; + bottom: 0px; + } + + &>div:nth-last-child(6) { + position: absolute !important; + bottom: 200px; + } + + &>div:nth-last-child(5) { + position: absolute !important; + bottom: 160px; + } + + &>div:nth-last-child(4) { + position: absolute !important; + bottom: 120px; + } + + &>div:nth-last-child(3) { + position: absolute !important; + bottom: 80px; + } + + &>div:nth-last-child(2) { + position: absolute !important; + bottom: 40px; + } + + &>div:nth-last-child(1) { + position: relative !important; + } +} + .app { width: 100vw; min-height: 100vh; diff --git a/frontend/src/app/app.module.ts b/frontend/src/app/app.module.ts index dd5a4745f6..4743f43502 100644 --- a/frontend/src/app/app.module.ts +++ b/frontend/src/app/app.module.ts @@ -5,7 +5,7 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HTTP_INTERCEPTORS, HttpClientJsonpModule, HttpClientModule } from '@angular/common/http'; import { CommonModule } from '@angular/common'; import { ToastrModule } from 'ngx-toastr'; -import { AppRoutingModule, AuditorGuard, StandardRegistryGuard, UserGuard } from './app-routing.module'; +import { AppRoutingModule, PermissionsGuard } from './app-routing.module'; import { AppComponent } from './app.component'; import { SchemaHelper } from '@guardian/interfaces'; import { CheckboxModule } from 'primeng/checkbox'; @@ -33,13 +33,14 @@ import { TagsService } from './services/tag.service'; import { MapService } from './services/map.service'; import { WizardService } from './modules/policy-engine/services/wizard.service'; import { NotificationService } from './services/notify.service'; +import { PermissionsService } from './services/permissions.service'; //Views import { UserProfileComponent } from './views/user-profile/user-profile.component'; import { LoginComponent } from './views/login/login.component'; import { HomeComponent } from './views/home/home.component'; import { HeaderComponent } from './views/header/header.component'; import { RegisterComponent } from './views/register/register.component'; -import { RootConfigComponent } from './views/root-config/root-config.component'; +import { RootProfileComponent } from './views/root-profile/root-profile.component'; import { TokenConfigComponent } from './views/token-config/token-config.component'; import { AuditComponent } from './views/audit/audit.component'; import { TrustChainComponent } from './views/trust-chain/trust-chain.component'; @@ -51,6 +52,9 @@ import { ServiceStatusComponent } from './views/admin/service-status/service-sta import { SchemaConfigComponent } from './views/schemas/schemas.component'; import { BrandingDialogComponent } from './components/branding-dialog/branding-dialog.component'; import { NotificationsComponent } from './views/notifications/notifications.component'; +import { RolesViewComponent } from './views/roles/roles-view.component'; +import { UsersManagementComponent } from './views/user-management/user-management.component'; +import { UsersManagementDetailComponent } from './views/user-management-detail/user-management-detail.component'; //Components import { InfoComponent } from './components/info/info/info.component'; import { BrandingComponent } from './views/branding/branding.component'; @@ -127,7 +131,7 @@ import { UseWithServiceDirective } from './directives/use-with-service.directive HomeComponent, HeaderComponent, RegisterComponent, - RootConfigComponent, + RootProfileComponent, TokenConfigComponent, AuditComponent, TrustChainComponent, @@ -160,6 +164,9 @@ import { UseWithServiceDirective } from './directives/use-with-service.directive OnlyForDemoDirective, TokenDialogComponent, UseWithServiceDirective, + RolesViewComponent, + UsersManagementComponent, + UsersManagementDetailComponent ], imports: [ BrowserModule, @@ -206,9 +213,6 @@ import { UseWithServiceDirective } from './directives/use-with-service.directive exports: [], providers: [ WebSocketService, - UserGuard, - StandardRegistryGuard, - AuditorGuard, AuthService, ProfileService, TokenService, @@ -237,6 +241,8 @@ import { UseWithServiceDirective } from './directives/use-with-service.directive RecordService, CompareStorage, ProjectComparisonService, + PermissionsService, + PermissionsGuard, { provide: GET_SCHEMA_NAME, useValue: SchemaHelper.getSchemaName diff --git a/frontend/src/app/components/info/info/info.component.css b/frontend/src/app/components/info/info/info.component.css deleted file mode 100644 index 0445ad2b4e..0000000000 --- a/frontend/src/app/components/info/info/info.component.css +++ /dev/null @@ -1,8 +0,0 @@ -.info-message { - position: absolute; - left: 50%; - top: 50%; - transform: translate(-50%, -50%); - font-size: 20px; - color: darkgrey; -} \ No newline at end of file diff --git a/frontend/src/app/components/info/info/info.component.html b/frontend/src/app/components/info/info/info.component.html index dfeb971f16..d059a48fc6 100644 --- a/frontend/src/app/components/info/info/info.component.html +++ b/frontend/src/app/components/info/info/info.component.html @@ -1 +1,4 @@ -
{{message}}
+
+
{{title}}
+
{{message}}
+
\ No newline at end of file diff --git a/frontend/src/app/components/info/info/info.component.scss b/frontend/src/app/components/info/info/info.component.scss new file mode 100644 index 0000000000..5c5e3a1aa6 --- /dev/null +++ b/frontend/src/app/components/info/info/info.component.scss @@ -0,0 +1,20 @@ + + +.info-content { + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + + .info-title { + font-size: 24px; + color: rgb(53, 53, 53); + text-align: center; + margin-bottom: 18px; + } + + .info-message { + font-size: 20px; + color: darkgrey; + } +} \ No newline at end of file diff --git a/frontend/src/app/components/info/info/info.component.ts b/frontend/src/app/components/info/info/info.component.ts index 49414b2cb9..b58a90a326 100644 --- a/frontend/src/app/components/info/info/info.component.ts +++ b/frontend/src/app/components/info/info/info.component.ts @@ -5,12 +5,13 @@ import { Subscription } from 'rxjs'; @Component({ selector: 'app-info', templateUrl: './info.component.html', - styleUrls: ['./info.component.css'] + styleUrls: ['./info.component.scss'] }) export class InfoComponent implements OnInit, OnDestroy { private subscription = new Subscription(); + public title: string = ''; public message: string = ''; constructor(private route: ActivatedRoute) { @@ -19,6 +20,7 @@ export class InfoComponent implements OnInit, OnDestroy { ngOnInit(): void { this.subscription.add( this.route.queryParams.subscribe(params => { + this.title = params['title']; this.message = params['message']; }) ); diff --git a/frontend/src/app/components/token-dialog/token-dialog.component.scss b/frontend/src/app/components/token-dialog/token-dialog.component.scss index fa456bec5a..38f83b9643 100644 --- a/frontend/src/app/components/token-dialog/token-dialog.component.scss +++ b/frontend/src/app/components/token-dialog/token-dialog.component.scss @@ -49,4 +49,4 @@ .token-configuration { padding: 0 1.5rem; overflow-y: auto; -} \ No newline at end of file +} diff --git a/frontend/src/app/modules/analytics/compare-document/compare-document.component.html b/frontend/src/app/modules/analytics/compare-document/compare-document.component.html index 433eed7543..672fe23d86 100644 --- a/frontend/src/app/modules/analytics/compare-document/compare-document.component.html +++ b/frontend/src/app/modules/analytics/compare-document/compare-document.component.html @@ -12,7 +12,7 @@
- +
Description
@@ -20,13 +20,13 @@
-
-
-
Policy Documents
+
{{ comparationLabels.documentsLabel }}
-
- Blocks are equal, including their child blocks. + {{ comparationLabels.equalFullLabel }}
- blocks are equal, but their child blocks are different. + {{ comparationLabels.equalNotFullLabel }}
- blocks are of the same type and are partially equal. + {{ comparationLabels.sameTypeLabel }}
- Blocks are absent in the other Policy. + {{ comparationLabels.differentLabel }}
-
{{row.number}}
@@ -95,12 +95,12 @@
-
-
-
@@ -158,9 +158,9 @@ {{ column.label }} - {{ row.data[column.name] }} @@ -241,20 +241,20 @@
- Documents: + Documents:
unfold_more unfold_less
-
-
{{field.label}}: @@ -276,12 +276,12 @@
Attributes:
-
-
{{attribute.label}}: @@ -293,8 +293,8 @@
-
+
- \ No newline at end of file + diff --git a/frontend/src/app/modules/analytics/compare-document/compare-document.component.scss b/frontend/src/app/modules/analytics/compare-document/compare-document.component.scss index 07d840bf67..e58e992156 100644 --- a/frontend/src/app/modules/analytics/compare-document/compare-document.component.scss +++ b/frontend/src/app/modules/analytics/compare-document/compare-document.component.scss @@ -871,4 +871,4 @@ div { height: 1px; } -} \ No newline at end of file +} diff --git a/frontend/src/app/modules/analytics/compare-document/compare-document.component.ts b/frontend/src/app/modules/analytics/compare-document/compare-document.component.ts index 1a7d9cce32..c5e4d402d8 100644 --- a/frontend/src/app/modules/analytics/compare-document/compare-document.component.ts +++ b/frontend/src/app/modules/analytics/compare-document/compare-document.component.ts @@ -50,6 +50,9 @@ interface IFieldContext { styleUrls: ['./compare-document.component.scss'] }) export class CompareDocumentComponent implements OnInit { + @Input('disableHeader') disableHeader: boolean = false; + @Input('customColumnSize') customColumnSize: string | null = null; + @Input('comparationType') comparationType = 'policy' @Input('value') value!: any; @Input() type: string = 'tree'; @Input() eventsLvl: string = '1'; @@ -59,7 +62,7 @@ export class CompareDocumentComponent implements OnInit { @Output() change = new EventEmitter(); - public minWidth: number; + public minWidth: number | string; public headers: any[]; public size: number; @@ -79,6 +82,36 @@ export class CompareDocumentComponent implements OnInit { public _systemProp = true; private _pOffset = 30; + get comparationLabels(): any { + switch (this.comparationType) { + case 'policy': { + return { + equalFullLabel: 'Blocks are equal, including their child blocks', + equalNotFullLabel: 'Blocks are equal, but their child blocks are different', + sameTypeLabel: 'Blocks are of the same type and are partially equal.', + differentLabel: 'Blocks are absent in the other Policy.', + documentsLabel: 'Policy Documents' + } + break; + } + + case 'documents': { + return { + equalFullLabel: 'Documents/fields are equal, including nested elements', + equalNotFullLabel: 'Documents/fields are equal, but some nested elements are different', + sameTypeLabel: 'Documents/fields are of the same type, but contain different values', + differentLabel: 'Documents/fields are absent from one of the documents', + documentsLabel: 'Project documents' + } + break; + } + + default: { + return {} + } + } + } + constructor() { this.minWidth = 1600; this.headers = []; @@ -89,7 +122,6 @@ export class CompareDocumentComponent implements OnInit { } ngOnInit() { - } ngOnChanges(changes: SimpleChanges): void { @@ -101,12 +133,14 @@ export class CompareDocumentComponent implements OnInit { onInit() { this.size = this.value.size || 2; this.totals = this.value.totals; - this.minWidth = 770 * this.size; + this.minWidth = (!this.customColumnSize) ? this.size * 770 : 'unset'; - const k = Math.round(100 / this.size); - this._gridStyle = `max(calc(${k}vw - 80px), 680px)`; - for (let i = 1; i < this.size; i++) { - this._gridStyle += ` 35px max(calc(${k}vw - 45px), 720px)`; + if (!this.customColumnSize) { + const k = (this.customColumnSize) ? this.customColumnSize : Math.round(100 / this.size); + this._gridStyle = `max(calc(${k}vw - 80px), 680px)`; + for (let i = 1; i < this.size; i++) { + this._gridStyle += ` 35px max(calc(${k}vw - 45px), 720px)`; + } } this.createHeaders(this.value); diff --git a/frontend/src/app/modules/analytics/compare/compare.component.html b/frontend/src/app/modules/analytics/compare/compare.component.html index 06d9cd3b87..fe0d76b88a 100644 --- a/frontend/src/app/modules/analytics/compare/compare.component.html +++ b/frontend/src/app/modules/analytics/compare/compare.component.html @@ -7,7 +7,7 @@
chevron_left - Policies + Policies
@@ -51,9 +51,9 @@
-
Apply
@@ -76,65 +76,65 @@
-
-
-
-
-
-
-
\ No newline at end of file +
diff --git a/frontend/src/app/modules/analytics/search-policies/search-policies.component.html b/frontend/src/app/modules/analytics/search-policies/search-policies.component.html index 8e4349dfd3..9674e414cb 100644 --- a/frontend/src/app/modules/analytics/search-policies/search-policies.component.html +++ b/frontend/src/app/modules/analytics/search-policies/search-policies.component.html @@ -98,8 +98,15 @@ Tags - + diff --git a/frontend/src/app/modules/analytics/search-policies/search-policies.component.ts b/frontend/src/app/modules/analytics/search-policies/search-policies.component.ts index bcb20ed706..0afc10874e 100644 --- a/frontend/src/app/modules/analytics/search-policies/search-policies.component.ts +++ b/frontend/src/app/modules/analytics/search-policies/search-policies.component.ts @@ -1,6 +1,6 @@ import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; -import { IUser, SchemaHelper, TagType } from '@guardian/interfaces'; +import { IUser, SchemaHelper, TagType, UserPermissions } from '@guardian/interfaces'; import { ProfileService } from 'src/app/services/profile.service'; import { TagsService } from 'src/app/services/tag.service'; import { forkJoin } from 'rxjs'; @@ -18,6 +18,7 @@ import { AnalyticsService } from 'src/app/services/analytics.service'; }) export class SearchPoliciesComponent implements OnInit { public loading: boolean = true; + public user: UserPermissions = new UserPermissions(); public type: any; public policyId: any; public policy: any; @@ -91,6 +92,7 @@ export class SearchPoliciesComponent implements OnInit { const tagSchemas: any[] = value[1] || []; this.owner = profile?.did; this.tagSchemas = SchemaHelper.map(tagSchemas); + this.user = new UserPermissions(profile); this.loadPolicy(); }, (e) => { this.loading = false; diff --git a/frontend/src/app/modules/artifact-engine/artifact-config/artifact-config.component.html b/frontend/src/app/modules/artifact-engine/artifact-config/artifact-config.component.html index d746610a9c..e7d7d188c4 100644 --- a/frontend/src/app/modules/artifact-engine/artifact-config/artifact-config.component.html +++ b/frontend/src/app/modules/artifact-engine/artifact-config/artifact-config.component.html @@ -21,19 +21,27 @@

Artifacts

@@ -60,7 +68,9 @@

Artifacts

-
@@ -96,7 +106,7 @@

Artifacts

-
+ - Detele Artifact + Delete Artifact
diff --git a/frontend/src/app/modules/artifact-engine/artifact-config/artifact-config.component.ts b/frontend/src/app/modules/artifact-engine/artifact-config/artifact-config.component.ts index 1e7734c2e5..cf27972322 100644 --- a/frontend/src/app/modules/artifact-engine/artifact-config/artifact-config.component.ts +++ b/frontend/src/app/modules/artifact-engine/artifact-config/artifact-config.component.ts @@ -1,12 +1,11 @@ import { Component, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { ActivatedRoute, Router } from '@angular/router'; -import { IUser, PolicyType } from '@guardian/interfaces'; +import { IUser, PolicyType, UserPermissions } from '@guardian/interfaces'; import { HttpResponse } from '@angular/common/http'; import { forkJoin } from 'rxjs'; import { PolicyEngineService } from 'src/app/services/policy-engine.service'; import { ProfileService } from 'src/app/services/profile.service'; -import { ConfirmationDialogComponent } from 'src/app/modules/common/confirmation-dialog/confirmation-dialog.component'; import { ArtifactService } from 'src/app/services/artifact.service'; import { ArtifactImportDialog } from '../artifact-import-dialog/artifact-import-dialog.component'; @@ -19,12 +18,13 @@ import { ArtifactImportDialog } from '../artifact-import-dialog/artifact-import- styleUrls: ['./artifact-config.component.css'] }) export class ArtifactConfigComponent implements OnInit { - loading: boolean = true; - isConfirmed: boolean = false; - artifacts: any[] = []; - artifactsCount: any; - columns: string[] = []; - policyArtifactColumns: string[] = [ + public loading: boolean = true; + public user: UserPermissions = new UserPermissions(); + public isConfirmed: boolean = false; + public artifacts: any[] = []; + public artifactsCount: any; + public columns: string[] = []; + public policyArtifactColumns: string[] = [ 'uuid', 'policy', 'name', @@ -32,13 +32,13 @@ export class ArtifactConfigComponent implements OnInit { 'extention', 'delete' ]; - policies: any[] | null; - currentPolicy: any = ''; - pageIndex: number; - pageSize: number; - policyNameById: any = {}; + public policies: any[] | null; + public currentPolicy: any | null = null; + public pageIndex: number; + public pageSize: number; + public policyNameById: any = {}; + public deleteArtifactVisible: boolean = false; private currentArtifact: any; - deleteArtifactVisible: boolean = false; constructor( private profileService: ProfileService, @@ -53,9 +53,7 @@ export class ArtifactConfigComponent implements OnInit { } ngOnInit() { - const policyId = this.route.snapshot.queryParams['policyId']; - this.currentPolicy = policyId && policyId != 'all' ? policyId : ''; - this.loadProfile() + this.loadProfile(); } loadProfile() { @@ -70,13 +68,25 @@ export class ArtifactConfigComponent implements OnInit { const policies: any[] = value[1] || []; this.isConfirmed = !!(profile && profile.confirmed); - this.policies = []; + this.user = new UserPermissions(profile); + + this.policies = [{ + name: 'All', + id: 'all' + }]; for (let i = 0; i < policies.length; i++) { const policy = policies[i]; this.policyNameById[policy.id] = policy.name; this.policies.push(policy); } + const policyId = this.route.snapshot.queryParams['policyId']; + if (policyId) { + this.currentPolicy = this.policies.find((p) => p.id === policyId); + } + if (!this.currentPolicy) { + this.currentPolicy = this.policies[0]; + } this.pageIndex = 0; this.pageSize = 10; this.loadArtifacts(); @@ -88,10 +98,14 @@ export class ArtifactConfigComponent implements OnInit { loadArtifacts() { this.loading = true; - const request = - this.artifact.getArtifacts(this.currentPolicy.id, this.pageIndex, this.pageSize); this.columns = this.policyArtifactColumns; - request.subscribe((artifactResponse: HttpResponse) => { + + const policyId = this.currentPolicy && this.currentPolicy.id !== 'all' ? this.currentPolicy.id : null; + this.artifact.getArtifacts( + policyId, + this.pageIndex, + this.pageSize + ).subscribe((artifactResponse: HttpResponse) => { this.artifacts = artifactResponse.body?.map(item => { const policy = this.policies?.find(policy => policy.id === item.policyId) return Object.assign(item, { @@ -110,11 +124,15 @@ export class ArtifactConfigComponent implements OnInit { onFilter() { this.pageIndex = 0; - this.router.navigate(['/artifacts'], { - queryParams: { - policyId: this.currentPolicy.id ? this.currentPolicy.id : 'all' - } - }); + if (this.currentPolicy && this.currentPolicy.id !== 'all') { + this.router.navigate(['/artifacts'], { + queryParams: { + policyId: this.currentPolicy.id + } + }); + } else { + this.router.navigate(['/artifacts']); + } this.loadArtifacts(); } @@ -132,7 +150,7 @@ export class ArtifactConfigComponent implements OnInit { importArtifacts() { const dialogRef = this.dialog.open(ArtifactImportDialog, { data: { - policyId: this.currentPolicy.id, + policyId: this.currentPolicy?.id, policies: this.policies }, disableClose: true, diff --git a/frontend/src/app/modules/common/async-progress/async-progress.component.ts b/frontend/src/app/modules/common/async-progress/async-progress.component.ts index f74b9b9562..670307c4d0 100644 --- a/frontend/src/app/modules/common/async-progress/async-progress.component.ts +++ b/frontend/src/app/modules/common/async-progress/async-progress.component.ts @@ -159,9 +159,8 @@ export class AsyncProgressComponent implements OnInit, OnDestroy { case TaskAction.RESTORE_USER_PROFILE: case TaskAction.CONNECT_USER: this.wsService.updateProfile(); - this.router.navigate([ - this.userRole === UserRole.USER ? 'user-profile' : 'config', - ], { + const home = this.auth.home(this.userRole); + this.router.navigate([home], { replaceUrl: true, }); return; @@ -182,7 +181,7 @@ export class AsyncProgressComponent implements OnInit, OnDestroy { }); break; case TaskAction.CREATE_TOOL: - this.router.navigate(['policy-configuration'], { + this.router.navigate(['tool-configuration'], { queryParams: { toolId: result, }, @@ -276,7 +275,7 @@ export class AsyncProgressComponent implements OnInit, OnDestroy { ); this._configurationErrors.set(tool?.id, errors); } - this.router.navigate(['policy-configuration'], { + this.router.navigate(['tool-configuration'], { queryParams: { toolId: tool?.id }, @@ -328,9 +327,8 @@ export class AsyncProgressComponent implements OnInit, OnDestroy { switch (this.action) { case TaskAction.RESTORE_USER_PROFILE: case TaskAction.CONNECT_USER: - this.router.navigate([ - this.userRole === UserRole.USER ? 'user-profile' : 'config', - ], { + const home = this.auth.home(this.userRole); + this.router.navigate([home], { replaceUrl: true, }); break; diff --git a/frontend/src/app/modules/common/confirmation-dialog/confirmation-dialog.component.css b/frontend/src/app/modules/common/confirmation-dialog/confirmation-dialog.component.css index f1586e9ac2..740d031b16 100644 --- a/frontend/src/app/modules/common/confirmation-dialog/confirmation-dialog.component.css +++ b/frontend/src/app/modules/common/confirmation-dialog/confirmation-dialog.component.css @@ -1,5 +1,6 @@ .content { overflow: visible; + min-width: 500px; } :host ::ng-deep { @@ -18,11 +19,52 @@ } .mat-dialog-actions { - margin-top: 16px; - padding: 0; display: flex; justify-content: end; gap: 16px; + border-top: 1px solid #E1E7EF; + padding: 20px 0px; + margin-top: 30px; + } + + .toolbar-btn-primary .p-button { + background: var(--color-primary); + border: 1px solid var(--color-primary); + font-family: Inter, sans-serif; + font-size: 1px; + font-style: normal; + font-weight: 500; + margin-left: 10px; + height: 40px; + padding: 8px; + border-radius: 8px; + color: white; + + .p-button-label { + font-size: 14px; + padding: 0px 10px; + color: white !important; + } + } + + .toolbar-btn-outlined .p-button { + background: white; + border: 1px solid var(--color-primary); + font-family: Inter, sans-serif; + font-size: 1px; + font-style: normal; + font-weight: 500; + margin-left: 10px; + height: 40px; + padding: 8px; + border-radius: 8px; + color: var(--color-primary); + + .p-button-label { + font-size: 14px; + padding: 0px 10px; + color: var(--color-primary) !important; + } } } diff --git a/frontend/src/app/modules/common/confirmation-dialog/confirmation-dialog.component.html b/frontend/src/app/modules/common/confirmation-dialog/confirmation-dialog.component.html index d0c5214526..fa333f41aa 100644 --- a/frontend/src/app/modules/common/confirmation-dialog/confirmation-dialog.component.html +++ b/frontend/src/app/modules/common/confirmation-dialog/confirmation-dialog.component.html @@ -8,11 +8,15 @@

{{dialogTitle}}

- +
diff --git a/frontend/src/app/modules/contract-engine/configs/contract-config/contract-config.component.html b/frontend/src/app/modules/contract-engine/configs/contract-config/contract-config.component.html index 41a36afcb9..7d3084a5b6 100644 --- a/frontend/src/app/modules/contract-engine/configs/contract-config/contract-config.component.html +++ b/frontend/src/app/modules/contract-engine/configs/contract-config/contract-config.component.html @@ -47,8 +47,15 @@ Tags - + diff --git a/frontend/src/app/modules/contract-engine/configs/contract-config/contract-config.component.ts b/frontend/src/app/modules/contract-engine/configs/contract-config/contract-config.component.ts index f2cfaca197..fbb1032edb 100644 --- a/frontend/src/app/modules/contract-engine/configs/contract-config/contract-config.component.ts +++ b/frontend/src/app/modules/contract-engine/configs/contract-config/contract-config.component.ts @@ -1,6 +1,6 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; -import { ContractType, IUser, SchemaHelper, TagType, Token, } from '@guardian/interfaces'; +import { ContractType, IUser, SchemaHelper, TagType, Token, UserPermissions, } from '@guardian/interfaces'; import { ProfileService } from 'src/app/services/profile.service'; import { TokenService } from 'src/app/services/token.service'; import { ContractService } from 'src/app/services/contract.service'; @@ -23,6 +23,7 @@ import { Validators } from '@angular/forms'; styleUrls: ['./contract-config.component.css'], }) export class ContractConfigComponent implements OnInit, OnDestroy { + public user: UserPermissions = new UserPermissions(); contracts: any[] | null; columns: string[] = []; role!: any; @@ -245,6 +246,7 @@ export class ContractConfigComponent implements OnInit, OnDestroy { this.role = profile ? profile.role : null; this.owner = profile?.did; this.tagSchemas = SchemaHelper.map(tagSchemas); + this.user = new UserPermissions(profile); if (this.isConfirmed) { this.loadAllContracts(); diff --git a/frontend/src/app/modules/policy-engine/helpers/compare-modules-dialog/compare-modules-dialog.component.html b/frontend/src/app/modules/policy-engine/helpers/compare-modules-dialog/compare-modules-dialog.component.html index 77193f2e93..22285687e0 100644 --- a/frontend/src/app/modules/policy-engine/helpers/compare-modules-dialog/compare-modules-dialog.component.html +++ b/frontend/src/app/modules/policy-engine/helpers/compare-modules-dialog/compare-modules-dialog.component.html @@ -21,16 +21,16 @@
- + >
diff --git a/frontend/src/app/modules/policy-engine/modules-list/modules-list.component.html b/frontend/src/app/modules/policy-engine/modules-list/modules-list.component.html index c72eadd34b..f9315b2292 100644 --- a/frontend/src/app/modules/policy-engine/modules-list/modules-list.component.html +++ b/frontend/src/app/modules/policy-engine/modules-list/modules-list.component.html @@ -24,24 +24,24 @@

Modules

+ class="toolbar-btn"> add Create a Module + class="toolbar-btn"> file_open Import + styleClass="p-button-outlined"> compare Compare @@ -66,9 +66,15 @@

Modules

{{ module.name }} {{ module.description }} - +
Draft
@@ -76,21 +82,28 @@

Modules

- +
-
+
{ this.modules = policiesResponse.body || []; this.modulesCount = Number(policiesResponse.headers.get('X-Total-Count') || this.modules.length); + this.loadTagsData(); + }, (e) => { + this.loading = false; + }); + } - const ids = this.modules.map(e => e.id); + private loadTagsData() { + if (this.user.TAGS_TAG_READ) { + const ids = this.modules?.map(e => e.id) || []; this.tagsService.search(this.tagEntity, ids).subscribe((data) => { if (this.modules) { for (const policy of this.modules) { @@ -131,9 +140,11 @@ export class ModulesListComponent implements OnInit, OnDestroy { console.error(e.error); this.loading = false; }); - }, (e) => { - this.loading = false; - }); + } else { + setTimeout(() => { + this.loading = false; + }, 500); + } } public onPage(event: any) { @@ -307,7 +318,7 @@ export class ModulesListComponent implements OnInit, OnDestroy { } this.informService.errorMessage(text.join(''), 'The module is invalid'); this._configurationErrors.set(element.uuid, errors); - this.router.navigate(['policy-configuration'], { + this.router.navigate(['module-configuration'], { queryParams: { moduleId: element.uuid, }, diff --git a/frontend/src/app/modules/policy-engine/policies/policies.component.html b/frontend/src/app/modules/policy-engine/policies/policies.component.html index d7365e0809..c02f29eb98 100644 --- a/frontend/src/app/modules/policy-engine/policies/policies.component.html +++ b/frontend/src/app/modules/policy-engine/policies/policies.component.html @@ -1,6 +1,6 @@ -
+
- {{ role === "USER" ? "List of Policies" : "Manage Policies" }} + {{ user.POLICIES_POLICY_MANAGE ? "Manage Policies" : "List of Policies" }}
@@ -11,7 +11,7 @@ -
+
+ class="button ml-8" + label="Apply Filters" + pButton> -
-
- +
+ + + + +
- -
-
- -
- share + [label]="['PUBLISH', 'DISCONTINUED'].includes(policy.status) ? 'Open' : 'Dry run'" + [routerLink]="['/policy-viewer', policy.id]" + class="p-button btn-go-policy" + pButton + type="button">
-
+
+ +
+
@@ -340,28 +350,42 @@ - - + + - + - + - -
{ + return true; + } +}, { + id: 'description', + permissions: (user: UserPermissions) => { + return true; + } +}, { + id: 'topic', + permissions: (user: UserPermissions) => { + return ( + user.POLICIES_POLICY_CREATE || + user.POLICIES_POLICY_UPDATE || + user.POLICIES_POLICY_REVIEW || + user.POLICIES_POLICY_DELETE + ) + } +}, { + id: 'roles', + permissions: (user: UserPermissions) => { + return !( + user.POLICIES_POLICY_CREATE || + user.POLICIES_POLICY_UPDATE || + user.POLICIES_POLICY_REVIEW || + user.POLICIES_POLICY_DELETE + ) + } +}, { + id: 'version', + permissions: (user: UserPermissions) => { + return true; + } +}, { + id: 'tags', + permissions: (user: UserPermissions) => { + return true; + } +}, { + id: 'tokens', + permissions: (user: UserPermissions) => { + return user.TOKENS_TOKEN_READ; + } +}, { + id: 'schemas', + permissions: (user: UserPermissions) => { + return user.SCHEMAS_SCHEMA_READ; + } +}, { + id: 'status', + permissions: (user: UserPermissions) => { + return true; + } +}, { + id: 'instance', + permissions: (user: UserPermissions) => { + return true; + } +}, { + id: 'operations', + permissions: (user: UserPermissions) => { + return ( + user.POLICIES_POLICY_CREATE || + user.POLICIES_POLICY_UPDATE || + user.POLICIES_POLICY_REVIEW || + user.POLICIES_POLICY_DELETE + ) + } +}]; + /** * Component for choosing a policy and * display blocks of the selected policy @@ -40,8 +112,8 @@ import { ContractService } from 'src/app/services/contract.service'; styleUrls: ['./policies.component.scss'], }) export class PoliciesComponent implements OnInit { + public user: UserPermissions = new UserPermissions(); public policies: any[] | null; - public role!: any; public loading: boolean = true; public isConfirmed: boolean = false; public pageIndex: number; @@ -54,7 +126,6 @@ export class PoliciesComponent implements OnInit { public publishMenuSelector: any = null; public noFilterResults: boolean = false; private columns: string[] = []; - private columnsRole: any = {}; private publishMenuOption = [ { id: 'Publish', @@ -129,6 +200,14 @@ export class PoliciesComponent implements OnInit { }; }); + public checkMigrationStatus(status: string): boolean { + return ( + status === 'PUBLISH' || + status === 'DRY-RUN' || + status === 'DISCONTINUED' + ) + } + constructor( public tagsService: TagsService, private profileService: ProfileService, @@ -142,7 +221,6 @@ export class PoliciesComponent implements OnInit { private wizardService: WizardService, private tokenService: TokenService, private analyticsService: AnalyticsService, - private changeDetector: ChangeDetectorRef, private contractSerivce: ContractService, @Inject(CONFIGURATION_ERRORS) private _configurationErrors: Map @@ -151,29 +229,6 @@ export class PoliciesComponent implements OnInit { this.pageIndex = 0; this.pageSize = 10; this.policiesCount = 0; - this.columnsRole = {}; - this.columnsRole[UserRole.STANDARD_REGISTRY] = [ - 'name', - 'description', - // 'roles', - 'topic', - 'version', - 'tags', - 'tokens', - 'schemas', - 'status', - 'instance', - 'operations', - ]; - this.columnsRole[UserRole.USER] = [ - 'name', - 'description', - 'roles', - 'version', - 'tags', - 'status', - 'instance', - ]; } ngOnInit() { @@ -189,29 +244,26 @@ export class PoliciesComponent implements OnInit { forkJoin([ this.profileService.getProfile(), this.tagsService.getPublishedSchemas(), - ]).subscribe( - (value) => { - const profile: IUser | null = value[0]; - const tagSchemas: any[] = value[1] || []; - - this.isConfirmed = !!(profile && profile.confirmed); - this.role = profile ? profile.role : null; - this.owner = profile?.did; - this.tagSchemas = SchemaHelper.map(tagSchemas); - - if (this.role == UserRole.STANDARD_REGISTRY) { - this.columns = this.columnsRole[UserRole.STANDARD_REGISTRY]; - } else { - this.columns = this.columnsRole[UserRole.USER]; - } - if (this.isConfirmed) { - this.loadAllPolicy(); - } else { - setTimeout(() => { - this.loading = false; - }, 500); - } - }, + ]).subscribe((value) => { + const profile: IUser | null = value[0]; + const tagSchemas: any[] = value[1] || []; + this.isConfirmed = !!(profile && profile.confirmed); + this.user = new UserPermissions(profile); + this.owner = this.user.did; + this.tagSchemas = SchemaHelper.map(tagSchemas); + + this.columns = columns + .filter((c) => c.permissions(this.user)) + .map((c) => c.id); + + if (this.isConfirmed) { + this.loadAllPolicy(); + } else { + setTimeout(() => { + this.loading = false; + }, 500); + } + }, (e) => { this.loading = false; } @@ -221,48 +273,51 @@ export class PoliciesComponent implements OnInit { private loadAllPolicy() { this.loading = true; this.tagOptions = []; - this.policyEngineService.page(this.pageIndex, this.pageSize).subscribe( - (policiesResponse) => { - this.policies = policiesResponse.body?.map(policy => { - if (policy.discontinuedDate) { - policy.discontinuedDate = new Date(policy.discontinuedDate); - } - return policy; - }) || []; - this.policiesCount = - policiesResponse.headers.get('X-Total-Count') || - this.policies.length; - const ids = this.policies.map((e) => e.id); - this.tagsService.search(this.tagEntity, ids).subscribe( - (data) => { - if (this.policies) { - for (const policy of this.policies) { - (policy as any)._tags = data[policy.id]; - data[policy.id]?.tags.forEach((tag: any) => { - const totalTagOptions = [ - ...this.tagOptions, - tag.name, - ]; - this.tagOptions = [ - ...new Set(totalTagOptions), - ]; - }); - } - } - setTimeout(() => { - this.loading = false; - }, 500); - }, - (e) => { - console.error(e.error); - this.loading = false; - } - ); - }, - (e) => { + this.policyEngineService.page(this.pageIndex, this.pageSize).subscribe((policiesResponse) => { + this.policies = policiesResponse.body?.map(policy => { + if (policy.discontinuedDate) { + policy.discontinuedDate = new Date(policy.discontinuedDate); + } + return policy; + }) || []; + this.policiesCount = + policiesResponse.headers.get('X-Total-Count') || + this.policies.length; + + this.loadPolicyTags(this.policies); + }, (e) => { + this.loading = false; + }); + } + + private loadPolicyTags(policies: any[]) { + if (!this.user.TAGS_TAG_READ || !policies || !policies.length) { + setTimeout(() => { this.loading = false; - } - ); + }, 500); + } else { + const ids = policies.map((e) => e.id); + this.tagsService.search(this.tagEntity, ids).subscribe((data) => { + for (const policy of policies) { + (policy as any)._tags = data[policy.id]; + data[policy.id]?.tags.forEach((tag: any) => { + const totalTagOptions = [ + ...this.tagOptions, + tag.name, + ]; + this.tagOptions = [ + ...new Set(totalTagOptions), + ]; + }); + } + setTimeout(() => { + this.loading = false; + }, 500); + }, (e) => { + console.error(e.error); + this.loading = false; + }); + } } public onPage(event: any): void { @@ -1106,7 +1161,7 @@ export class PoliciesComponent implements OnInit { } public onChangeStatus(event: any, policy: any): void { - switch(policy.status) { + switch (policy.status) { case 'DRAFT': this.onPublishAction(event, policy); break; diff --git a/frontend/src/app/modules/policy-engine/policy-configuration/policy-configuration/policy-configuration.component.html b/frontend/src/app/modules/policy-engine/policy-configuration/policy-configuration/policy-configuration.component.html index d4c53bcd30..8224c0cb2a 100644 --- a/frontend/src/app/modules/policy-engine/policy-configuration/policy-configuration/policy-configuration.component.html +++ b/frontend/src/app/modules/policy-engine/policy-configuration/policy-configuration/policy-configuration.component.html @@ -20,7 +20,11 @@ Save
-
+
save Save As
@@ -87,14 +91,20 @@ Save
-
+
save Save As
-
edit Draft @@ -135,14 +145,20 @@ Save
-
+
save Save As
-
edit Draft @@ -199,6 +215,7 @@ move_to_inbox Convert to Module @@ -1104,8 +1124,12 @@
-
+
public Publish
@@ -1118,7 +1142,9 @@ -
public Publish @@ -1126,7 +1152,9 @@ -
public Publish diff --git a/frontend/src/app/modules/policy-engine/policy-configuration/policy-configuration/policy-configuration.component.ts b/frontend/src/app/modules/policy-engine/policy-configuration/policy-configuration/policy-configuration.component.ts index 74fe9fb22b..15103e337a 100644 --- a/frontend/src/app/modules/policy-engine/policy-configuration/policy-configuration/policy-configuration.component.ts +++ b/frontend/src/app/modules/policy-engine/policy-configuration/policy-configuration/policy-configuration.component.ts @@ -2,16 +2,9 @@ import { CdkDragDrop, CdkDropList, moveItemInArray } from '@angular/cdk/drag-dro import { ChangeDetectorRef, Component, HostListener, Inject, OnInit, ViewChild } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { ActivatedRoute, Router } from '@angular/router'; -import { PolicyCategoryType, Schema, SchemaHelper, Token } from '@guardian/interfaces'; +import { PolicyCategoryType, Schema, SchemaHelper, Token, UserPermissions } from '@guardian/interfaces'; import * as yaml from 'js-yaml'; import { forkJoin, Observable } from 'rxjs'; -import { ConfirmationDialogComponent } from 'src/app/modules/common/confirmation-dialog/confirmation-dialog.component'; -import { SetVersionDialog } from 'src/app/modules/schema-engine/set-version-dialog/set-version-dialog.component'; -import { InformService } from 'src/app/services/inform.service'; -import { ModulesService } from 'src/app/services/modules.service'; -import { PolicyEngineService } from 'src/app/services/policy-engine.service'; -import { SchemaService } from 'src/app/services/schema.service'; -import { TokenService } from 'src/app/services/token.service'; import { NewModuleDialog } from '../../helpers/new-module-dialog/new-module-dialog.component'; import { SaveBeforeDialogComponent } from '../../helpers/save-before-dialog/save-before-dialog.component'; import { PolicyAction, SavePolicyDialog } from '../../helpers/save-policy-dialog/save-policy-dialog.component'; @@ -19,16 +12,24 @@ import { RegisteredService } from '../../services/registered.service'; import { IPolicyCategory, ModuleTemplate, Options, PolicyBlock, PolicyModule, PolicyStorage, PolicyTemplate, Theme, ThemeRule, ToolMenu, ToolTemplate } from '../../structures'; import { PolicyTreeComponent } from '../policy-tree/policy-tree.component'; import { ThemeService } from '../../../../services/theme.service'; -import { WizardMode, WizardService } from 'src/app/modules/policy-engine/services/wizard.service'; import { SuggestionsService } from '../../../../services/suggestions.service'; import { PolicyFolder, PolicyItem, PolicyRoot } from '../../structures/policy-models/interfaces/types'; -import { ToolsService } from 'src/app/services/tools.service'; import { DialogService } from 'primeng/dynamicdialog'; import { CONFIGURATION_ERRORS } from '../../injectors/configuration.errors.injector'; -import { AnalyticsService } from 'src/app/services/analytics.service'; import { StopResizingEvent } from '../../directives/resizing.directive'; import { OrderOption } from '../../structures/interfaces/order-option.interface'; import { PolicyPropertiesComponent } from '../policy-properties/policy-properties.component'; +import { WizardMode, WizardService } from 'src/app/modules/policy-engine/services/wizard.service'; +import { ConfirmationDialogComponent } from 'src/app/modules/common/confirmation-dialog/confirmation-dialog.component'; +import { SetVersionDialog } from 'src/app/modules/schema-engine/set-version-dialog/set-version-dialog.component'; +import { InformService } from 'src/app/services/inform.service'; +import { ModulesService } from 'src/app/services/modules.service'; +import { PolicyEngineService } from 'src/app/services/policy-engine.service'; +import { SchemaService } from 'src/app/services/schema.service'; +import { TokenService } from 'src/app/services/token.service'; +import { ProfileService } from 'src/app/services/profile.service'; +import { ToolsService } from 'src/app/services/tools.service'; +import { AnalyticsService } from 'src/app/services/analytics.service'; /** * The page for editing the policy and blocks. @@ -45,6 +46,7 @@ export class PolicyConfigurationComponent implements OnInit { public options: Options; public readonly!: boolean; + public user: UserPermissions = new UserPermissions(); public rootType: 'Policy' | 'Module' | 'Tool' = 'Policy'; public policyId!: string; public moduleId!: string; @@ -209,6 +211,7 @@ export class PolicyConfigurationComponent implements OnInit { private modulesService: ModulesService, private toolsService: ToolsService, private analyticsService: AnalyticsService, + private profileService: ProfileService, @Inject(CONFIGURATION_ERRORS) private _configurationErrors: Map ) { @@ -282,7 +285,12 @@ export class PolicyConfigurationComponent implements OnInit { private loadPolicy(): void { this.rootId = this.policyId; - this.policyEngineService.policy(this.policyId).subscribe((policy: any) => { + forkJoin([ + this.profileService.getProfile(), + this.policyEngineService.policy(this.policyId) + ]).subscribe(([user, policy]) => { + this.user = new UserPermissions(user); + if (!policy) { this.policyTemplate = new PolicyTemplate(); this.onOpenRoot(this.policyTemplate); @@ -298,7 +306,7 @@ export class PolicyConfigurationComponent implements OnInit { } forkJoin([ - this.tokenService.getTokens(), + this.tokenService.menuList(), this.policyEngineService.getBlockInformation(), this.schemaService.getSchemas(this.policyTemplate.topicId), this.modulesService.menuList(), @@ -366,7 +374,12 @@ export class PolicyConfigurationComponent implements OnInit { private loadModule(): void { this.rootId = this.moduleId; - this.modulesService.getById(this.moduleId).subscribe((module: any) => { + forkJoin([ + this.profileService.getProfile(), + this.modulesService.getById(this.moduleId) + ]).subscribe(([user, module]) => { + this.user = new UserPermissions(user); + if (!module) { this.moduleTemplate = new ModuleTemplate(); this.onOpenRoot(this.moduleTemplate); @@ -412,7 +425,12 @@ export class PolicyConfigurationComponent implements OnInit { private loadTool(): void { this.rootId = this.toolId; - this.toolsService.getById(this.toolId).subscribe((tool: any) => { + forkJoin([ + this.profileService.getProfile(), + this.toolsService.getById(this.toolId) + ]).subscribe(([user, tool]) => { + this.user = new UserPermissions(user); + if (!tool) { this.toolTemplate = new ToolTemplate(); this.onOpenRoot(this.toolTemplate); @@ -429,7 +447,7 @@ export class PolicyConfigurationComponent implements OnInit { forkJoin([ this.policyEngineService.getBlockInformation(), - this.tokenService.getTokens(), + this.tokenService.menuList(), this.schemaService.getSchemas(this.toolTemplate.topicId), this.modulesService.menuList(), this.toolsService.menuList() @@ -1502,7 +1520,9 @@ export class PolicyConfigurationComponent implements OnInit { module.description = result.description; this.loading = true; this.modulesService.create(module).subscribe((result) => { - this.router.navigate(['/policy-configuration'], { queryParams: { moduleId: result.uuid } }); + this.router.navigate(['/module-configuration'], { + queryParams: { moduleId: result.uuid } + }); }, (e) => { this.loading = false; }); @@ -1609,7 +1629,7 @@ export class PolicyConfigurationComponent implements OnInit { tool.description = result.description; this.loading = true; this.toolsService.create(tool).subscribe((result) => { - this.router.navigate(['/policy-configuration'], { + this.router.navigate(['/tool-configuration'], { queryParams: { toolId: result.id } }); }, (e) => { diff --git a/frontend/src/app/modules/policy-engine/policy-viewer/blocks/tags-manager-block/tags-manager-block.component.html b/frontend/src/app/modules/policy-engine/policy-viewer/blocks/tags-manager-block/tags-manager-block.component.html index 77eb8c92a3..890382a3bc 100644 --- a/frontend/src/app/modules/policy-engine/policy-viewer/blocks/tags-manager-block/tags-manager-block.component.html +++ b/frontend/src/app/modules/policy-engine/policy-viewer/blocks/tags-manager-block/tags-manager-block.component.html @@ -1,5 +1,10 @@
-
diff --git a/frontend/src/app/modules/policy-engine/policy-viewer/policy-viewer/policy-viewer.component.scss b/frontend/src/app/modules/policy-engine/policy-viewer/policy-viewer/policy-viewer.component.scss index 4450e770b8..05165d9b82 100644 --- a/frontend/src/app/modules/policy-engine/policy-viewer/policy-viewer/policy-viewer.component.scss +++ b/frontend/src/app/modules/policy-engine/policy-viewer/policy-viewer/policy-viewer.component.scss @@ -4,7 +4,8 @@ right: 0; bottom: 0; top: 0; - display: block; + display: flex; + flex-direction: column; } .loading { @@ -94,7 +95,7 @@ a.go-back-link mat-icon { display: flex; //flex-direction: column; gap: 24px; - padding: 20px 48px; + padding: 18px 20px 78px 48px; background: #f9fafc; } @@ -207,18 +208,21 @@ a.go-back-link mat-icon { } .content[status="DRY-RUN"] .policy-header { + min-height: 136px; height: 136px; background: #23252e; color: #fff; } .content[status="DISCONTINUED"] .policy-header { + min-height: 136px; height: 136px; background: #ff3e3e; color: #fff; } .content[status="PUBLISH"] .policy-header[expired="true"] { + min-height: 136px; height: 136px; background: #FF8460; color: #fff; @@ -237,6 +241,7 @@ a.go-back-link mat-icon { left: 0px; right: 0px; height: 50px; + min-height: 50px; display: flex; box-sizing: border-box; z-index: 150; diff --git a/frontend/src/app/modules/policy-engine/tools-list/tools-list.component.html b/frontend/src/app/modules/policy-engine/tools-list/tools-list.component.html index 40e09777fa..fd6e7a3b47 100644 --- a/frontend/src/app/modules/policy-engine/tools-list/tools-list.component.html +++ b/frontend/src/app/modules/policy-engine/tools-list/tools-list.component.html @@ -17,6 +17,7 @@
- -
+ +
+ >Publish
tool.status === 'DRAFT'); + this.loadTagsData(); + }, (e) => { + this.loading = false; + }); + } - const ids = this.tools.map(e => e.id); + private loadTagsData() { + if (this.user.TAGS_TAG_READ) { + const ids = this.tools?.map(e => e.id) || []; this.tagsService.search(this.tagEntity, ids).subscribe((data) => { if (this.tools) { for (const policy of this.tools) { @@ -130,9 +139,11 @@ export class ToolsListComponent implements OnInit, OnDestroy { console.error(e.error); this.loading = false; }); - }, (e) => { - this.loading = false; - }); + } else { + setTimeout(() => { + this.loading = false; + }, 500); + } } public onPage(event: any) { diff --git a/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.html b/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.html index bba07976f2..1f58220c61 100644 --- a/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.html +++ b/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.html @@ -1,11 +1,12 @@
-
-

Project Comparison

-
-
-
+ +
+

Project Comparison

+
+
+
@@ -78,7 +79,31 @@

Project Comparison

-
+
+ +
+

VP Comparison

+
+
+
+ + + + + +
+
+
+
diff --git a/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.scss b/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.scss index d285e03cf0..cfdc5ae349 100644 --- a/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.scss +++ b/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.scss @@ -30,7 +30,7 @@ h1 { .projects-comparison { padding: 34px 80px; box-sizing: border-box; - position: absolute; + //position: absolute; left: 0; right: 0; bottom: 0; @@ -319,3 +319,7 @@ tr { .toggle-icon.toggle-icon-collapsed { transform: rotate(-90deg); } + +.vp-documents { + width: 100%; +} diff --git a/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.ts b/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.ts index 81c368e3a8..37696b0000 100644 --- a/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.ts +++ b/frontend/src/app/modules/project-comparison/component/projects-comparison-table/projects-comparison-table.component.ts @@ -82,6 +82,7 @@ interface IPropertyRow { styleUrls: ['./projects-comparison-table.component.scss'], }) export class ProjectsComparisonTableComponent implements OnInit { + public vpDocuments: any[] = []; public loading: boolean = true; public columns: boolean[]; public groups: IGroup[]; @@ -161,7 +162,12 @@ export class ProjectsComparisonTableComponent implements OnInit { ]).subscribe((result: any) => { const [properties, data] = result; this.properties = properties; - this.setData(data); + this.setData(data.projects); + this.vpDocuments = data.presentations.map((vp: any) => { + console.log(vp); + vp.size = 2; + return vp; + }) this.loading = false; }) } diff --git a/frontend/src/app/modules/project-comparison/project-comparison.module.ts b/frontend/src/app/modules/project-comparison/project-comparison.module.ts index 8ef7eb0704..32a4ed0234 100644 --- a/frontend/src/app/modules/project-comparison/project-comparison.module.ts +++ b/frontend/src/app/modules/project-comparison/project-comparison.module.ts @@ -13,6 +13,7 @@ import { ProjectsOverviewComponent } from './component/projects-overview/project import { ProjectsComparisonTableComponent } from './component/projects-comparison-table/projects-comparison-table.component'; import { CommonModule } from '@angular/common'; import { AngularSvgIconModule } from 'angular-svg-icon'; +import { CompareModule } from '../analytics/analytics.module'; @NgModule({ declarations: [ @@ -32,7 +33,8 @@ import { AngularSvgIconModule } from 'angular-svg-icon'; MultiSelectModule, ReactiveFormsModule, HttpClientModule, - AngularSvgIconModule.forRoot() + AngularSvgIconModule.forRoot(), + CompareModule ], exports: [ AnnotationBlockComponent, @@ -41,4 +43,4 @@ import { AngularSvgIconModule } from 'angular-svg-icon'; ] }) export class ProjectComparisonModule { -} \ No newline at end of file +} diff --git a/frontend/src/app/modules/schema-engine/schema-form-view/schema-form-view.component.html b/frontend/src/app/modules/schema-engine/schema-form-view/schema-form-view.component.html index dc3815345d..87ca508082 100644 --- a/frontend/src/app/modules/schema-engine/schema-form-view/schema-form-view.component.html +++ b/frontend/src/app/modules/schema-engine/schema-form-view/schema-form-view.component.html @@ -60,7 +60,8 @@ [preset]="this.values && this.values[item.name]" [disabled]="true"> + [delimiter-hide]="true" + [dryRun]="dryRun" [values]="this.values && this.values[item.name]">
@@ -139,7 +140,7 @@ + [delimiter-hide]="true" [dryRun]="dryRun" [values]="listItem">
diff --git a/frontend/src/app/modules/schema-engine/schema-form/schema-form.component.html b/frontend/src/app/modules/schema-engine/schema-form/schema-form.component.html index 66b46502b5..904b2cfa8f 100644 --- a/frontend/src/app/modules/schema-engine/schema-form/schema-form.component.html +++ b/frontend/src/app/modules/schema-engine/schema-form/schema-form.component.html @@ -132,7 +132,10 @@ [preset]="item.preset"> + [conditions]="item.conditions" [delimiter-hide]="true" + [dryRun]="dryRun" [isChildSchema]="true" + [policyId]="policyId" [preset]="item.preset" + >
@@ -274,7 +277,10 @@ [formGroup]="listItem.control" [preset]="listItem.preset"> + [conditions]="item.conditions" [delimiter-hide]="true" + [dryRun]="dryRun" [isChildSchema]="true" + [policyId]="policyId" [preset]="listItem.preset" + > @@ -303,13 +309,16 @@ [fields]="condition.thenFields" [formGroup]="condition.conditionForm" [preset]="condition.preset" [readonly-fields]="readonly" (destroy)="removeConditionFields(condition.thenFields, condition)" - [isChildSchema]="true"> + [dryRun]="dryRun" + [isChildSchema]="true" + [policyId]="policyId" + > + [dryRun]="dryRun" [isChildSchema]="true" [policyId]="policyId">
diff --git a/frontend/src/app/modules/tag-engine/tags-explorer-dialog/tags-explorer-dialog.component.html b/frontend/src/app/modules/tag-engine/tags-explorer-dialog/tags-explorer-dialog.component.html index ffff6219f4..abd0d47ff5 100644 --- a/frontend/src/app/modules/tag-engine/tags-explorer-dialog/tags-explorer-dialog.component.html +++ b/frontend/src/app/modules/tag-engine/tags-explorer-dialog/tags-explorer-dialog.component.html @@ -18,8 +18,9 @@ [class.selected]="item === select" class="item" > -
{{item.name}} @@ -31,7 +32,7 @@
-
+
diff --git a/frontend/src/app/modules/tag-engine/tags-explorer-dialog/tags-explorer-dialog.component.ts b/frontend/src/app/modules/tag-engine/tags-explorer-dialog/tags-explorer-dialog.component.ts index 47ea662a2b..b75e232514 100644 --- a/frontend/src/app/modules/tag-engine/tags-explorer-dialog/tags-explorer-dialog.component.ts +++ b/frontend/src/app/modules/tag-engine/tags-explorer-dialog/tags-explorer-dialog.component.ts @@ -1,5 +1,4 @@ import { Component } from '@angular/core'; -import { FormBuilder } from '@angular/forms'; import { TagCreateDialog } from '../tags-create-dialog/tags-create-dialog.component'; import { TagsService } from 'src/app/services/tag.service'; import { TagsHistory } from '../models/tags-history'; @@ -8,6 +7,7 @@ import { TagItem } from '../models/tag-item'; import * as moment from 'moment'; import { VCViewerDialog } from '../../schema-engine/vc-dialog/vc-dialog.component'; import { DialogService, DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog'; +import { UserPermissions } from '@guardian/interfaces'; /** * Dialog for creating tokens. @@ -32,16 +32,25 @@ export class TagsExplorerDialog { public schemas: any[] = []; public hasChanges: boolean = false; public selectedTags: TagMapItem[] = []; + public user: UserPermissions; + + public get canCreate():boolean { + if(this.user) { + return this.user.TAGS_TAG_CREATE; + } else { + return true; + } + } constructor( public dialogRef: DynamicDialogRef, public dialog: DialogService, - private fb: FormBuilder, public dialogData: DynamicDialogConfig ) { this.schemas = dialogData.data?.schemas; - this.tagsService = dialogData.data.service; - this.history = dialogData.data.history; + this.tagsService = dialogData.data?.service; + this.history = dialogData.data?.history; + this.user = dialogData.data?.user; this.selectedTags = this.history.items; this.owner = this.history.owner; diff --git a/frontend/src/app/modules/tag-engine/tags-explorer/tags-explorer.component.html b/frontend/src/app/modules/tag-engine/tags-explorer/tags-explorer.component.html index 99f0fa7052..12b40f6d89 100644 --- a/frontend/src/app/modules/tag-engine/tags-explorer/tags-explorer.component.html +++ b/frontend/src/app/modules/tag-engine/tags-explorer/tags-explorer.component.html @@ -3,8 +3,8 @@
@@ -23,7 +23,10 @@
more_horiz
-
+
- +
diff --git a/frontend/src/app/views/header/header.component.ts b/frontend/src/app/views/header/header.component.ts index 24298b33ea..a0492356d2 100644 --- a/frontend/src/app/views/header/header.component.ts +++ b/frontend/src/app/views/header/header.component.ts @@ -219,10 +219,14 @@ export class HeaderComponent implements OnInit { this.activeLinkRoot === '/suggestions' || this.activeLinkRoot === '/policy-viewer' || this.activeLinkRoot === '/policy-configuration' || + this.activeLinkRoot === '/module-configuration' || + this.activeLinkRoot === '/tool-configuration' || this.activeLinkRoot === '/compare' || this.activeLinkRoot === '/search' || /^\/policy-configuration\/\w+/.test(this.activeLinkRoot) || - this.activeLinkRoot === 'policy-configuration' + this.activeLinkRoot === 'policy-configuration' || + this.activeLinkRoot === 'module-configuration' || + this.activeLinkRoot === 'tool-configuration' ); case 'SR_ADMIN': return ( @@ -251,7 +255,11 @@ export class HeaderComponent implements OnInit { case 'SR_VIEWER': return /^\/policy-viewer\/\w+/.test(this.activeLinkRoot); case 'SR_EDITOR': - return this.activeLinkRoot === '/policy-configuration'; + return ( + this.activeLinkRoot === '/policy-configuration' || + this.activeLinkRoot === '/module-configuration' || + this.activeLinkRoot === '/tool-configuration' + ); case 'SR_COMPARE': return this.activeLinkRoot === '/compare'; case 'SR_SEARCH': diff --git a/frontend/src/app/views/home/home.component.ts b/frontend/src/app/views/home/home.component.ts index 732f782a5c..732682296d 100644 --- a/frontend/src/app/views/home/home.component.ts +++ b/frontend/src/app/views/home/home.component.ts @@ -1,6 +1,6 @@ import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; -import { UserRole } from '@guardian/interfaces'; +import { UserCategory, UserRole } from '@guardian/interfaces'; import { AuthService } from 'src/app/services/auth.service'; /** @@ -25,13 +25,8 @@ export class HomeComponent implements OnInit { async redirect() { this.auth.sessions().subscribe((user: any | null) => { if (user) { - if (user.role === UserRole.STANDARD_REGISTRY) { - this.router.navigate(['/config']); - } else if (user.role === UserRole.AUDITOR) { - this.router.navigate(['/audit']); - } else { - this.router.navigate(['/user-profile']); - } + const home = this.auth.home(user.role); + this.router.navigate([home]); } else { this.router.navigate(['/login']); } diff --git a/frontend/src/app/views/list-of-tokens-user/list-of-tokens-user.component.html b/frontend/src/app/views/list-of-tokens-user/list-of-tokens-user.component.html index aa231737a4..c7879e8d83 100644 --- a/frontend/src/app/views/list-of-tokens-user/list-of-tokens-user.component.html +++ b/frontend/src/app/views/list-of-tokens-user/list-of-tokens-user.component.html @@ -60,9 +60,15 @@

List of Tokens

{{ getPoliciesInfo(token.policies) }}
- + diff --git a/frontend/src/app/views/list-of-tokens-user/list-of-tokens-user.component.ts b/frontend/src/app/views/list-of-tokens-user/list-of-tokens-user.component.ts index 324ad53dd0..ce1606ed9c 100644 --- a/frontend/src/app/views/list-of-tokens-user/list-of-tokens-user.component.ts +++ b/frontend/src/app/views/list-of-tokens-user/list-of-tokens-user.component.ts @@ -3,7 +3,7 @@ import { AuthService } from '../../services/auth.service'; import { ProfileService } from '../../services/profile.service'; import { TokenService } from '../../services/token.service'; import { ActivatedRoute, Router } from '@angular/router'; -import { IUser, SchemaHelper, TagType, Token } from '@guardian/interfaces'; +import { IUser, SchemaHelper, TagType, Token, UserPermissions } from '@guardian/interfaces'; import { InformService } from 'src/app/services/inform.service'; import { TasksService } from 'src/app/services/tasks.service'; import { forkJoin } from 'rxjs'; @@ -27,17 +27,18 @@ enum OperationMode { providers: [DialogService] }) export class ListOfTokensUserComponent implements OnInit { - profile?: IUser | null; - tokens: any[] = []; - loading: boolean = true; - isConfirmed: boolean = false; - isFailed: boolean = false; - isNewAccount: boolean = false; - - value: any; - - users: any[] = []; - usersColumns: string[] = [ + public user: UserPermissions = new UserPermissions(); + public profile?: IUser | null; + public tokens: any[] = []; + public loading: boolean = true; + public isConfirmed: boolean = false; + public isFailed: boolean = false; + public isNewAccount: boolean = false; + + public value: any; + + public users: any[] = []; + public usersColumns: string[] = [ 'username', 'associated', 'tokenBalance', @@ -46,20 +47,20 @@ export class ListOfTokensUserComponent implements OnInit { 'refresh' ]; - taskId: string | undefined = undefined; - expectedTaskMessages: number = 0; - operationMode: OperationMode = OperationMode.None; - user: any; - currentPolicy: any = ''; - policies: any[] | null = null; - tagEntity = TagType.Token; - owner: any; - tagSchemas: any[] = []; - - tokenDialogVisible: boolean = false; - deleteTokenVisible: boolean = false; - currentTokenId: any; - dataForm = new FormGroup({ + public taskId: string | undefined = undefined; + public expectedTaskMessages: number = 0; + public operationMode: OperationMode = OperationMode.None; + public selectedUser: any; + public currentPolicy: any = ''; + public policies: any[] | null = null; + public tagEntity = TagType.Token; + public owner: any; + public tagSchemas: any[] = []; + + public tokenDialogVisible: boolean = false; + public deleteTokenVisible: boolean = false; + public currentTokenId: any; + public dataForm = new FormGroup({ draftToken: new FormControl(true, [Validators.required]), tokenName: new FormControl('Token Name', [Validators.required, noWhitespaceValidator()]), tokenSymbol: new FormControl('F', [Validators.required, noWhitespaceValidator()]), @@ -72,11 +73,11 @@ export class ListOfTokensUserComponent implements OnInit { enableKYC: new FormControl(false, [Validators.required]), enableWipe: new FormControl(true, [Validators.required]) }); - dataFormPristine: any = this.dataForm.value; - readonlyForm: boolean = false; - hideType: boolean = false; + public dataFormPristine: any = this.dataForm.value; + public readonlyForm: boolean = false; + public hideType: boolean = false; - policyDropdownItem: any; + public policyDropdownItem: any; public innerWidth: any; public innerHeight: any; @@ -117,7 +118,7 @@ export class ListOfTokensUserComponent implements OnInit { this.profileService.getProfile().subscribe((data) => { this.profile = data as IUser; - + this.user = new UserPermissions(this.profile); this.isConfirmed = !!this.profile.confirmed; this.isFailed = !!this.profile.failed; this.isNewAccount = !this.profile.didDocument; @@ -125,7 +126,7 @@ export class ListOfTokensUserComponent implements OnInit { this.loadTokenData(); - }, ({message}) => { + }, ({ message }) => { this.loading = false; console.error(message); }); @@ -135,7 +136,12 @@ export class ListOfTokensUserComponent implements OnInit { this.loading = true; forkJoin([ - this.tokenService.getTokensPage(undefined, this.pageIndex, this.pageSize), + this.tokenService.getTokensPage( + undefined, + this.pageIndex, + this.pageSize, + 'Associated' + ), this.tagsService.getPublishedSchemas() ]).subscribe((value) => { const tokensResponse = value[0]; @@ -151,7 +157,18 @@ export class ListOfTokensUserComponent implements OnInit { } }); this.tagSchemas = SchemaHelper.map(tagSchemas); + this.tokensCount = + tokensResponse.headers.get('X-Total-Count') || + this.tokens.length; + this.loadTagsData(); + }, ({ message }) => { + this.loading = false; + console.error(message); + }); + } + private loadTagsData() { + if (this.user.TAGS_TAG_READ) { const ids = this.tokens.map(e => e.id); this.tagsService.search(this.tagEntity, ids).subscribe((data) => { if (this.tokens) { @@ -166,18 +183,11 @@ export class ListOfTokensUserComponent implements OnInit { console.error(e.error); this.loading = false; }); - + } else { setTimeout(() => { this.loading = false; - }, 200) - - this.tokensCount = - tokensResponse.headers.get('X-Total-Count') || - this.tokens.length; - }, ({message}) => { - this.loading = false; - console.error(message); - }); + }, 500); + } } associate(token: Token) { @@ -186,7 +196,7 @@ export class ListOfTokensUserComponent implements OnInit { .pushAssociate(token.tokenId, token.associated != 'Yes') .subscribe( (result) => { - const {taskId, expectation} = result; + const { taskId, expectation } = result; this.taskId = taskId; this.expectedTaskMessages = expectation; this.operationMode = OperationMode.Associate; diff --git a/frontend/src/app/views/login/login.component.ts b/frontend/src/app/views/login/login.component.ts index b1b067b090..e4550ff8ea 100644 --- a/frontend/src/app/views/login/login.component.ts +++ b/frontend/src/app/views/login/login.component.ts @@ -2,7 +2,7 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AbstractControl, FormControl, FormGroup, ValidationErrors, Validators, } from '@angular/forms'; import { AuthService } from '../../services/auth.service'; -import { UserRole } from '@guardian/interfaces'; +import { UserCategory, UserRole } from '@guardian/interfaces'; import { AuthStateService } from 'src/app/services/auth-state.service'; import { Observable, Subject, Subscription } from 'rxjs'; import { noWhitespaceValidator } from 'src/app/validators/no-whitespace-validator'; @@ -108,13 +108,8 @@ export class LoginComponent implements OnInit, OnDestroy { async redirect() { this.auth.sessions().subscribe((user: any | null) => { if (user) { - if (user.role === UserRole.STANDARD_REGISTRY) { - this.router.navigate(['/config']); - } else if (user.role === UserRole.AUDITOR) { - this.router.navigate(['/audit']); - } else { - this.router.navigate(['/user-profile']); - } + const home = this.auth.home(user.role); + this.router.navigate([home]); } }); } @@ -149,11 +144,8 @@ export class LoginComponent implements OnInit, OnDestroy { this.auth.setUsername(login); this.auth.updateAccessToken().subscribe(_result => { this.authState.updateState(true); - if (result.role == UserRole.STANDARD_REGISTRY) { - this.router.navigate(['/config']); - } else { - this.router.navigate(['/']); - } + const home = this.auth.home(result.role); + this.router.navigate([home]); }); }, ({ message }) => { @@ -236,11 +228,8 @@ export class LoginComponent implements OnInit, OnDestroy { this.auth.setAccessToken(event.accessToken); this.auth.setUsername(event.username); this.authState.updateState(true); - if (event.role == UserRole.STANDARD_REGISTRY) { - this.router.navigate(['/config']); - } else { - this.router.navigate(['/']); - } + const home = this.auth.home(event.role); + this.router.navigate([home]); }); } @@ -297,18 +286,6 @@ export class LoginComponent implements OnInit, OnDestroy { return; } this.login(userData.username, userData.password); - // this.auth.login(userData.username, userData.password).subscribe((result) => { - // this.auth.setAccessToken(result.accessToken); - // this.auth.setUsername(userData.username); - // this.authState.updateState(true); - // if (result.role === UserRole.STANDARD_REGISTRY) { - // this.router.navigate(['/config']); - // } else { - // this.router.navigate(['/']); - // } - // }, () => { - // this.loading = false; - // }) }, ({ error }) => { this.error = error.message; this.loading = false; diff --git a/frontend/src/app/views/new-header/menu.model.ts b/frontend/src/app/views/new-header/menu.model.ts index ddaf5ff87c..0964e9a38b 100644 --- a/frontend/src/app/views/new-header/menu.model.ts +++ b/frontend/src/app/views/new-header/menu.model.ts @@ -1,4 +1,4 @@ -import { UserRole } from '@guardian/interfaces'; +import { UserPermissions, UserRole } from '@guardian/interfaces'; export interface NavbarMenuItem { title: string; @@ -17,23 +17,23 @@ const NAVBAR_MENU_STANDARD_REGISTRY: NavbarMenuItem[] = [ active: false, childItems: [ { - title: 'Schemas', + title: 'Manage Schemas', routerLink: '/schemas' }, { - title: 'Artifacts', + title: 'Manage Artifacts', routerLink: '/artifacts' }, { - title: 'Modules', + title: 'Manage Modules', routerLink: '/modules' }, { - title: 'Policies', + title: 'Manage Policies', routerLink: '/policy-viewer' }, { - title: 'Tools', + title: 'Manage Tools', routerLink: '/tools' }, ], @@ -45,11 +45,11 @@ const NAVBAR_MENU_STANDARD_REGISTRY: NavbarMenuItem[] = [ active: false, childItems: [ { - title: 'Tokens', + title: 'Manage Tokens', routerLink: '/tokens' }, { - title: 'Retirement', + title: 'Manage Contracts', routerLink: '/contracts' }, ], @@ -60,6 +60,14 @@ const NAVBAR_MENU_STANDARD_REGISTRY: NavbarMenuItem[] = [ active: false, iconUrl: 'stars', childItems: [ + { + title: 'Manage Roles', + routerLink: '/roles' + }, + { + title: 'User Management', + routerLink: '/user-management' + }, { title: 'Settings', routerLink: '/admin/settings' @@ -80,41 +88,6 @@ const NAVBAR_MENU_STANDARD_REGISTRY: NavbarMenuItem[] = [ }, ]; -const NAVBAR_MENU_USER: NavbarMenuItem[] = [ - { - title: 'Policies', - allowedUserRoles: [UserRole.USER], - active: false, - iconUrl: 'table', - childItems: [ - { - title: 'Search for Policies', - routerLink: '/policy-search' - }, - { - title: 'List of Policies', - routerLink: '/policy-viewer' - }, - ], - }, - { - title: 'Tokens', - iconUrl: 'twoRings', - allowedUserRoles: [UserRole.USER], - active: false, - childItems: [ - { - title: 'List of Tokens', - routerLink: '/tokens-user' - }, - { - title: 'Retirement', - routerLink: '/retirement-user' - }, - ] - }, -]; - const NAVBAR_MENU_AUDITOR: NavbarMenuItem[] = [ { title: 'Audit', @@ -132,17 +105,201 @@ const NAVBAR_MENU_AUDITOR: NavbarMenuItem[] = [ }, ]; -export function getMenuItems(userRole: UserRole): NavbarMenuItem[] { - switch (userRole) { - case UserRole.STANDARD_REGISTRY: - default: { - return NAVBAR_MENU_STANDARD_REGISTRY; +function customMenu(user: UserPermissions): NavbarMenuItem[] { + const menu: NavbarMenuItem[] = []; + if ( + user.SCHEMAS_SCHEMA_READ || + user.SCHEMAS_SYSTEM_SCHEMA_READ || + user.ARTIFACTS_FILE_READ || + user.MODULES_MODULE_READ || + user.POLICIES_POLICY_READ || + user.POLICIES_POLICY_EXECUTE || + user.POLICIES_POLICY_MANAGE || + user.TOOLS_TOOL_READ + ) { + const childItems: any = []; + if (user.POLICIES_POLICY_READ || + user.POLICIES_POLICY_EXECUTE || + user.POLICIES_POLICY_MANAGE + ) { + if ( + user.POLICIES_POLICY_CREATE || + user.POLICIES_POLICY_UPDATE || + user.POLICIES_POLICY_DELETE || + user.POLICIES_POLICY_REVIEW || + user.POLICIES_POLICY_MANAGE + ) { + childItems.push({ + title: 'Manage Policies', + routerLink: '/policy-viewer' + }); + } else { + childItems.push({ + title: 'Search for Policies', + routerLink: '/policy-search' + }); + childItems.push({ + title: 'List of Policies', + routerLink: '/policy-viewer' + }); + } + } + if ( + user.SCHEMAS_SCHEMA_READ || + user.SCHEMAS_SYSTEM_SCHEMA_READ + ) { + childItems.push({ + title: 'Manage Schemas', + routerLink: '/schemas' + }); + } + if (user.ARTIFACTS_FILE_READ) { + childItems.push({ + title: 'Manage Artifacts', + routerLink: '/artifacts' + }); + } + if (user.MODULES_MODULE_READ) { + childItems.push({ + title: 'Manage Modules', + routerLink: '/modules' + }); + } + if (user.TOOLS_TOOL_READ) { + childItems.push({ + title: 'Manage Tools', + routerLink: '/tools' + }); + } + menu.push({ + title: 'Policies', + allowedUserRoles: [UserRole.STANDARD_REGISTRY], + iconUrl: 'table', + active: false, + childItems + }); + } + + if ( + user.TOKENS_TOKEN_READ || + user.CONTRACTS_CONTRACT_READ + ) { + const childItems: any = []; + if (user.TOKENS_TOKEN_READ) { + if (user.TOKENS_TOKEN_EXECUTE) { + childItems.push({ + title: 'List of Tokens', + routerLink: '/tokens-user' + }); + } + if ( + !user.TOKENS_TOKEN_EXECUTE || + user.TOKENS_TOKEN_CREATE || + user.TOKENS_TOKEN_UPDATE || + user.TOKENS_TOKEN_DELETE || + user.TOKENS_TOKEN_MANAGE + ) { + childItems.push({ + title: 'Manage Tokens', + routerLink: '/tokens' + }); + } + + } + if (user.CONTRACTS_CONTRACT_READ) { + if ( + user.CONTRACTS_CONTRACT_EXECUTE + ) { + childItems.push({ + title: 'Retirement', + routerLink: '/retirement-user' + }); + } + if ( + user.CONTRACTS_CONTRACT_MANAGE + ) { + childItems.push({ + title: 'Manage Contracts', + routerLink: '/contracts' + }); + } + } + menu.push({ + title: 'Tokens', + iconUrl: 'twoRings', + allowedUserRoles: [UserRole.STANDARD_REGISTRY], + active: false, + childItems + }); + } + + if ( + user.DELEGATION_ROLE_MANAGE || + user.PERMISSIONS_ROLE_MANAGE || + user.PERMISSIONS_ROLE_CREATE || + user.PERMISSIONS_ROLE_UPDATE || + user.PERMISSIONS_ROLE_DELETE || + user.SETTINGS_SETTINGS_READ || + user.LOG_LOG_READ + ) { + const childItems: any = []; + if ( + user.PERMISSIONS_ROLE_CREATE || + user.PERMISSIONS_ROLE_UPDATE || + user.PERMISSIONS_ROLE_DELETE + ) { + childItems.push({ + title: 'Manage Roles', + routerLink: '/roles' + }); + } + + if ( + user.DELEGATION_ROLE_MANAGE || + user.PERMISSIONS_ROLE_MANAGE + ) { + childItems.push({ + title: 'User Management', + routerLink: '/user-management' + }); } - case UserRole.USER: { - return NAVBAR_MENU_USER; + + if (user.SETTINGS_SETTINGS_READ) { + childItems.push({ + title: 'Settings', + routerLink: '/admin/settings' + }); } - case UserRole.AUDITOR: { - return NAVBAR_MENU_AUDITOR; + if (user.LOG_LOG_READ) { + childItems.push({ + title: 'Logs', + routerLink: '/admin/logs' + }); } + menu.push({ + title: 'Administration', + allowedUserRoles: [UserRole.STANDARD_REGISTRY], + active: false, + iconUrl: 'stars', + childItems + }); } + + return menu; +} + +export function getMenuItems(user: UserPermissions): NavbarMenuItem[] { + if (!user) { + return []; + } + + if (user.AUDITOR) { + return NAVBAR_MENU_AUDITOR; + } + + if (user.STANDARD_REGISTRY) { + return NAVBAR_MENU_STANDARD_REGISTRY; + } + + return customMenu(user); } diff --git a/frontend/src/app/views/new-header/new-header.component.html b/frontend/src/app/views/new-header/new-header.component.html index 6ec2703e5b..ef22731954 100644 --- a/frontend/src/app/views/new-header/new-header.component.html +++ b/frontend/src/app/views/new-header/new-header.component.html @@ -1,7 +1,6 @@ -