Skip to content

Commit

Permalink
refactor: API refactor in user, organization, auth and agent module (#82
Browse files Browse the repository at this point in the history
)

* docs: add CONTRIBUTING guidelines

Signed-off-by: KulkarniShashank <[email protected]>

* docs: add company name in LICESE file

Signed-off-by: Ajay Jadhav <[email protected]>
Signed-off-by: KulkarniShashank <[email protected]>

* merge dev branch to main (#77)

* fix: Changed the passkey approch

Signed-off-by: KulkarniShashank <[email protected]>

* feat/fix: Implemented Add passkey for existing users

Signed-off-by: tipusinghaw <[email protected]>

* feat:implemented add passke

Signed-off-by: tipusinghaw <[email protected]>

* fix: login error message

Signed-off-by: tipusinghaw <[email protected]>

---------

Signed-off-by: KulkarniShashank <[email protected]>
Signed-off-by: tipusinghaw <[email protected]>
Signed-off-by: KulkarniShashank <[email protected]>

* worked on the master table json file and .env sample refractoring

Signed-off-by: @nishad.shirsat <[email protected]>
Signed-off-by: KulkarniShashank <[email protected]>

* Included credebl-master-table json file in the .gitignore

Signed-off-by: @nishad.shirsat <[email protected]>
Signed-off-by: KulkarniShashank <[email protected]>

* fix: API refactor in user, organization, auth and agent module

Signed-off-by: KulkarniShashank <[email protected]>

* fix: Changed the passkey approch

Signed-off-by: KulkarniShashank <[email protected]>

* feat/fix: Implemented Add passkey for existing users

Signed-off-by: tipusinghaw <[email protected]>
Signed-off-by: KulkarniShashank <[email protected]>

* feat:implemented add passke

Signed-off-by: tipusinghaw <[email protected]>
Signed-off-by: KulkarniShashank <[email protected]>

* fix: login error message

Signed-off-by: tipusinghaw <[email protected]>
Signed-off-by: KulkarniShashank <[email protected]>

* Set Validation for the user login

Signed-off-by: KulkarniShashank <[email protected]>

* Removed unnecessarily conditions in user dto

Signed-off-by: KulkarniShashank <[email protected]>

* added the role matrix in the organization, user and agent module

Signed-off-by: KulkarniShashank <[email protected]>

* Added the error handling in the API-gateway

Signed-off-by: KulkarniShashank <[email protected]>

* Added role guard in user and organization

Signed-off-by: KulkarniShashank <[email protected]>

* Error handling in the user signin functionality

Signed-off-by: KulkarniShashank <[email protected]>

* Function name changes in the singin functionality

Signed-off-by: KulkarniShashank <[email protected]>

* Added activity log success in user

Signed-off-by: KulkarniShashank <[email protected]>

* Solved the bug regarding in organization update functionality

Signed-off-by: KulkarniShashank <[email protected]>

* added role guard in user invitation

Signed-off-by: KulkarniShashank <[email protected]>

* Error handling on api-gateway dto

Signed-off-by: KulkarniShashank <[email protected]>

* Added veriable for the seed in agent-service

Signed-off-by: KulkarniShashank <[email protected]>

* Added veriable for the seed on globaly in agent-service

Signed-off-by: KulkarniShashank <[email protected]>

---------

Signed-off-by: KulkarniShashank <[email protected]>
Signed-off-by: Ajay Jadhav <[email protected]>
Signed-off-by: tipusinghaw <[email protected]>
Signed-off-by: @nishad.shirsat <[email protected]>
Co-authored-by: Ajay Jadhav <[email protected]>
Co-authored-by: Ajay Jadhav <[email protected]>
Co-authored-by: Nishad Shirsat <[email protected]>
Co-authored-by: @nishad.shirsat <[email protected]>
Co-authored-by: tipusinghaw <[email protected]>
Signed-off-by: KulkarniShashank <[email protected]>
  • Loading branch information
6 people committed Sep 11, 2024
1 parent bbe147b commit 80a0c66
Show file tree
Hide file tree
Showing 27 changed files with 718 additions and 560 deletions.
20 changes: 10 additions & 10 deletions apps/agent-service/src/agent-service.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export class AgentServiceService {
return internalIp;
} catch (error) {
this.logger.error(`error in valid internal ip : ${JSON.stringify(error)}`);
throw new RpcException(error.response);
throw new RpcException(error.response ? error.response : error);
}
}

