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

[@dhealthdapps/backend] fix(routes): add drop of integration in case … #118

Open
wants to merge 10 commits into
base: next
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions runtime/backend/src/common/services/QueryService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// external dependencies
import { Injectable } from "@nestjs/common";
import { Model, FilterQuery, PipelineStage, Aggregate } from "mongoose";
import { DeleteResult } from "mongodb";

// internal dependencies
import { Documentable } from "../concerns/Documentable";
Expand Down Expand Up @@ -306,6 +307,24 @@ export class QueryService<
.exec();
}

/**
* This method deletes *exactly one document* in a collection.
* Item to delete is defined by query.
* <br /><br />
*
* @access public
* @async
* @param {Queryable<TDocument>} query The query configuration with `sort`, `order`, `pageNumber`, `pageSize`.
* @param {TModel} model The model *class instance* used for the resulting document.
* @returns {Promise<TDocument>}
*/
public async deleteOne(
query: Queryable<TDocument>,
model: TModel,
): Promise<DeleteResult> {
return await model.deleteOne(query).exec();
}

/**
* Method to update a batch of documents in one collection. The
* query built here uses a document's `_id` field value and
Expand Down
42 changes: 41 additions & 1 deletion runtime/backend/src/oauth/routes/OAuthController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
HttpException,
UseGuards,
HttpStatus,
Delete,
} from "@nestjs/common";
import {
ApiExtraModels,
Expand Down Expand Up @@ -201,7 +202,46 @@ export class OAuthController {
// create a "success" status response
return StatusDTO.create(200);
} catch (e) {
if (e instanceof HttpException) throw e;
if (e instanceof HttpException) {
this.oauthService.deleteIntegration(provider, account.address);
throw e;
}
throw new HttpException("Bad Request", HttpStatus.BAD_REQUEST);
}
}

/**
* Revoke existing integration with passed provider.
*
* @method DELETE
* @param req
* @param provider
* @param query
* @returns
*/
@UseGuards(AuthGuard)
@Delete("oauth/:provider/revoke")
@ApiOperation({
summary: "Remove existing integration",
description: "Remove existing provider from integrations",
})
@ApiExtraModels(OAuthCallbackRequest, StatusDTO)
@ApiOkResponse(HTTPResponses.OAuthLinkResponseSchema)
protected async revoke(
@NestRequest() req: Request,
@Param("provider") provider: string,
) {
// read and decode access token, then find account in database
const account: AccountDocument = await this.authService.getAccount(req);
try {
return await this.oauthService.deleteIntegration(
provider,
account.address,
);
} catch (e) {
if (e instanceof HttpException) {
throw e;
}
throw new HttpException("Bad Request", HttpStatus.BAD_REQUEST);
}
}
Expand Down
24 changes: 24 additions & 0 deletions runtime/backend/src/oauth/services/OAuthService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ export class OAuthService {
>,
private readonly cipher: CipherService,
) {}
/**
* This property represents valid scope
* received from provider.
*
*/
expectedScope = "read,activity:read_all";

