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

refactor: remove legacy connection invitation #689

Merged
merged 3 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
112 changes: 60 additions & 52 deletions apps/agent-service/src/agent-service.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ export class AgentServiceService {

const getOrganization = await this.agentServiceRepository.getOrgDetails(orgData?.id);

await this._createLegacyConnectionInvitation(orgData?.id, user, getOrganization.name);
await this._createConnectionInvitation(orgData?.id, user, getOrganization.name);
if (agentSpinupDto.clientSocketId) {
socket.emit('invitation-url-creation-success', { clientId: agentSpinupDto.clientSocketId });
}
Expand Down Expand Up @@ -620,7 +620,7 @@ export class AgentServiceService {
}
}

async _createLegacyConnectionInvitation(
async _createConnectionInvitation(
orgId: string,
user: IUserRequestInterface,
label: string
Expand All @@ -629,9 +629,9 @@ export class AgentServiceService {
}> {
try {
const pattern = {
cmd: 'create-connection'
cmd: 'create-connection-invitation'
};
const payload = { orgId, user, label };
const payload = { createOutOfBandConnectionInvitation: { orgId, user, label } };
return await this.natsCall(pattern, payload);
} catch (error) {
this.logger.error(`error in create-connection in wallet provision : ${JSON.stringify(error)}`);
Expand Down Expand Up @@ -786,7 +786,7 @@ export class AgentServiceService {
this.notifyClientSocket('invitation-url-creation-started', payload.clientSocketId);

// Create the legacy connection invitation
await this._createLegacyConnectionInvitation(payload.orgId, user, getOrganization.name);
await this._createConnectionInvitation(payload.orgId, user, getOrganization.name);

this.notifyClientSocket('invitation-url-creation-success', payload.clientSocketId);
} catch (error) {
Expand Down Expand Up @@ -838,7 +838,7 @@ export class AgentServiceService {
*/
async createDid(createDidPayload: IDidCreate, orgId: string, user: IUserRequestInterface): Promise<object> {
try {
const {isPrimaryDid} = createDidPayload;
const { isPrimaryDid } = createDidPayload;
const agentDetails = await this.agentServiceRepository.getOrgAgentDetails(orgId);

const getApiKey = await this.getOrgAgentApiKey(orgId);
Expand All @@ -851,9 +851,11 @@ export class AgentServiceService {
}

delete createDidPayload.isPrimaryDid;

const didDetails = await this.commonService.httpPost(url, createDidPayload, { headers: { authorization: getApiKey } });


const didDetails = await this.commonService.httpPost(url, createDidPayload, {
headers: { authorization: getApiKey }
});

if (!didDetails) {
throw new InternalServerErrorException(ResponseMessages.agent.error.createDid, {
cause: new Error(),
Expand All @@ -869,7 +871,7 @@ export class AgentServiceService {
userId: user.id
};
const storeDidDetails = await this.agentServiceRepository.storeDidDetails(createdDidDetails);

if (!storeDidDetails) {
throw new InternalServerErrorException(ResponseMessages.agent.error.storeDid, {
cause: new Error(),
Expand Down Expand Up @@ -1518,35 +1520,39 @@ export class AgentServiceService {

async getOrgAgentApiKey(orgId: string): Promise<string> {
try {
const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId);
const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED);
const cacheKey = orgAgentApiKey?.orgAgentTypeId === orgAgentId ? CommonConstants.CACHE_SHARED_APIKEY_KEY : CommonConstants.CACHE_APIKEY_KEY;

let apiKey = await this.cacheService.get(cacheKey);
const orgAgentApiKey = await this.agentServiceRepository.getAgentApiKey(orgId);
const orgAgentId = await this.agentServiceRepository.getOrgAgentTypeDetails(OrgAgentType.SHARED);
const cacheKey =
orgAgentApiKey?.orgAgentTypeId === orgAgentId
? CommonConstants.CACHE_SHARED_APIKEY_KEY
: CommonConstants.CACHE_APIKEY_KEY;

let apiKey = await this.cacheService.get(cacheKey);
if (!apiKey) {
if (orgAgentApiKey?.orgAgentTypeId === orgAgentId) {
const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent(
CommonConstants.PLATFORM_ADMIN_ORG
);
if (!platformAdminSpinnedUp) {
throw new InternalServerErrorException('Agent not able to spin-up');
}
apiKey = platformAdminSpinnedUp.org_agents[0]?.apiKey;
} else {
apiKey = orgAgentApiKey?.apiKey;
}
if (!apiKey) {
if (orgAgentApiKey?.orgAgentTypeId === orgAgentId) {
const platformAdminSpinnedUp = await this.agentServiceRepository.platformAdminAgent(CommonConstants.PLATFORM_ADMIN_ORG);
if (!platformAdminSpinnedUp) {
throw new InternalServerErrorException('Agent not able to spin-up');
}
apiKey = platformAdminSpinnedUp.org_agents[0]?.apiKey;
} else {
apiKey = orgAgentApiKey?.apiKey;
}
if (!apiKey) {
throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist);
}
await this.cacheService.set(cacheKey, apiKey, 0);
throw new NotFoundException(ResponseMessages.agent.error.apiKeyNotExist);
}
await this.cacheService.set(cacheKey, apiKey, 0);
}

const decryptedToken = await this.commonService.decryptPassword(apiKey);
return decryptedToken;
const decryptedToken = await this.commonService.decryptPassword(apiKey);
return decryptedToken;
} catch (error) {
this.logger.error(`Agent api key details : ${JSON.stringify(error)}`);
throw error;
this.logger.error(`Agent api key details : ${JSON.stringify(error)}`);
throw error;
}
}

}

async handleAgentSpinupStatusErrors(error: string): Promise<object> {
if (error && Object.keys(error).length === 0) {
Expand Down Expand Up @@ -1586,26 +1592,30 @@ export class AgentServiceService {
const getApiKey = await this.getOrgAgentApiKey(orgId);

const data = await this.commonService
.httpGet(url, { headers: { authorization: getApiKey } })
.then(async (response) => response)
.catch((error) => this.handleAgentSpinupStatusErrors(error));
.httpGet(url, { headers: { authorization: getApiKey } })
.then(async (response) => response)
.catch((error) => this.handleAgentSpinupStatusErrors(error));

return data;
return data;
}

async createW3CSchema(url: string, orgId: string, schemaRequestPayload): Promise<object> {
try {
const getApiKey = await this.getOrgAgentApiKey(orgId);
const schemaRequest = await this.commonService
.httpPost(url, schemaRequestPayload, { headers: { 'authorization': getApiKey } })
.then(async response => response);
.httpPost(url, schemaRequestPayload, { headers: { authorization: getApiKey } })
.then(async (response) => response);
return schemaRequest;
} catch (error) {
this.logger.error(`Error in createW3CSchema request in agent service : ${JSON.stringify(error)}`);
}
}

async createConnectionInvitation(url: string, orgId: string, connectionPayload: ICreateConnectionInvitation): Promise<object> {
async createConnectionInvitation(
url: string,
orgId: string,
connectionPayload: ICreateConnectionInvitation
): Promise<object> {
try {
const getApiKey = await this.getOrgAgentApiKey(orgId);

Expand All @@ -1619,25 +1629,23 @@ export class AgentServiceService {
}
}

async natsCall(pattern: object, payload: object): Promise<{
async natsCall(
pattern: object,
payload: object
): Promise<{
response: string;
}> {
try {
return this.agentServiceProxy
.send<string>(pattern, payload)
.pipe(
map((response) => (
{
response
}))
).toPromise()
.catch(error => {
return this.agentServiceProxy.send<string>(pattern, payload).pipe(map((response) => ({response}))).toPromise()
.catch((error) => {
this.logger.error(`catch: ${JSON.stringify(error)}`);
throw new HttpException(
{
status: error.statusCode,
error: error.message
}, error.error);
},
error.error
);
});
} catch (error) {
this.logger.error(`[natsCall] - error in nats call : ${JSON.stringify(error)}`);
Expand Down
33 changes: 2 additions & 31 deletions apps/api-gateway/src/connection/connection.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { User } from '../authz/decorators/user.decorator';
import { ForbiddenErrorDto } from '../dtos/forbidden-error.dto';
import { UnauthorizedErrorDto } from '../dtos/unauthorized-error.dto';
import { ConnectionService } from './connection.service';
import { ConnectionDto, CreateConnectionDto, CreateOutOfBandConnectionInvitation, ReceiveInvitationDto, ReceiveInvitationUrlDto } from './dtos/connection.dto';
import { ConnectionDto, CreateOutOfBandConnectionInvitation, ReceiveInvitationDto, ReceiveInvitationUrlDto } from './dtos/connection.dto';
import { IUserRequestInterface } from './interfaces';
import { Response } from 'express';
import { IUserRequest } from '@credebl/user-request/user-request.interface';
Expand Down Expand Up @@ -163,42 +163,13 @@ export class ConnectionController {
return res.status(HttpStatus.OK).json(finalResponse);
}

/**
* Create out-of-band connection legacy invitation
* @param connectionDto
* @param res
* @returns Created out-of-band connection invitation url
*/
@Post('/orgs/:orgId/connections')
@ApiOperation({ summary: 'Create outbound out-of-band connection (Legacy Invitation)', description: 'Create outbound out-of-band connection (Legacy Invitation)' })
@UseGuards(AuthGuard('jwt'), OrgRolesGuard)
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN, OrgRoles.ISSUER, OrgRoles.VERIFIER, OrgRoles.MEMBER)
@ApiResponse({ status: HttpStatus.CREATED, description: 'Created', type: ApiResponseDto })
async createLegacyConnectionInvitation(
@Param('orgId') orgId: string,
@Body() connectionDto: CreateConnectionDto,
@User() reqUser: IUserRequestInterface,
@Res() res: Response
): Promise<Response> {

connectionDto.orgId = orgId;
const connectionData = await this.connectionService.createLegacyConnectionInvitation(connectionDto, reqUser);
const finalResponse: IResponse = {
statusCode: HttpStatus.CREATED,
message: ResponseMessages.connection.success.create,
data: connectionData
};
return res.status(HttpStatus.CREATED).json(finalResponse);

}

/**
* Create out-of-band connection invitation
* @param connectionDto
* @param res
* @returns Created out-of-band connection invitation url
*/
@Post('/orgs/:orgId/connection-invitation')
@Post('/orgs/:orgId/connections')
@ApiOperation({ summary: 'Create outbound out-of-band connection invitation', description: 'Create outbound out-of-band connection invitation' })
@UseGuards(AuthGuard('jwt'), OrgRolesGuard)
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN, OrgRoles.ISSUER, OrgRoles.VERIFIER, OrgRoles.MEMBER)
Expand Down
30 changes: 2 additions & 28 deletions apps/api-gateway/src/connection/connection.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { IUserRequest } from '@credebl/user-request/user-request.interface';
import { Inject, Injectable} from '@nestjs/common';
import { ClientProxy, RpcException } from '@nestjs/microservices';
import { BaseService } from 'libs/service/base.service';
import { ConnectionDto, CreateConnectionDto, CreateOutOfBandConnectionInvitation, ReceiveInvitationDto, ReceiveInvitationUrlDto } from './dtos/connection.dto';
import { ConnectionDto, CreateOutOfBandConnectionInvitation, ReceiveInvitationDto, ReceiveInvitationUrlDto } from './dtos/connection.dto';
import { IReceiveInvitationRes, IUserRequestInterface } from './interfaces';
import { IConnectionList, ICreateConnectionUrl } from '@credebl/common/interfaces/connection.interface';
import { IConnectionList } from '@credebl/common/interfaces/connection.interface';
import { AgentConnectionSearchCriteria, IConnectionDetailsById, IConnectionSearchCriteria } from '../interfaces/IConnectionSearch.interface';
import { QuestionDto } from './dtos/question-answer.dto';

Expand All @@ -24,32 +24,6 @@ export class ConnectionService extends BaseService {
}
}

createLegacyConnectionInvitation(
connectionDto: CreateConnectionDto,
user: IUserRequestInterface
): Promise<ICreateConnectionUrl> {
try {
const connectionDetails = {
orgId: connectionDto.orgId,
alias: connectionDto.alias,
label: connectionDto.label,
imageUrl: connectionDto.imageUrl,
multiUseInvitation: connectionDto.multiUseInvitation,
autoAcceptConnection: connectionDto.autoAcceptConnection,
goalCode: connectionDto.goalCode,
goal: connectionDto.goal,
handshake: connectionDto.handshake,
handshakeProtocols: connectionDto.handshakeProtocols,
user,
recipientKey:connectionDto.recipientKey
};

return this.sendNatsMessage(this.connectionServiceProxy, 'create-connection', connectionDetails);
} catch (error) {
throw new RpcException(error.response);
}
}

getConnectionWebhook(
connectionDto: ConnectionDto,
orgId: string
Expand Down
6 changes: 6 additions & 0 deletions apps/api-gateway/src/connection/dtos/connection.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ export class CreateOutOfBandConnectionInvitation {
@IsOptional()
appendedAttachments?: object[];

@ApiPropertyOptional()
@IsString()
@IsOptional()
@IsNotEmpty({ message: 'Please provide recipientKey' })
recipientKey: string;

orgId;
}

Expand Down
13 changes: 1 addition & 12 deletions apps/connection/src/connection.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { ConnectionService } from './connection.service'; // Import the common s
import { MessagePattern } from '@nestjs/microservices'; // Import the nestjs microservices package
import {
GetAllConnections,
IConnection,
ICreateConnection,
ICreateOutOfbandConnectionInvitation,
IFetchConnectionById,
Expand All @@ -12,24 +11,14 @@ import {
IReceiveInvitationByUrlOrg,
IReceiveInvitationResponse
} from './interfaces/connection.interfaces';
import { IConnectionList, ICreateConnectionUrl } from '@credebl/common/interfaces/connection.interface';
import { IConnectionList } from '@credebl/common/interfaces/connection.interface';
import { IConnectionDetailsById } from 'apps/api-gateway/src/interfaces/IConnectionSearch.interface';
import { IQuestionPayload } from './interfaces/question-answer.interfaces';

@Controller()
export class ConnectionController {
constructor(private readonly connectionService: ConnectionService) {}

/**
* Create connection legacy invitation URL
* @param payload
* @returns connection invitation URL
*/
@MessagePattern({ cmd: 'create-connection' })
async createLegacyConnectionInvitation(payload: IConnection): Promise<ICreateConnectionUrl> {
return this.connectionService.createLegacyConnectionInvitation(payload);
}

/**
* Receive connection webhook responses and save details in connection table
* @param orgId
Expand Down
Loading