Expand Down Expand Up @@ -573,7 +573,7 @@ export class AgentServiceService {
});
socket.emit('error-in-wallet-creation-process', { clientId: payload.clientSocketId, error });
}
throw new RpcException(error.response);
throw new RpcException(error.response ? error.response : error);
}
}

Expand Down Expand Up @@ -739,7 +739,7 @@ export class AgentServiceService {
return data;
} catch (error) {
this.logger.error(`Error in connection Invitation in agent service : ${JSON.stringify(error)}`);
throw new RpcException(error);
throw new RpcException(error.response ? error.response : error);
}
}

Expand All @@ -761,7 +761,7 @@ export class AgentServiceService {
return getProofPresentationsData;
} catch (error) {
this.logger.error(`Error in proof presentations in agent service : ${JSON.stringify(error)}`);
throw new RpcException(error);
throw new RpcException(error.response ? error.response : error);
}
}

Expand All @@ -783,7 +783,7 @@ export class AgentServiceService {
return getProofPresentationById;
} catch (error) {
this.logger.error(`Error in proof presentation by id in agent service : ${JSON.stringify(error)}`);
throw new RpcException(error);
throw new RpcException(error.response ? error.response : error);
}
}

Expand All @@ -805,7 +805,7 @@ export class AgentServiceService {
return sendProofRequest;
} catch (error) {
this.logger.error(`Error in send proof request in agent service : ${JSON.stringify(error)}`);
throw new RpcException(error);
throw new RpcException(error.response ? error.response : error);
}
}

Expand All @@ -817,7 +817,7 @@ export class AgentServiceService {
return verifyPresentation;
} catch (error) {
this.logger.error(`Error in verify proof presentation in agent service : ${JSON.stringify(error)}`);
throw new RpcException(error);
throw new RpcException(error.response ? error.response : error);
}
}

Expand Down Expand Up @@ -860,7 +860,7 @@ export class AgentServiceService {

} catch (error) {
this.logger.error(`Agent health details : ${JSON.stringify(error)}`);
throw new RpcException(error);
throw new RpcException(error.response ? error.response : error);
}
}

Expand All @@ -872,7 +872,7 @@ export class AgentServiceService {
return sendProofRequest;
} catch (error) {
this.logger.error(`Error in send out of band proof request in agent service : ${JSON.stringify(error)}`);
throw new RpcException(error);
throw new RpcException(error.response ? error.response : error);
}
}

Expand All @@ -884,7 +884,7 @@ export class AgentServiceService {
return getProofFormData;
} catch (error) {
this.logger.error(`Error in get proof form data in agent service : ${JSON.stringify(error)}`);
throw new RpcException(error);
throw new RpcException(error.response ? error.response : error);
}
}
}
Expand Down
48 changes: 42 additions & 6 deletions apps/api-gateway/common/exception-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,48 @@ export class CustomExceptionFilter extends BaseExceptionFilter {
exception.message = 'Oops! Something went wrong. Please try again';
}

const errorResponse = {
statusCode: status,
message: exception.message || 'Internal server error',
error: exception.message
};
let errorResponse;
if (exception && exception["statusCode"] === HttpStatus.INTERNAL_SERVER_ERROR) {
errorResponse = {
statusCode: status,
message: 'Oops! Something went wrong. Please try again',
error: 'Oops! Something went wrong. Please try again'
};
} else if (exception && exception["statusCode"] === undefined && status === HttpStatus.INTERNAL_SERVER_ERROR) {
errorResponse = {
statusCode: status,
message: 'Oops! Something went wrong. Please try again',
error: 'Oops! Something went wrong. Please try again'
};
} else {
if (exception && exception["response"] && exception.message) {

response.status(status).json(errorResponse);
if (Array.isArray(exception["response"].message)) {
exception["response"].message.forEach((msg) => {
errorResponse = {
statusCode: exception["statusCode"] ? exception["statusCode"] : status,
message: msg || 'Internal server error',
error: msg || 'Internal server error'
};
});
} else {
errorResponse = {
statusCode: exception["statusCode"] ? exception["statusCode"] : status,
message: exception["response"].message ? exception["response"].message : exception["response"] ? exception["response"] : 'Internal server error',
error: exception["response"].message ? exception["response"].message : exception["response"] ? exception["response"] : 'Internal server error'
};
}
} else if (exception && exception.message) {

errorResponse = {
statusCode: exception["statusCode"] ? exception["statusCode"] : status,
message: exception.message || 'Internal server error',
error: exception.message || 'Internal server error'
};

}
}

