Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: added validation for network and ledgerId update when did update #789

Merged
merged 4 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 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,8 @@ export class AgentServiceService {
if (network) {
const getLedgerDetails = await this.agentServiceRepository.getLedgerByNameSpace(network);
await this.agentServiceRepository.updateLedgerId(orgId, getLedgerDetails.id);
} else {
await this.agentServiceRepository.updateLedgerId(orgId, null);
}
}

Expand Down
30 changes: 29 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,30 @@ 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;
}
33 changes: 30 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 } 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,17 @@ 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;
}
}
}
50 changes: 38 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, 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,51 @@ 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);
}

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
1 change: 1 addition & 0 deletions libs/common/src/response-messages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ 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',
agentSpinupError: 'Agent endpoint unreachable',
Expand Down