/**
* This method determines and creates an OAuth driver
Expand Down Expand Up @@ -202,6 +208,10 @@ export class OAuthService {
if (!integration || !("address" in integration)) {
throw new HttpException(`Forbidden`, 403);
}
// if scope not contains read_all - throw an exception
if (request && request.scope !== this.expectedScope) {
throw new HttpException(`Forbidden`, 403);
}

// reads OAuth provider from configuration
const provider = this.getProvider(providerName);
Expand Down Expand Up @@ -453,6 +463,20 @@ export class OAuthService {
return integration;
}

public async deleteIntegration(providerName: string, address: string) {
try {
await this.queryService.deleteOne(
new AccountIntegrationQuery({
address,
name: providerName,
} as AccountIntegrationDocument),
this.model,
);
} catch (e) {
throw e;
}
}

/**
* Method to find {@link AccountIntegrationDocument} from the
* database by querying with fields of an {@link AccountDocument}.
Expand Down
113 changes: 66 additions & 47 deletions runtime/backend/tests/mocks/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const TestWinstonLogger = {
error: jest.fn(),
verbose: jest.fn(),
setLogLevels: jest.fn(),
}
};
jest.mock("nest-winston", () => ({
utilities: {
format: {
Expand All @@ -86,10 +86,10 @@ jest.mock("nest-winston", () => ({
WinstonModule: { createLogger: jest.fn().mockReturnValue(TestWinstonLogger) },
}));

export class TestMongoDBTransport {};
export class TestConsoleTransport {};
export class TestDailyRotateFileTransport {};
export class TestFileTransportErrors {};
export class TestMongoDBTransport {}
export class TestConsoleTransport {}
export class TestDailyRotateFileTransport {}
export class TestFileTransportErrors {}
jest.mock("winston", () => ({
format: {
timestamp: jest.fn(),
Expand All @@ -102,18 +102,18 @@ jest.mock("winston", () => ({
Console: TestConsoleTransport,
DailyRotateFile: TestDailyRotateFileTransport,
File: TestFileTransportErrors,
}
},
}));

// Mocks an unsigned transfer transaction with message
export const mockUnsignedTransferTransaction =
"C400000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "000000000000000000000000016854410100000000000000545873E209000000"
+ "68B09718CA4D1CF2A6E97CAE1AB192B1317E1EDB519349CC1400010000000000"
+ "59A422A39FC4E03940420F0000000000007468697320697320746865206D6573"
+ "73616765";
export const mockUnsignedTransferTransaction =
"C400000000000000000000000000000000000000000000000000000000000000" +
"0000000000000000000000000000000000000000000000000000000000000000" +
"0000000000000000000000000000000000000000000000000000000000000000" +
"000000000000000000000000016854410100000000000000545873E209000000" +
"68B09718CA4D1CF2A6E97CAE1AB192B1317E1EDB519349CC1400010000000000" +
"59A422A39FC4E03940420F0000000000007468697320697320746865206D6573" +
"73616765";

const mockMosaicId = "fake-mosaic-id";

Expand All @@ -126,7 +126,7 @@ export const createTransaction = (
): any => ({
transactionInfo: { hash, height: { compact: jest.fn() } },
signer: { address: { plain: jest.fn() } },
recipientAddress: { plain: jest.fn()},
recipientAddress: { plain: jest.fn() },
type,
serialize: jest.fn().mockReturnValue(mockUnsignedTransferTransaction),
message: { payload: "fakePayload" },
Expand All @@ -137,8 +137,8 @@ export const createTransaction = (
compact: jest.fn(),
equals: jest.fn().mockReturnValue(false),
},
}
]
},
],
});

// Mocks a **transaction document** factory for internal
Expand All @@ -156,11 +156,13 @@ export const createTransactionDocument = (
transactionMode: transactionMode,
transactionType: "fake-type",
creationBlock: 1,
transactionAssets: [{
mosaicId: "testMosaicId",
amount: 1,
transactionHash: "testTransactionHash",
}],
transactionAssets: [
{
mosaicId: "testMosaicId",
amount: 1,
transactionHash: "testTransactionHash",
},
],
transactionMessage: "fakeMessage",
});

Expand Down Expand Up @@ -191,6 +193,11 @@ export class MockModel {
exec: () => jest.fn(),
};
}
// deleteOne() {
// return {
// exec: () => jest.fn(),
// };
// }
static findOneAndUpdate() {
return {
exec: () => jest.fn(),
Expand All @@ -201,6 +208,16 @@ export class MockModel {
exec: () => this.data,
};
}
deleteOne(query: any) {
return {
exec: async () => jest.fn(),
};
}
static deleteOne(query: any) {
return {
exec: async () => jest.fn(),
};
}
aggregate(param: any) {
return jest
.fn((param) => ({
Expand Down Expand Up @@ -237,37 +254,39 @@ export class MockModel {
export const httpQueryStringParser = (
search: string,
decode: boolean = true,
): Record<string, string> => (search || '')
.replace(/^\?/g, '')
.split('&')
.reduce((acc, query) => {
const [key, value] = query.split('=');
if (key) {
acc[key] = decode ? decodeURIComponent(value) : value;
}
return acc;
}, {} as Record<string, string>);
): Record<string, string> =>
(search || "")
.replace(/^\?/g, "")
.split("&")
.reduce((acc, query) => {
const [key, value] = query.split("=");
if (key) {
acc[key] = decode ? decodeURIComponent(value) : value;
}
return acc;
}, {} as Record<string, string>);

// sets mocked environment variables
process.env.DB_USER = "fake-user";
process.env.DB_PASS = "fake-pass";
process.env.DB_HOST = "fake-host";
process.env.DB_PORT = "1234";
process.env.DB_NAME = "fake-db-name";
process.env.BACKEND_URL="fake-backend-url";
process.env.BACKEND_DOMAIN="fake-backend-host";
process.env.BACKEND_INTERNAL_PORT="4321";
process.env.BACKEND_EXTERNAL_PORT="4321";
process.env.FRONTEND_URL="fake-frontend-url";
process.env.FRONTEND_DOMAIN="fake-frontend-host";
process.env.FRONTEND_PORT="9876";
process.env.SECURITY_AUTH_TOKEN_SECRET="fake-auth-token";
process.env.BACKEND_URL = "fake-backend-url";
process.env.BACKEND_DOMAIN = "fake-backend-host";
process.env.BACKEND_INTERNAL_PORT = "4321";
process.env.BACKEND_EXTERNAL_PORT = "4321";
process.env.FRONTEND_URL = "fake-frontend-url";
process.env.FRONTEND_DOMAIN = "fake-frontend-host";
process.env.FRONTEND_PORT = "9876";
process.env.SECURITY_AUTH_TOKEN_SECRET = "fake-auth-token";
process.env.LOGS_DIRECTORY_PATH = "/logs";
process.env.SMTP_HOST="fake.smtp.server";
process.env.SMTP_PORT="587";
process.env.SMTP_USER="fakeMailerUser";
process.env.SMTP_PASSWORD="fakePassword";
process.env.FROM="Fake Mailer <[email protected]>";
process.env.SMTP_HOST = "fake.smtp.server";
process.env.SMTP_PORT = "587";
process.env.SMTP_USER = "fakeMailerUser";
process.env.SMTP_PASSWORD = "fakePassword";
process.env.FROM = "Fake Mailer <[email protected]>";
process.env.ANOTHER_DB_NAME_THROUGH_ENV = "this-exists-only-in-mock";
process.env.MAIN_PUBLIC_KEY="71BC0DB348A25D163290C44EF863B031FD5251D4E3674DCE37D78FE6C5F8E0FE"
process.env.MAIN_ADDRESS="NDAPPH6ZGD4D6LBWFLGFZUT2KQ5OLBLU32K3HNY"
process.env.MAIN_PUBLIC_KEY =
"71BC0DB348A25D163290C44EF863B031FD5251D4E3674DCE37D78FE6C5F8E0FE";
process.env.MAIN_ADDRESS = "NDAPPH6ZGD4D6LBWFLGFZUT2KQ5OLBLU32K3HNY";
Loading