Skip to content

Commit

Permalink
Merge pull request #789 from credebl/fix/primary-did-different-network
Browse files Browse the repository at this point in the history
fix: added validation for network and ledgerId update when did update
  • Loading branch information
KulkarniShashank authored Jun 19, 2024
2 parents 6c83157 + e635e70 commit 49fa9a8
Show file tree
Hide file tree
Showing 9 changed files with 186 additions and 17 deletions.
14 changes: 14 additions & 0 deletions apps/agent-service/src/agent-service.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -935,6 +935,14 @@ export class AgentServiceService {
async createDid(createDidPayload: IDidCreate, orgId: string, user: IUserRequestInterface): Promise<object> {
try {
const agentDetails = await this.agentServiceRepository.getOrgAgentDetails(orgId);

if (createDidPayload?.network) {
const getNameSpace = await this.agentServiceRepository.getLedgerByNameSpace(createDidPayload?.network);
if (agentDetails.ledgerId !== getNameSpace.id) {
throw new BadRequestException(ResponseMessages.agent.error.networkMismatch);
}
}

const getApiKey = await this.getOrgAgentApiKey(orgId);
const getOrgAgentType = await this.agentServiceRepository.getOrgAgentType(agentDetails?.orgAgentTypeId);

Expand Down Expand Up @@ -1045,6 +1053,12 @@ export class AgentServiceService {
if (network) {
const getLedgerDetails = await this.agentServiceRepository.getLedgerByNameSpace(network);
await this.agentServiceRepository.updateLedgerId(orgId, getLedgerDetails.id);
} else {
const noLedgerData = await this.agentServiceRepository.getLedger(Ledgers.Not_Applicable);
if (!noLedgerData) {
throw new NotFoundException(ResponseMessages.agent.error.noLedgerFound);
}
await this.agentServiceRepository.updateLedgerId(orgId, noLedgerData?.id);
}
}

Expand Down
15 changes: 15 additions & 0 deletions apps/agent-service/src/interface/agent-service.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -636,4 +636,19 @@ export interface OrgDid {
did: string;
didDocument: Prisma.JsonValue;
orgAgentId: string;
}

export interface ILedgers {
id: string;
createDateTime: Date;
lastChangedDateTime: Date;
name: string;
networkType: string;
poolConfig: string;
isActive: boolean;
networkString: string;
nymTxnEndpoint: string;
indyNamespace: string;
networkUrl: string;

}
16 changes: 15 additions & 1 deletion apps/agent-service/src/repositories/agent-service.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { PrismaService } from '@credebl/prisma-service';
import { Injectable, Logger } from '@nestjs/common';
// eslint-disable-next-line camelcase
import { Prisma, ledgerConfig, ledgers, org_agents, org_agents_type, org_dids, organisation, platform_config, user } from '@prisma/client';
import { ICreateOrgAgent, IOrgAgent, IOrgAgentsResponse, IOrgLedgers, IStoreAgent, IStoreDidDetails, IStoreOrgAgentDetails, LedgerNameSpace, OrgDid } from '../interface/agent-service.interface';
import { ICreateOrgAgent, ILedgers, IOrgAgent, IOrgAgentsResponse, IOrgLedgers, IStoreAgent, IStoreDidDetails, IStoreOrgAgentDetails, LedgerNameSpace, OrgDid } from '../interface/agent-service.interface';
import { AgentType } from '@credebl/enum/enum';

@Injectable()
Expand Down Expand Up @@ -509,4 +509,18 @@ export class AgentServiceRepository {
}
}

async getLedger(name: string): Promise<ILedgers> {
try {
const ledgerData = await this.prisma.ledgers.findFirstOrThrow({
where: {
name
}
});
return ledgerData;
} catch (error) {
this.logger.error(`[getLedger] - get org ledger: ${JSON.stringify(error)}`);
throw error;
}
}

}
45 changes: 44 additions & 1 deletion apps/organization/interfaces/organization.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ export interface IDidDetails {
}

export interface IPrimaryDidDetails extends IPrimaryDid {
id: string,
id: string
networkId: string
didDocument: Prisma.JsonValue
}

Expand All @@ -190,3 +191,45 @@ export interface OrgInvitation {
orgRoles: string[];
email: string;
}

export interface ILedgerNameSpace {
id: string;
createDateTime: Date;
lastChangedDateTime: Date;
name: string;
networkType: string;
poolConfig: string;
isActive: boolean;
networkString: string;
nymTxnEndpoint: string;
indyNamespace: string;
networkUrl: string;
}

export interface IGetDids {
id: string;
createDateTime: Date;
createdBy: string;
lastChangedDateTime: Date;
lastChangedBy: string;
orgId: string;
isPrimaryDid: boolean;
did: string;
didDocument: Prisma.JsonValue;
orgAgentId: string;
}

export interface ILedgerDetails {
id: string;
createDateTime: Date;
lastChangedDateTime: Date;
name: string;
networkType: string;
poolConfig: string;
isActive: boolean;
networkString: string;
nymTxnEndpoint: string;
indyNamespace: string;
networkUrl: string;

}
47 changes: 44 additions & 3 deletions apps/organization/repositories/organization.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ConflictException, Injectable, Logger, NotFoundException } from '@nestj
import { Prisma, agent_invitations, org_agents, org_invitations, user, user_org_roles } from '@prisma/client';