response.status(errorResponse.statusCode).json(errorResponse);
}
}
83 changes: 50 additions & 33 deletions apps/api-gateway/src/agent-service/agent-service.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import {
HttpStatus,
Res,
Get,
Query,
UseFilters
UseFilters,
Param
} from '@nestjs/common';
import { ApiTags, ApiResponse, ApiOperation, ApiUnauthorizedResponse, ApiForbiddenResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { ApiTags, ApiResponse, ApiOperation, ApiUnauthorizedResponse, ApiForbiddenResponse, ApiBearerAuth } from '@nestjs/swagger';
import { GetUser } from '../authz/decorators/get-user.decorator';
import { AuthGuard } from '@nestjs/passport';
import { UnauthorizedErrorDto } from '../dtos/unauthorized-error.dto';
Expand All @@ -30,43 +30,74 @@ import { user } from '@prisma/client';
import { CreateTenantDto } from './dto/create-tenant.dto';
import { User } from '../authz/decorators/user.decorator';
import { CustomExceptionFilter } from 'apps/api-gateway/common/exception-handler';
import { Roles } from '../authz/decorators/roles.decorator';
import { OrgRoles } from 'libs/org-roles/enums';
import { OrgRolesGuard } from '../authz/guards/org-roles.guard';

const seedLength = 32;
@UseFilters(CustomExceptionFilter)
@Controller('agent-service')
@Controller()
@ApiTags('agents')
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
@ApiUnauthorizedResponse({ status: 401, description: 'Unauthorized', type: UnauthorizedErrorDto })
@ApiForbiddenResponse({ status: 403, description: 'Forbidden', type: ForbiddenErrorDto })
export class AgentController {
constructor(private readonly agentService: AgentService) { }

private readonly logger = new Logger();

@Get('/orgs/:orgId/agents/health')
@ApiOperation({
summary: 'Get the agent health details',
description: 'Get the agent health details'
})
@UseGuards(AuthGuard('jwt'))
async getAgentHealth(@User() reqUser: user, @Param('orgId') orgId: number, @Res() res: Response): Promise<object> {
const agentData = await this.agentService.getAgentHealth(reqUser, orgId);

const finalResponse: IResponseType = {
statusCode: HttpStatus.OK,
message: ResponseMessages.agent.success.health,
data: agentData.response
};

return res.status(HttpStatus.OK).json(finalResponse);

}

/**
*
* @param agentSpinupDto
* @param user
* @returns
*/
@Post('/spinup')
@Post('/orgs/:orgId/agents/spinup')
@ApiOperation({
summary: 'Agent spinup',
description: 'Create a new agent spin up.'
})
@UseGuards(AuthGuard('jwt'), OrgRolesGuard)
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN)
@ApiResponse({ status: 201, description: 'Success', type: ApiResponseDto })
async agentSpinup(
@Body() agentSpinupDto: AgentSpinupDto,
@Param('orgId') orgId: number,
@GetUser() user: user,
@Res() res: Response
): Promise<Response<object, Record<string, object>>> {

if (seedLength !== agentSpinupDto.seed.length) {
throw new BadRequestException(`seed must be at most 32 characters.`);
}

const regex = new RegExp('^[a-zA-Z0-9]+$');

if (!regex.test(agentSpinupDto.walletName)) {
this.logger.error(`Wallet name in wrong format.`);
throw new BadRequestException(`Please enter valid wallet name, It allows only alphanumeric values`);
}
this.logger.log(`**** Spin up the agent...${JSON.stringify(agentSpinupDto)}`);

agentSpinupDto.orgId = orgId;
const agentDetails = await this.agentService.agentSpinup(agentSpinupDto, user);

const finalResponse: IResponseType = {
Expand All @@ -78,17 +109,27 @@ export class AgentController {
return res.status(HttpStatus.CREATED).json(finalResponse);
}

@Post('/tenant')
@Post('/orgs/:orgId/agents/wallet')
@ApiOperation({
summary: 'Shared Agent',
description: 'Create a shared agent.'
})
@UseGuards(AuthGuard('jwt'), OrgRolesGuard)
@Roles(OrgRoles.OWNER, OrgRoles.ADMIN)
@ApiResponse({ status: 201, description: 'Success', type: ApiResponseDto })
async createTenant(
@Param('orgId') orgId: number,
@Body() createTenantDto: CreateTenantDto,
@GetUser() user: user,
@Res() res: Response
): Promise<object> {

createTenantDto.orgId = orgId;

if (seedLength !== createTenantDto.seed.length) {
throw new BadRequestException(`seed must be at most 32 characters.`);
}

const tenantDetails = await this.agentService.createTenant(createTenantDto, user);

const finalResponse: IResponseType = {
Expand All @@ -99,28 +140,4 @@ export class AgentController {

return res.status(HttpStatus.CREATED).json(finalResponse);
}

@Get('/health')
@ApiOperation({
summary: 'Fetch agent details',
description: 'Fetch agent health details'
})
@ApiQuery({
name: 'orgId',
type: Number,
required: false
})
async getAgentHealth(@User() reqUser: user, @Query('orgId') orgId: number, @Res() res: Response): Promise<object> {
const agentData = await this.agentService.getAgentHealth(reqUser, orgId);

const finalResponse: IResponseType = {
statusCode: HttpStatus.OK,
message: ResponseMessages.agent.success.health,
data: agentData.response
};

return res.status(HttpStatus.OK).json(finalResponse);

}

}
}
19 changes: 11 additions & 8 deletions apps/api-gateway/src/agent-service/dto/agent-service.dto.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { trim } from '@credebl/common/cast.helper';
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsBoolean, IsNotEmpty, IsNumber, IsOptional, IsString, Matches, MaxLength, MinLength } from 'class-validator';
const regex = /^[a-zA-Z0-9 ]*$/;
export class AgentSpinupDto {

orgId: number;

@ApiProperty()
@Transform(({ value }) => trim(value))
@IsNotEmpty({ message: 'walletName is required'})
Expand All @@ -31,28 +33,28 @@ export class AgentSpinupDto {
@Matches(/^\S*$/, {
message: 'Spaces are not allowed in seed'
})
seed: string;

@ApiProperty()
@IsNumber()
orgId: number;
seed: string;

@ApiProperty()
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
ledgerId?: number;

@ApiProperty()
@IsOptional()
@ApiPropertyOptional()
clientSocketId?: string;

@ApiProperty()
@IsOptional()
@IsBoolean()
@IsBoolean()
@ApiPropertyOptional()
tenant?: boolean;

@ApiProperty()
@IsOptional()
@ApiPropertyOptional()
@Transform(({ value }) => trim(value))
@IsNotEmpty({ message: 'agentType is required'})
@MinLength(2, { message: 'agentType must be at least 2 characters.' })
Expand All @@ -62,10 +64,11 @@ export class AgentSpinupDto {

@ApiProperty()
@IsOptional()
@ApiPropertyOptional()
@Transform(({ value }) => trim(value))
@IsNotEmpty({ message: 'transactionApproval is required'})
@MinLength(2, { message: 'transactionApproval must be at least 2 characters.' })
@MaxLength(50, { message: 'transactionApproval must be at most 50 characters.' })
@IsString({ message: 'transactionApproval must be in string format.' })
transactionApproval?: string;
}
}
Loading

0 comments on commit 80a0c66

Please sign in to comment.