Skip to content
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
163 changes: 157 additions & 6 deletions api-gateway/src/api/service/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { IAuthUser, NotificationHelper, PinoLogger } from '@guardian/common';
import { Permissions, PolicyStatus, SchemaEntity, UserRole } from '@guardian/interfaces';
import { ClientProxy } from '@nestjs/microservices';
import { Body, Controller, Get, Headers, HttpCode, HttpException, HttpStatus, Inject, Post, Req } from '@nestjs/common';
import { ApiBearerAuth, ApiBody, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AccountsResponseDTO, AccountsSessionResponseDTO, AggregatedDTOItem, BalanceResponseDTO, ChangePasswordDTO, InternalServerErrorDTO, LoginUserDTO, RegisterUserDTO } from '#middlewares';
import { ApiBearerAuth, ApiBody, ApiExtraModels, ApiInternalServerErrorResponse, ApiOkResponse, ApiOperation, ApiTags, getSchemaPath } from '@nestjs/swagger';
import { AccountsResponseDTO, AccountsSessionResponseDTO, AggregatedDTOItem, BalanceResponseDTO, ChangePasswordDTO, InternalServerErrorDTO, LoginUserDTO, RegisterUserDTO, GenerateOPTResponseDTO, EmptyResponseDTO, LoginSuccessResponseDTO, LoginOTPRequiredResponseDTO, OTPConfirmDTO, OTPConfirmResponseDTO, ObjectExamples, OTPStatusResponseDTO } from '#middlewares';
import { Auth, AuthUser, checkPermission } from '#auth';
import { EntityOwner, Guardians, InternalException, PolicyEngine, UseCache, Users } from '#helpers';
import { PolicyListResponse } from '../../entities/policy';
Expand Down Expand Up @@ -126,8 +126,22 @@ export class AccountApi {
summary: 'Logs user into the system.',
})
@ApiOkResponse({
description: 'Successful operation.',
type: AccountsSessionResponseDTO
schema: {
oneOf: [
{ $ref: getSchemaPath(LoginSuccessResponseDTO) },
{ $ref: getSchemaPath(LoginOTPRequiredResponseDTO) }
]
},
examples: {
success: {
summary: 'Successful response',
value: ObjectExamples.LOGIN_SUCCESSFUL
},
otpRequired: {
summary: 'OTP required',
value: ObjectExamples.OTP_REQUIRED_RESPONSE
}
}
})
@ApiInternalServerErrorResponse({
description: 'Internal server error.',
Expand All @@ -139,9 +153,9 @@ export class AccountApi {
@Body() body: LoginUserDTO
): Promise<AccountsSessionResponseDTO> {
try {
const { username, password } = body;
const { username, password, otp } = body;
const users = new Users();
return await users.generateNewToken(username, password);
return await users.generateNewToken(username, password, otp);
} catch (error) {
await this.logger.warn(error.message, ['API_GATEWAY'], null);
throw new HttpException(error.message, error.code || HttpStatus.UNAUTHORIZED);
Expand Down Expand Up @@ -385,4 +399,141 @@ export class AccountApi {
await InternalException(error, this.logger, user.id);
}
}

/**
* Generate an OTP secret for 2FA setup
*/
@Post('otp/generate')
@Auth()
@ApiOperation({
summary: 'Generate an OTP secret for 2FA setup.',
description: 'Generate an OTP secret for 2FA setup.',
})
@ApiOkResponse({
description: 'Successful operation.',
type: GenerateOPTResponseDTO,
})
@ApiInternalServerErrorResponse({
description: 'Internal server error.',
type: InternalServerErrorDTO,
})
@HttpCode(HttpStatus.CREATED)
async generateOtp(@AuthUser() user: IAuthUser,) {
const users = new Users();
try {
const code = await users.otpGenerateSecret(user.id);

return code

} catch (error) {
await this.logger.error(error.message, ['API_GATEWAY']);
throw new HttpException(error.message, error.code || HttpStatus.INTERNAL_SERVER_ERROR);
}
}

/**
* Confirm OTP setup
*/
@Post('otp/confirm')
@Auth()
@ApiOperation({
summary: 'Confirm OTP setup.',
description: 'Confirm OTP setup by OTP token.',
})
@ApiBody({
description: 'Configuration.',
type: OTPConfirmDTO,
required: true
})
@ApiOkResponse({
description: 'Successful operation.',
type: OTPConfirmResponseDTO,
})
@ApiInternalServerErrorResponse({
description: 'Internal server error.',
type: InternalServerErrorDTO,
})
@HttpCode(HttpStatus.CREATED)
async confirmOtp(
@AuthUser() user: IAuthUser,
@Body() body: OTPConfirmDTO
) {
const users = new Users();
try {
const token = body.token;
const result = await users.otpConfirmSecret(user.id, token);

return result;

} catch (error) {
await this.logger.error(error.message, ['API_GATEWAY']);
throw new HttpException(error.message, error.code || HttpStatus.INTERNAL_SERVER_ERROR);
}
}

/**
* Get OTP status
*/
@Get('otp/status')
@Auth()
@ApiOperation({
summary: 'Get OTP status.',
description: 'Get OTP status for the current user.',
})
@ApiOkResponse({
description: 'Successful operation.',
type: OTPStatusResponseDTO
})
@ApiInternalServerErrorResponse({
description: 'Internal server error.',
type: InternalServerErrorDTO,
})
@HttpCode(HttpStatus.OK)
async getOtpStatus(
@AuthUser() user: IAuthUser,
) {
const users = new Users();
try {
const result = await users.otpGetStatus(user.id);

return result;

} catch (error) {
await this.logger.error(error.message, ['API_GATEWAY']);
throw new HttpException(error.message, error.code || HttpStatus.INTERNAL_SERVER_ERROR);
}
}

/**
* Deactivate 2FA
*/
@Post('otp/deactivate')
@Auth()
@ApiOperation({
summary: 'Deactivate 2FA.',
description: 'Deactivate 2FA.',
})
@ApiOkResponse({
description: 'Successful operation.',
type: EmptyResponseDTO,
})
@ApiInternalServerErrorResponse({
description: 'Internal server error.',
type: InternalServerErrorDTO,
})
@HttpCode(HttpStatus.CREATED)
async deactivateOtp(
@AuthUser() user: IAuthUser,
) {
const users = new Users();
try {
const result = await users.otpDeactivate(user.id);

return result;

} catch (error) {
await this.logger.error(error.message, ['API_GATEWAY']);
throw new HttpException(error.message, error.code || HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
21 changes: 19 additions & 2 deletions api-gateway/src/helpers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,10 @@ export class Users extends NatsService {
* Register new token
* @param username
* @param password
* @param otp
*/
public async generateNewToken(username: string, password: string): Promise<AccountsSessionResponseDTO> {
return await this.sendMessage(AuthEvents.GENERATE_NEW_TOKEN, { username, password });
public async generateNewToken(username: string, password: string, otp?: string): Promise<AccountsSessionResponseDTO> {
return await this.sendMessage(AuthEvents.GENERATE_NEW_TOKEN, { username, password, otp });
}

public async generateNewAccessToken(refreshToken: string): Promise<any> {
Expand Down Expand Up @@ -447,6 +448,22 @@ export class Users extends NatsService {
): Promise<any> {
return await this.sendMessage(AuthEvents.GENERATE_RELAYER_ACCOUNT, { user });
}

public async otpGenerateSecret(userId: string) {
return await this.sendMessage(AuthEvents.OTP_GENERATE_SECRET, { userId });
}

public async otpConfirmSecret(userId: any, token: string) {
return await this.sendMessage(AuthEvents.OTP_CONFIRM_SECRET, { userId, token });
}

public async otpGetStatus(userId: string) {
return await this.sendMessage(AuthEvents.OTP_GET_STATUS, { userId });
}

public async otpDeactivate(userId: string) {
return await this.sendMessage(AuthEvents.OTP_DEACTIVATE, { userId });
}
}

@Injectable()
Expand Down
25 changes: 25 additions & 0 deletions api-gateway/src/middlewares/validation/examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,29 @@ export enum Examples {
COLOR = '#000000',
DID = '#did:hedera:testnet:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA_0.0.0000001',
HASH = 'GcDE9NsPJc7oCZvSVJySCZHxTxvjc3ZAMgtKozP1r1Eh',
OTP_NAME = 'OS Guardian',
USER_NAME_SR_1 = 'StandardRegistry',
OTP_SECRET = 'AAA0AA0A0A00A000',
OTP_AUTH_URL = 'otpauth://totp/OS%20Guardian:StandardRegistry?issuer=OS+Guardian&period=30&secret=XXX0XX0X0X00X000',
OTP_ALGO = 'sha1',
NUMBER = 111,
OTP_CODE = '111111',
TOKEN = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImIxM2E0NTkyLWU2YjQtNDg0OS1hMTkxLTAxOWVkODNkYzM5ZCIsIm5hbWUiOiJTdGFuZGFyZFJlZ2lzdHJ5IiwiZXhwaXJlQXQiOjE4MDUyODI4NjU3MDEsImlhdCI6MTc3Mzc0Njg2NX0.BsKje1bza0NEKKTAHFMRfwa3H-H-eRu7-KEDHKTftljXE3eQNmYCf_ftaPpw3DdsfsavBcEDfs5UQwlyeMsaTJPehEx_gl697rGQx6b8objGkqfFL2A7nWetMbWtxFFsIrbxs4mqHy1LM_4VVJuiXsH2DYQZkxOmw4HdyUshjE84',
ROLE_SR = 'STANDARD_REGISTRY',
ROLE_USER = 'USER'
}

export const ObjectExamples = {
LOGIN_SUCCESSFUL: {
did: Examples.DID,
refreshToken: Examples.TOKEN,
role: Examples.ROLE_SR,
username: Examples.USER_NAME_SR_1,
weakPassword: false
},

OTP_REQUIRED_RESPONSE: {
success: false,
otprequired: true
}
}
Loading
Loading