import { CreateOrganizationDto } from '../dtos/create-organization.dto';
import { IDidDetails, IDidList, IGetOrgById, IGetOrganization, IPrimaryDidDetails, IUpdateOrganization, OrgInvitation } from '../interfaces/organization.interface';
import { IGetDids, IDidDetails, IDidList, IGetOrgById, IGetOrganization, IPrimaryDidDetails, IUpdateOrganization, ILedgerNameSpace, OrgInvitation, ILedgerDetails } from '../interfaces/organization.interface';
import { InternalServerErrorException } from '@nestjs/common';
import { Invitation, SortValue } from '@credebl/enum/enum';
import { PrismaService } from '@credebl/prisma-service';
Expand Down Expand Up @@ -864,7 +864,7 @@ export class OrganizationRepository {

async setOrgsPrimaryDid(primaryDidDetails: IPrimaryDidDetails): Promise<string> {
try {
const {did, didDocument, id, orgId} = primaryDidDetails;
const {did, didDocument, id, orgId, networkId} = primaryDidDetails;
await this.prisma.$transaction([
this.prisma.org_dids.update({
where: {
Expand All @@ -880,7 +880,8 @@ export class OrganizationRepository {
},
data: {
orgDid: did,
didDocument
didDocument,
ledgerId: networkId
}
})
]);
Expand Down Expand Up @@ -918,6 +919,19 @@ async getDidDetailsByDid(did:string): Promise<IDidDetails> {
}
}

async getDids(orgId:string): Promise<IGetDids[]> {
try {
return this.prisma.org_dids.findMany({
where: {
orgId
}
});
} catch (error) {
this.logger.error(`[getDids] - get all DIDs: ${JSON.stringify(error)}`);
throw error;
}
}

async setPreviousDidFlase(id:string): Promise<IDidDetails> {
try {
return this.prisma.org_dids.update({
Expand Down Expand Up @@ -946,4 +960,31 @@ async getDidDetailsByDid(did:string): Promise<IDidDetails> {
throw error;
}
}

async getNetworkByNameSpace(nameSpace: string): Promise<ILedgerNameSpace> {
try {
return this.prisma.ledgers.findFirstOrThrow({
where: {
indyNamespace: nameSpace
}
});
} catch (error) {
this.logger.error(`[getNetworkByIndyNameSpace] - get network by namespace: ${JSON.stringify(error)}`);
throw error;
}
}

async getLedger(name: string): Promise<ILedgerDetails> {
try {
const ledgerData = await this.prisma.ledgers.findFirstOrThrow({
where: {
name
}
});
return ledgerData;
} catch (error) {
this.logger.error(`[getLedger] - get ledger details: ${JSON.stringify(error)}`);
throw error;
}
}
}
54 changes: 42 additions & 12 deletions apps/organization/src/organization.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { sendEmail } from '@credebl/common/send-grid-helper-file';
import { CreateOrganizationDto } from '../dtos/create-organization.dto';
import { BulkSendInvitationDto } from '../dtos/send-invitation.dto';
import { UpdateInvitationDto } from '../dtos/update-invitation.dt';
import { Invitation, transition } from '@credebl/enum/enum';
import { DidMethod, Invitation, Ledgers, transition } from '@credebl/enum/enum';
import { IGetOrgById, IGetOrganization, IUpdateOrganization, IOrgAgent, IClientCredentials, ICreateConnectionUrl, IOrgRole, IDidList, IPrimaryDidDetails } from '../interfaces/organization.interface';
import { UserActivityService } from '@credebl/user-activity';
import { ClientRegistrationService } from '@credebl/client-registration/client-registration.service';
Expand Down Expand Up @@ -200,25 +200,55 @@ export class OrganizationService {
if (!didDetails) {
throw new NotFoundException(ResponseMessages.organisation.error.didNotFound);
}

const dids = await this.organizationRepository.getDids(orgId);
const noPrimaryDid = dids.every(orgDids => false === orgDids.isPrimaryDid);

let existingPrimaryDid;
let priviousDidFalse;
if (!noPrimaryDid) {
existingPrimaryDid = await this.organizationRepository.getPerviousPrimaryDid(orgId);

if (!existingPrimaryDid) {
throw new NotFoundException(ResponseMessages.organisation.error.didNotFound);
}

priviousDidFalse = await this.organizationRepository.setPreviousDidFlase(existingPrimaryDid.id);
}

const didParts = did.split(':');
let nameSpace: string | null = null;

// This condition will handle the multi-ledger support
if (DidMethod.INDY === didParts[1]) {
nameSpace = `${didParts[2]}:${didParts[3]}`;
} else if (DidMethod.POLYGON === didParts[1]) {
nameSpace = `${didParts[1]}:${didParts[2]}`;
} else {
nameSpace = null;
}

let network;
if (null !== nameSpace) {
network = await this.organizationRepository.getNetworkByNameSpace(nameSpace);
} else {
network = await this.organizationRepository.getLedger(Ledgers.Not_Applicable);
if (!network) {
throw new NotFoundException(ResponseMessages.agent.error.noLedgerFound);
}
}

const primaryDidDetails: IPrimaryDidDetails = {
did,
orgId,
id,
didDocument: didDetails.didDocument
didDocument: didDetails.didDocument,
networkId: network?.id ?? null
};


const getExistingPrimaryDid = await this.organizationRepository.getPerviousPrimaryDid(orgId);

if (!getExistingPrimaryDid) {
throw new NotFoundException(ResponseMessages.organisation.error.didNotFound);
}

const setPriviousDidFalse = await this.organizationRepository.setPreviousDidFlase(getExistingPrimaryDid.id);

const setPrimaryDid = await this.organizationRepository.setOrgsPrimaryDid(primaryDidDetails);

await Promise.all([setPrimaryDid, getExistingPrimaryDid, setPriviousDidFalse]);
await Promise.all([setPrimaryDid, existingPrimaryDid, priviousDidFalse]);


return ResponseMessages.organisation.success.primaryDid;
Expand Down
2 changes: 2 additions & 0 deletions libs/common/src/response-messages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,10 @@ export const ResponseMessages = {
invalidTenantIdIdFormat:'Invalid tenantId format',
requiredTenantId:'Tenant Id is required',
createDid:'Error while creating DID',
networkMismatch:'The network is mismatched.',
didAlreadyExist:'DID already exist',
storeDid: 'Error while storing DID',
noLedgerFound: 'No ledger data not found.',
agentSpinupError: 'Agent endpoint unreachable',
agentEndpointRequired: 'Agent endpoint is required',
failedAgentType: 'Agent endpoint is required',
Expand Down
1 change: 1 addition & 0 deletions libs/enum/src/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export enum Ledgers {
Indicio_Testnet = 'Indicio Testnet',
Indicio_Demonet = 'Indicio Demonet',
Indicio_Mainnet = 'Indicio Mainnet',
Not_Applicable = 'NA'
}

export enum Invitation {
Expand Down
9 changes: 9 additions & 0 deletions libs/prisma-service/prisma/data/credebl-master-table.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,15 @@
"networkString": "testnet",
"nymTxnEndpoint": "",
"indyNamespace": "polygon:testnet"
},
{
"name": "NA",
"networkType": "",
"poolConfig": "",
"isActive": true,
"networkString": "",
"nymTxnEndpoint": "",
"indyNamespace": ""
}
],
"endorseData": [
Expand Down

0 comments on commit 49fa9a8

Please sign in to comment.