Skip to content

Commit

Permalink
Merge pull request #379 from credebl/refactor-sign-in-sign-up-api
Browse files Browse the repository at this point in the history
Refactor sign in and sign up api
  • Loading branch information
vivekayanworks authored Dec 27, 2023
2 parents eda3786 + 2358144 commit d7a4ef3
Show file tree
Hide file tree
Showing 12 changed files with 81 additions and 52 deletions.
27 changes: 10 additions & 17 deletions apps/api-gateway/src/authz/authz.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { Response } from 'express';
import { EmailVerificationDto } from '../user/dto/email-verify.dto';
import { AuthTokenResponse } from './dtos/auth-token-res.dto';
import { LoginUserDto } from '../user/dto/login-user.dto';
import { AddUserDetails } from '../user/dto/add-user.dto';
import { AddUserDetailsDto } from '../user/dto/add-user.dto';
import { CustomExceptionFilter } from 'apps/api-gateway/common/exception-handler';


Expand Down Expand Up @@ -71,37 +71,30 @@ export class AuthzController {

/**
*
* @param email
* @param userInfo
* @param res
* @returns Add new user
* @Body userInfo
* @returns User's registration status
*/
@Post('/signup')
@ApiOperation({ summary: 'Register new user to platform', description: 'Register new user to platform' })
async addUserDetails(@Body() userInfo: AddUserDetails, @Res() res: Response): Promise<Response> {
const userDetails = await this.authzService.addUserDetails(userInfo);
async addUserDetails(@Body() userInfo: AddUserDetailsDto, @Res() res: Response): Promise<Response> {
await this.authzService.addUserDetails(userInfo);
const finalResponse = {
statusCode: HttpStatus.CREATED,
message: ResponseMessages.user.success.create,
data: userDetails.response
message: ResponseMessages.user.success.create
};
return res.status(HttpStatus.CREATED).json(finalResponse);

}


/**
*
* @param loginUserDto
* @param res
* @returns User access token details
* @Body loginUserDto
* @returns User's access token details
*/
@Post('/signin')
@ApiOperation({
summary: 'Authenticate the user for the access',
description: 'Authenticate the user for the access'
})
@ApiResponse({ status: 200, description: 'Success', type: AuthTokenResponse })
@ApiResponse({ status: HttpStatus.OK, description: 'Success', type: AuthTokenResponse })
@ApiBody({ type: LoginUserDto })
async login(@Body() loginUserDto: LoginUserDto, @Res() res: Response): Promise<Response> {

Expand All @@ -110,7 +103,7 @@ export class AuthzController {
const finalResponse: IResponseType = {
statusCode: HttpStatus.OK,
message: ResponseMessages.user.success.login,
data: userData.response
data: userData
};

return res.status(HttpStatus.OK).json(finalResponse);
Expand Down
16 changes: 8 additions & 8 deletions apps/api-gateway/src/authz/authz.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import {
} from '@nestjs/websockets';
import { UserEmailVerificationDto } from '../user/dto/create-user.dto';
import { EmailVerificationDto } from '../user/dto/email-verify.dto';
import { AddUserDetails } from '../user/dto/add-user.dto';

import { AddUserDetailsDto } from '../user/dto/add-user.dto';
import { ISendVerificationEmail, ISignInUser, IVerifyUserEmail } from '@credebl/common/interfaces/user.interface';

@Injectable()
@WebSocketGateway()
Expand All @@ -28,23 +28,23 @@ export class AuthzService extends BaseService {
return this.sendNats(this.authServiceProxy, 'get-user-by-keycloakUserId', keycloakUserId);
}

async sendVerificationMail(userEmailVerification: UserEmailVerificationDto): Promise<UserEmailVerificationDto> {
async sendVerificationMail(userEmailVerification: UserEmailVerificationDto): Promise<ISendVerificationEmail> {
const payload = { userEmailVerification };
return this.sendNatsMessage(this.authServiceProxy, 'send-verification-mail', payload);
}

async verifyEmail(param: EmailVerificationDto): Promise<EmailVerificationDto> {
async verifyEmail(param: EmailVerificationDto): Promise<IVerifyUserEmail> {
const payload = { param };
return this.sendNatsMessage(this.authServiceProxy, 'user-email-verification', payload);
}

async login(email: string, password?: string, isPasskey = false): Promise<{ response: object }> {
async login(email: string, password?: string, isPasskey = false): Promise<ISignInUser> {
const payload = { email, password, isPasskey };
return this.sendNats(this.authServiceProxy, 'user-holder-login', payload);
return this.sendNatsMessage(this.authServiceProxy, 'user-holder-login', payload);
}

async addUserDetails(userInfo: AddUserDetails): Promise<{ response: string }> {
async addUserDetails(userInfo: AddUserDetailsDto): Promise<string> {
const payload = { userInfo };
return this.sendNats(this.authServiceProxy, 'add-user', payload);
return this.sendNatsMessage(this.authServiceProxy, 'add-user', payload);
}
}
5 changes: 3 additions & 2 deletions apps/api-gateway/src/dtos/email-validator.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { IsEmail, IsNotEmpty, MaxLength } from 'class-validator';
export class EmailValidator {

@ApiProperty()
@IsNotEmpty({ message: 'Email is required.' })
@MaxLength(256, { message: 'Email must be at most 256 character.' })
@IsEmail({}, { message: 'Please provide a valid email' })
@IsNotEmpty({ message: 'Email is required' })
@MaxLength(256, { message: 'Email must be at most 256 character' })
@IsEmail()
email: string;
}
8 changes: 6 additions & 2 deletions apps/api-gateway/src/user/dto/add-user.dto.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { trim } from '@credebl/common/cast.helper';
import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsBoolean, IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator';
import { IsBoolean, IsEmail, IsNotEmpty, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';

export class AddUserDetails {
export class AddUserDetailsDto {

@ApiProperty({ example: 'awqx@getnada.com' })
@IsEmail({}, { message: 'Please provide a valid email' })
Expand All @@ -13,11 +13,15 @@ export class AddUserDetails {

@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.' })
@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.' })
@IsString({ message: 'Last name should be a string' })
lastName: string;

Expand Down
5 changes: 3 additions & 2 deletions apps/api-gateway/src/user/dto/create-user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ export class UserEmailVerificationDto {
@ApiProperty()
@Transform(({ value }) => trim(value))
@Transform(({ value }) => toLowerCase(value))
@IsNotEmpty({ message: 'Email is required.' })
@MaxLength(256, { message: 'Email must be at most 256 character.' })
@IsEmail({}, { message: 'Please provide a valid email' })
@IsNotEmpty({ message: 'Email is required' })
@MaxLength(256, { message: 'Email must be at most 256 character' })
@IsEmail()
email: string;
}
5 changes: 3 additions & 2 deletions apps/api-gateway/src/user/dto/email-verify.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ export class EmailVerificationDto {
@ApiProperty()
@Transform(({ value }) => trim(value))
@Transform(({ value }) => toLowerCase(value))
@IsNotEmpty({ message: 'Email is required.' })
@MaxLength(256, { message: 'Email must be at most 256 character.' })
@IsEmail({}, { message: 'Please provide a valid email' })
@IsNotEmpty({ message: 'Email is required' })
@MaxLength(256, { message: 'Email must be at most 256 character' })
@IsEmail()
email: string;

Expand Down
4 changes: 2 additions & 2 deletions apps/api-gateway/src/user/dto/login-user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { trim } from '@credebl/common/cast.helper';

export class LoginUserDto {
@ApiProperty({ example: 'awqx@getnada.com' })
@IsEmail()
@IsNotEmpty({ message: 'Please provide valid email' })
@IsEmail({}, { message: 'Please provide a valid email' })
@IsNotEmpty({ message: 'Email is required' })
@IsString({ message: 'email should be string' })
email: string;

Expand Down
15 changes: 10 additions & 5 deletions apps/user/interfaces/user.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ interface IUserOrgRole {
email?: string;
orgRoles: string[];
}

export interface ISendVerificationEmail {
export interface ISendVerificationEmail {
email: string;
username?: string;
}
Expand Down Expand Up @@ -176,8 +176,13 @@ interface IUserOrgRole {
search: string;
}

export class IVerifyUserEmail {
email: string;
verificationCode: string;
export interface IVerifyUserEmail{
email: string;
verificationCode: string;
}

export interface IUserSignIn{
email: string;
password: string;
isPasskey: boolean;
}
16 changes: 12 additions & 4 deletions apps/user/src/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { AddPasskeyDetails, ICheckUserDetails, PlatformSettings, ShareUserCertificate, UpdateUserProfile, UserCredentials, IUserInformation, IUsersProfile, UserInvitations, ISendVerificationEmail, IVerifyUserEmail} from '../interfaces/user.interface';
import { AddPasskeyDetails, ICheckUserDetails, PlatformSettings, ShareUserCertificate, UpdateUserProfile, UserCredentials, IUsersProfile, UserInvitations, IUserInformation, IUserSignIn} from '../interfaces/user.interface';
import {IOrgUsers, Payload} from '../interfaces/user.interface';

import { AcceptRejectInvitationDto } from '../dtos/accept-reject-invitation.dto';
import { Controller } from '@nestjs/common';
import { LoginUserDto } from '../dtos/login-user.dto';
import { MessagePattern } from '@nestjs/microservices';
import { UserService } from './user.service';
import { VerifyEmailTokenDto } from '../dtos/verify-email.dto';
import { user } from '@prisma/client';
import { IUsersActivity } from 'libs/user-activity/interface';
import { ISendVerificationEmail, ISignInUser, IVerifyUserEmail } from '@credebl/common/interfaces/user.interface';

@Controller()
export class UserController {
Expand All @@ -34,9 +34,13 @@ export class UserController {
async verifyEmail(payload: { param: VerifyEmailTokenDto }): Promise<IVerifyUserEmail> {
return this.userService.verifyEmail(payload.param);
}
/**
* @Body loginUserDto
* @returns User's access token details
*/

@MessagePattern({ cmd: 'user-holder-login' })
async login(payload: LoginUserDto): Promise<object> {
async login(payload: IUserSignIn): Promise<ISignInUser> {
return this.userService.login(payload);
}

Expand Down Expand Up @@ -129,8 +133,12 @@ export class UserController {
async checkUserExist(payload: { userEmail: string }): Promise<ICheckUserDetails> {
return this.userService.checkUserExist(payload.userEmail);
}
/**
* @Body userInfo
* @returns User's registration status
*/
@MessagePattern({ cmd: 'add-user' })
async addUserDetailsInKeyCloak(payload: { userInfo: IUserInformation }): Promise<string | object> {
async addUserDetailsInKeyCloak(payload: { userInfo: IUserInformation }): Promise<string> {
return this.userService.createUserForToken(payload.userInfo);
}

Expand Down
12 changes: 6 additions & 6 deletions apps/user/src/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,9 @@ import {
IOrgUsers,
UpdateUserProfile,
UserCredentials,
ISendVerificationEmail,
IUserInformation,
IUsersProfile,
UserInvitations,
IVerifyUserEmail
UserInvitations
} from '../interfaces/user.interface';
import { AcceptRejectInvitationDto } from '../dtos/accept-reject-invitation.dto';
import { UserActivityService } from '@credebl/user-activity';
Expand All @@ -57,6 +55,7 @@ import { AwsService } from '@credebl/aws';
import puppeteer from 'puppeteer';
import { WorldRecordTemplate } from '../templates/world-record-template';
import { IUsersActivity } from 'libs/user-activity/interface';
import { ISendVerificationEmail, ISignInUser, IVerifyUserEmail } from '@credebl/common/interfaces/user.interface';

@Injectable()
export class UserService {
Expand Down Expand Up @@ -267,7 +266,7 @@ export class UserService {
const holderRoleData = await this.orgRoleService.getRole(OrgRoles.HOLDER);
await this.userOrgRoleService.createUserOrgRole(userDetails.id, holderRoleData.id);

return 'User created successfully';
return ResponseMessages.user.success.signUpUser;
} catch (error) {
this.logger.error(`Error in createUserForToken: ${JSON.stringify(error)}`);
throw new RpcException(error.response ? error.response : error);
Expand Down Expand Up @@ -312,7 +311,7 @@ export class UserService {
* @param loginUserDto
* @returns User access token details
*/
async login(loginUserDto: LoginUserDto): Promise<object> {
async login(loginUserDto: LoginUserDto): Promise<ISignInUser> {
const { email, password, isPasskey } = loginUserDto;

try {
Expand Down Expand Up @@ -344,7 +343,7 @@ export class UserService {
}
}

async generateToken(email: string, password: string): Promise<object> {
async generateToken(email: string, password: string): Promise<ISignInUser> {
try {
const supaInstance = await this.supabaseService.getClient();
this.logger.error(`supaInstance::`, supaInstance);
Expand All @@ -361,6 +360,7 @@ export class UserService {
}

const token = data?.session;

return token;
} catch (error) {
throw new RpcException(error.response ? error.response : error);
Expand Down
16 changes: 16 additions & 0 deletions libs/common/src/interfaces/user.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export interface ISignInUser {
access_token: string;
token_type?: string;
expires_in?: number;
expires_at?: number;
refresh_token?: string;
}
export interface IVerifyUserEmail{
email: string;
verificationCode: string;
}
export interface ISendVerificationEmail {
email: string;
username?: string;
}

4 changes: 2 additions & 2 deletions libs/common/src/response-messages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export const ResponseMessages = {
userActivity: 'User activities fetched successfully',
userCredentials: 'User credentials fetched successfully',
platformEcosystemettings: 'Platform and ecosystem settings updated',
fetchPlatformSettings: 'Platform settings fetched'

fetchPlatformSettings: 'Platform settings fetched',
signUpUser:'User created successfully'
},
error: {
exists: 'User already exists',
Expand Down

0 comments on commit d7a4ef3

Please sign in to comment.