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: User module APIs. #386

Merged
merged 8 commits into from
Dec 28, 2023
15 changes: 7 additions & 8 deletions apps/api-gateway/src/user/dto/add-user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,22 @@ export class AddUserDetailsDto {

@ApiProperty({ example: 'Alen' })
@IsNotEmpty({ message: 'First name is required' })
@MinLength(2, { message: 'First name must be at least 2 characters.' })
@MaxLength(50, { message: 'First name must be at most 50 characters.' })
@MinLength(2, { message: 'First name must be at least 2 characters' })
@MaxLength(50, { message: 'First name must be at most 50 characters' })
@IsString({ message: 'First name should be a string' })
firstName: string;

@ApiProperty({ example: 'Harvey' })
@IsNotEmpty({ message: 'Last name is required' })
@MinLength(2, { message: 'Last name must be at least 2 characters.' })
@MaxLength(50, { message: 'Last name must be at most 50 characters.' })
@MinLength(2, { message: 'Last name must be at least 2 characters' })
@MaxLength(50, { message: 'Last name must be at most 50 characters' })
@IsString({ message: 'Last name should be a string' })
lastName: string;

@ApiProperty()
@Transform(({ value }) => trim(value))
@IsNotEmpty({ message: 'Password is required.' })
@IsOptional()
password?: string;
@IsNotEmpty({ message: 'Password is required' })
password: string;

@ApiProperty({ example: 'false' })
@IsOptional()
Expand All @@ -40,7 +39,7 @@ export class AddUserDetailsDto {
export class AddPasskeyDetails {
@ApiProperty()
@Transform(({ value }) => trim(value))
@IsNotEmpty({ message: 'Password is required.' })
@IsNotEmpty({ message: 'Password is required' })
password: string;

}
56 changes: 35 additions & 21 deletions apps/api-gateway/src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { UnauthorizedErrorDto } from '../dtos/unauthorized-error.dto';
import { ForbiddenErrorDto } from '../dtos/forbidden-error.dto';
import { Response } from 'express';
import { CommonService } from '@credebl/common';
import IResponseType from '@credebl/common/interfaces/response.interface';
import IResponse from '@credebl/common/interfaces/response.interface';
import { ResponseMessages } from '@credebl/common/response-messages';
import { user } from '@prisma/client';
import { AuthGuard } from '@nestjs/passport';
Expand Down Expand Up @@ -94,7 +94,7 @@ export class UserController {
@Res() res: Response
): Promise<Response> {
const users = await this.userService.get(getAllUsersDto);
const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.fetchUsers,
data: users.response
Expand All @@ -117,7 +117,7 @@ export class UserController {
async getPublicProfile(@Param('username') username: string, @Res() res: Response): Promise<object> {
const userData = await this.userService.getPublicProfile(username);

const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.fetchProfile,
data: userData.response
Expand All @@ -136,7 +136,7 @@ export class UserController {
async getProfile(@User() reqUser: user, @Res() res: Response): Promise<Response> {
const userData = await this.userService.getProfile(reqUser.id);

const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.fetchProfile,
data: userData
Expand All @@ -145,6 +145,9 @@ export class UserController {
return res.status(HttpStatus.OK).json(finalResponse);
}

/**
* @returns platform and ecosystem settings
*/
@Get('/platform-settings')
@ApiOperation({
summary: 'Get all platform and ecosystem settings',
Expand All @@ -159,7 +162,7 @@ export class UserController {
const finalResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.fetchPlatformSettings,
data: settings.response
data: settings
};

return res.status(HttpStatus.OK).json(finalResponse);
Expand All @@ -180,7 +183,7 @@ export class UserController {
): Promise<Response> {
const userDetails = await this.userService.getUserActivities(reqUser.id, limit);

const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.userActivity,
data: userDetails
Expand Down Expand Up @@ -231,7 +234,7 @@ export class UserController {
getAllInvitationsDto
);

const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.fetchInvitations,
data: invitations.response
Expand All @@ -250,25 +253,28 @@ export class UserController {
async checkUserExist(@Param() emailParam: EmailValidator, @Res() res: Response): Promise<Response> {
const userDetails = await this.userService.checkUserExist(emailParam.email);

const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.checkEmail,
data: userDetails
};

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

/**
* @param credentialId
* @returns User credentials
*/
@Get('/user-credentials/:credentialId')
@ApiOperation({ summary: 'Get user credentials by Id', description: 'Get user credentials by Id' })
@ApiResponse({ status: 200, description: 'Success', type: ApiResponseDto })
@ApiResponse({ status: HttpStatus.OK, description: 'Success', type: ApiResponseDto })
async getUserCredentialsById(@Param('credentialId') credentialId: string, @Res() res: Response): Promise<Response> {
const getUserCrdentialsById = await this.userService.getUserCredentialsById(credentialId);

const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.userCredentials,
data: getUserCrdentialsById.response
data: getUserCrdentialsById
};
return res.status(HttpStatus.OK).json(finalResponse);
}
Expand Down Expand Up @@ -296,33 +302,36 @@ export class UserController {
acceptRejectInvitation.invitationId = invitationId;
const invitationRes = await this.userService.acceptRejectInvitaion(acceptRejectInvitation, reqUser.id);

const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.CREATED,
message: invitationRes.response
};
return res.status(HttpStatus.CREATED).json(finalResponse);
}

/**
* @Body shareUserCredentials
* @returns User certificate url
*/
@Post('/certificate')
@ApiOperation({
summary: 'Share user certificate',
description: 'Share user certificate'
})
@ApiResponse({ status: 200, description: 'Success', type: ApiResponseDto })
@ApiResponse({ status: HttpStatus.OK, description: 'Success', type: ApiResponseDto })
async shareUserCertificate(
@Body() shareUserCredentials: CreateUserCertificateDto,
@Res() res: Response
): Promise<object> {
): Promise<Response> {
const schemaIdParts = shareUserCredentials.schemaId.split(':');
// eslint-disable-next-line prefer-destructuring
const title = schemaIdParts[2];

const imageBuffer = await this.userService.shareUserCertificate(shareUserCredentials);
const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.CREATED,
message: 'Certificate url generated successfully',
message: ResponseMessages.user.success.shareUserCertificate,
label: title,
data: imageBuffer.response
data: imageBuffer
};
return res.status(HttpStatus.CREATED).json(finalResponse);
}
Expand All @@ -344,7 +353,7 @@ export class UserController {
updateUserProfileDto.id = userId;
await this.userService.updateUserProfile(updateUserProfileDto);

const finalResponse: IResponseType = {
const finalResponse: IResponse = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.update
};
Expand All @@ -370,6 +379,11 @@ export class UserController {
return res.status(HttpStatus.OK).json(finalResponse);
}

/**
* @Body platformSettings
* @returns platform and ecosystem settings updated status
*/

@Put('/platform-settings')
@ApiOperation({
summary: 'Update platform and ecosystem settings',
Expand All @@ -386,7 +400,7 @@ export class UserController {

const finalResponse = {
statusCode: HttpStatus.OK,
message: result.response
message: result
};

return res.status(HttpStatus.OK).json(finalResponse);
Expand Down
6 changes: 3 additions & 3 deletions apps/api-gateway/src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export class UserService extends BaseService {
shareUserCredentials: CreateUserCertificateDto
): Promise<{ response: Buffer }> {
const payload = { shareUserCredentials};
return this.sendNats(this.serviceProxy, 'share-user-certificate', payload);
return this.sendNatsMessage(this.serviceProxy, 'share-user-certificate', payload);
}

async get(
Expand Down Expand Up @@ -91,10 +91,10 @@ export class UserService extends BaseService {

async updatePlatformSettings(platformSettings: UpdatePlatformSettingsDto): Promise<{ response: string }> {
const payload = { platformSettings };
return this.sendNats(this.serviceProxy, 'update-platform-settings', payload);
return this.sendNatsMessage(this.serviceProxy, 'update-platform-settings', payload);
}

async getPlatformSettings(): Promise<{ response: object }> {
return this.sendNats(this.serviceProxy, 'fetch-platform-settings', '');
return this.sendNatsMessage(this.serviceProxy, 'fetch-platform-settings', '');
}
}
4 changes: 2 additions & 2 deletions apps/user/interfaces/user.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,10 @@ export interface ISendVerificationEmail {
}

export interface ICheckUserDetails {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we reduce no. of fields as discussed earlier?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes sir.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved.

isExist: boolean;
isRegistrationCompleted: boolean;
isEmailVerified?: boolean;
isFidoVerified?: boolean;
isSupabase?: boolean;
isAuthenticated?: boolean;
}

export interface UserCredentials {
Expand Down
17 changes: 11 additions & 6 deletions apps/user/src/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ export class UserController {
async findUserByEmail(payload: { email }): Promise<object> {
return this.userService.findUserByEmail(payload);
}


/**
* @param credentialId
* @returns User credentials
*/
@MessagePattern({ cmd: 'get-user-credentials-by-id' })
async getUserCredentialsById(payload: { credentialId }): Promise<UserCredentials> {
return this.userService.getUserCredentialsById(payload);
Expand All @@ -94,9 +96,8 @@ export class UserController {
}

/**
*
* @param payload
* @returns Share user certificate
* @returns User certificate url
*/
@MessagePattern({ cmd: 'share-user-certificate' })
async shareUserCertificate(payload: {
Expand Down Expand Up @@ -152,12 +153,16 @@ export class UserController {
async addPasskey(payload: { userEmail: string, userInfo: AddPasskeyDetails }): Promise<string | object> {
return this.userService.addPasskey(payload.userEmail, payload.userInfo);
}

/**
* @returns platform and ecosystem settings updated status
*/
@MessagePattern({ cmd: 'update-platform-settings' })
async updatePlatformSettings(payload: { platformSettings: PlatformSettings }): Promise<string> {
return this.userService.updatePlatformSettings(payload.platformSettings);
}

/**
* @returns platform and ecosystem settings
*/
@MessagePattern({ cmd: 'fetch-platform-settings' })
async getPlatformEcosystemSettings(): Promise<object> {
return this.userService.getPlatformEcosystemSettings();
Expand Down
22 changes: 11 additions & 11 deletions apps/user/src/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -457,19 +457,21 @@ export class UserService {
if (!userData) {
throw new NotFoundException(ResponseMessages.user.error.notFound);
}


const invitationsData = await this.getOrgInvitations(
userData.email,
payload.status,
payload.pageNumber,
payload.pageSize,
payload.search
);

const invitations: OrgInvitations[] = await this.updateOrgInvitations(invitationsData['invitations']);
invitationsData['invitations'] = invitations;
);
const invitations: OrgInvitations[] = await this.updateOrgInvitations(invitationsData['invitations']);
invitationsData['invitations'] = invitations;

return invitationsData;

} catch (error) {
this.logger.error(`Error in get invitations: ${JSON.stringify(error)}`);
throw new RpcException(error.response ? error.response : error);
Expand Down Expand Up @@ -510,6 +512,8 @@ export class UserService {
}

async updateOrgInvitations(invitations: OrgInvitations[]): Promise<OrgInvitations[]> {


const updatedInvitations = [];

for (const invitation of invitations) {
Expand Down Expand Up @@ -546,10 +550,6 @@ export class UserService {
}
}

/**
*
* @returns
*/
async shareUserCertificate(shareUserCertificate: ShareUserCertificate): Promise<string> {

const attributeArray = [];
Expand Down Expand Up @@ -735,14 +735,14 @@ export class UserService {
throw new ConflictException(ResponseMessages.user.error.exists);
} else if (null === userDetails) {
return {
isExist: false
isRegistrationCompleted: false
};
} else {
const userVerificationDetails = {
isEmailVerified: userDetails.isEmailVerified,
isFidoVerified: userDetails.isFidoVerified,
isSupabase: null !== userDetails.supabaseUserId && undefined !== userDetails.supabaseUserId,
isExist: true
isAuthenticated: null !== userDetails.supabaseUserId && undefined !== userDetails.supabaseUserId,
isRegistrationCompleted: true
};
return userVerificationDetails;
}
Expand Down
3 changes: 2 additions & 1 deletion libs/common/src/response-messages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ export const ResponseMessages = {
userCredentials: 'User credentials fetched successfully',
platformEcosystemettings: 'Platform and ecosystem settings updated',
fetchPlatformSettings: 'Platform settings fetched',
signUpUser:'User created successfully'
signUpUser:'User created successfully',
shareUserCertificate:'Certificate url generated successfully'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

URL should be in capital letters.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved.

},
error: {
exists: 'User already exists',
Expand Down