📁 Changed TDrive root folder (#16)

📁 Changed TDrive root folder
This commit is contained in:
Montassar Ghanmy
2023-04-11 10:04:29 +01:00
committed by GitHub
parent 3b3f67af07
commit e0615fa867
10548 changed files with 48 additions and 48 deletions
@@ -0,0 +1 @@
test
@@ -0,0 +1,183 @@
import { afterAll, afterEach, beforeEach, describe, expect, it } from "@jest/globals";
import { deserialize } from "class-transformer";
import { AccessInformation } from "../../../src/services/documents/entities/drive-file";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import { e2e_createDocument, e2e_getDocument } from "./utils";
const url = "/internal/services/documents/v1";
describe("the Drive Tdrive tabs feature", () => {
let platform: TestPlatform;
class DriveFileMockClass {
id: string;
name: string;
size: number;
added: string;
parent_id: string;
access_info: AccessInformation;
}
class DriveItemDetailsMockClass {
path: string[];
item: DriveFileMockClass;
children: DriveFileMockClass[];
versions: Record<string, unknown>[];
}
beforeEach(async () => {
platform = await init({
services: [
"webserver",
"database",
"applications",
"search",
"storage",
"message-queue",
"user",
"search",
"files",
"websocket",
"messages",
"auth",
"realtime",
"channels",
"counter",
"statistics",
"platform-services",
"documents",
],
});
});
afterEach(async () => {
await platform.tearDown();
});
afterAll(async () => {
await platform.app.close();
});
it("did create a tab configuration on Drive side", async done => {
await TestDbService.getInstance(platform, true);
const item = {
name: "new tab test file",
parent_id: "root",
company_id: platform.workspace.company_id,
};
const version = {};
const response = await e2e_createDocument(platform, item, version);
const doc = deserialize<DriveFileMockClass>(DriveFileMockClass, response.body);
const tab = {
company_id: platform.workspace.company_id,
tab_id: "1234567890",
channel_id: "abcdefghij",
item_id: doc.id,
level: "write",
};
const token = await platform.auth.getJWTToken();
const createdTab = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/tabs/${tab.tab_id}`,
headers: {
authorization: `Bearer ${token}`,
},
payload: tab,
});
expect(createdTab.statusCode).toBe(200);
expect(createdTab.body).toBeDefined();
expect(createdTab.json().company_id).toBe(tab.company_id);
expect(createdTab.json().tab_id).toBe(tab.tab_id);
expect(createdTab.json().item_id).toBe(tab.item_id);
const getTabResponse = await platform.app.inject({
method: "GET",
url: `${url}/companies/${platform.workspace.company_id}/tabs/${tab.tab_id}`,
headers: {
authorization: `Bearer ${token}`,
},
});
expect(getTabResponse.statusCode).toBe(200);
expect(getTabResponse.body).toBeDefined();
expect(getTabResponse.json().company_id).toBe(tab.company_id);
expect(getTabResponse.json().tab_id).toBe(tab.tab_id);
expect(getTabResponse.json().item_id).toBe(tab.item_id);
const documentResponse = await e2e_getDocument(platform, doc.id);
const documentResult = deserialize<DriveItemDetailsMockClass>(
DriveItemDetailsMockClass,
documentResponse.body,
);
console.log(documentResult?.item);
expect(
documentResult?.item?.access_info?.entities?.find(
a => a?.type === "channel" && a.id === "abcdefghij" && a.level === "write",
),
).toBeDefined();
done?.();
});
it("did refuse to create a tab configuration for an item I can't manage", async done => {
const dbService = await TestDbService.getInstance(platform, true);
const ws0pk = {
id: platform.workspace.workspace_id,
company_id: platform.workspace.company_id,
};
const otherUser = await dbService.createUser([ws0pk]);
const item = {
name: "new tab test file",
parent_id: "root",
company_id: platform.workspace.company_id,
access_info: {
entities: [
{
type: "folder",
id: "parent",
level: "none",
} as any,
],
},
};
const version = {};
const response = await e2e_createDocument(platform, item, version);
const doc = deserialize<DriveFileMockClass>(DriveFileMockClass, response.body);
const tab = {
company_id: platform.workspace.company_id,
tab_id: "1234567890",
channel_id: "abcdefghij",
item_id: doc.id,
level: "read",
};
const token = await platform.auth.getJWTToken({ sub: otherUser.id });
const createdTab = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/tabs/${tab.tab_id}`,
headers: {
authorization: `Bearer ${token}`,
},
payload: tab,
});
expect(createdTab.statusCode).toBe(403);
done?.();
});
});
@@ -0,0 +1,238 @@
import { describe, beforeEach, afterEach, it, expect, afterAll } from "@jest/globals";
import { deserialize } from "class-transformer";
import { File } from "../../../src/services/files/entities/file";
import { ResourceUpdateResponse } from "../../../src/utils/types";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import {
e2e_createDocument,
e2e_createDocumentFile,
e2e_createVersion,
e2e_deleteDocument,
e2e_getDocument,
e2e_searchDocument,
e2e_updateDocument,
} from "./utils";
describe("the Drive feature", () => {
let platform: TestPlatform;
class DriveFileMockClass {
id: string;
name: string;
size: number;
added: string;
parent_id: string;
}
class DriveItemDetailsMockClass {
path: string[];
item: DriveFileMockClass;
children: DriveFileMockClass[];
versions: Record<string, unknown>[];
}
class SearchResultMockClass {
entities: DriveFileMockClass[];
}
beforeEach(async () => {
platform = await init({
services: [
"webserver",
"database",
"applications",
"search",
"storage",
"message-queue",
"user",
"search",
"files",
"websocket",
"messages",
"auth",
"realtime",
"channels",
"counter",
"statistics",
"platform-services",
"documents",
],
});
});
afterEach(async () => {
await platform.tearDown();
});
afterAll(async () => {
await platform.app.close();
});
const createItem = async (): Promise<DriveFileMockClass> => {
await TestDbService.getInstance(platform, true);
const item = {
name: "new test file",
parent_id: "root",
company_id: platform.workspace.company_id,
};
const version = {};
const response = await e2e_createDocument(platform, item, version);
return deserialize<DriveFileMockClass>(DriveFileMockClass, response.body);
};
it("did create the drive item", async done => {
const result = await createItem();
expect(result).toBeDefined();
expect(result.name).toEqual("new test file");
expect(result.added).toBeDefined();
done?.();
});
it("did fetch the drive item", async done => {
await TestDbService.getInstance(platform, true);
const response = await e2e_getDocument(platform, "");
const result = deserialize<DriveItemDetailsMockClass>(DriveItemDetailsMockClass, response.body);
expect(result.item.name).toEqual("root");
done?.();
});
it("did fetch the trash", async done => {
await TestDbService.getInstance(platform, true);
const response = await e2e_getDocument(platform, "trash");
const result = deserialize<DriveItemDetailsMockClass>(DriveItemDetailsMockClass, response.body);
expect(result.item.name).toEqual("trash");
done?.();
});
it("did delete an item", async done => {
const createItemResult = await createItem();
expect(createItemResult.id).toBeDefined();
const deleteResponse = await e2e_deleteDocument(platform, createItemResult.id);
expect(deleteResponse.statusCode).toEqual(200);
done?.();
});
it("did update an item", async done => {
const createItemResult = await createItem();
expect(createItemResult.id).toBeDefined();
const update = {
name: "somethingelse",
};
const updateItemResponse = await e2e_updateDocument(platform, createItemResult.id, update);
const updateItemResult = deserialize<DriveFileMockClass>(
DriveFileMockClass,
updateItemResponse.body,
);
expect(createItemResult.id).toEqual(updateItemResult.id);
expect(updateItemResult.name).toEqual("somethingelse");
done?.();
});
it("did move an item to trash", async done => {
const createItemResult = await createItem();
expect(createItemResult.id).toBeDefined();
const moveToTrashResponse = await e2e_deleteDocument(platform, createItemResult.id);
expect(moveToTrashResponse.statusCode).toEqual(200);
const listTrashResponse = await e2e_getDocument(platform, "trash");
const listTrashResult = deserialize<DriveItemDetailsMockClass>(
DriveItemDetailsMockClass,
listTrashResponse.body,
);
expect(listTrashResult.item.name).toEqual("trash");
expect(listTrashResult.children.some(({ id }) => id === createItemResult.id)).toBeTruthy();
done?.();
});
// TODO: wait for elastic search index
it("did search for an item", async done => {
const createItemResult = await createItem();
expect(createItemResult.id).toBeDefined();
await e2e_getDocument(platform, "root");
await e2e_getDocument(platform, createItemResult.id);
await new Promise(resolve => setTimeout(resolve, 3000));
const searchPayload = {
search: "test",
};
const searchResponse = await e2e_searchDocument(platform, searchPayload);
const searchResult = deserialize<SearchResultMockClass>(
SearchResultMockClass,
searchResponse.body,
);
expect(searchResult.entities.length).toBeGreaterThanOrEqual(1);
done?.();
});
it("did search for an item that doesn't exist", async done => {
await createItem();
const unexistingSeachPayload = {
search: "somethingthatdoesn'tandshouldn'texist",
};
const failSearchResponse = await e2e_searchDocument(platform, unexistingSeachPayload);
const failSearchResult = deserialize<SearchResultMockClass>(
SearchResultMockClass,
failSearchResponse.body,
);
expect(failSearchResult.entities).toHaveLength(0);
done?.();
});
it("did create a version for a drive item", async done => {
const item = await createItem();
const fileUploadResponse = await e2e_createDocumentFile(platform);
const fileUploadResult = deserialize<ResourceUpdateResponse<File>>(
ResourceUpdateResponse,
fileUploadResponse.body,
);
const file_metadata = { external_id: fileUploadResult.resource.id };
await e2e_createVersion(platform, item.id, { filename: "file2", file_metadata });
await e2e_createVersion(platform, item.id, { filename: "file3", file_metadata });
await e2e_createVersion(platform, item.id, { filename: "file4", file_metadata });
const fetchItemResponse = await e2e_getDocument(platform, item.id);
const fetchItemResult = deserialize<DriveItemDetailsMockClass>(
DriveItemDetailsMockClass,
fetchItemResponse.body,
);
expect(fetchItemResult.versions).toHaveLength(4);
done?.();
});
});
@@ -0,0 +1,116 @@
import { DriveFile } from "../../../src/services/documents/entities/drive-file";
import { FileVersion } from "../../../src/services/documents/entities/file-version";
import { TestPlatform } from "../setup";
import formAutoContent from "form-auto-content";
import fs from "fs";
const url = "/internal/services/documents/v1";
export const e2e_createDocument = async (
platform: TestPlatform,
item: Partial<DriveFile>,
version: Partial<FileVersion>,
) => {
const token = await platform.auth.getJWTToken();
return await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/item`,
headers: {
authorization: `Bearer ${token}`,
},
payload: {
item,
version,
},
});
};
export const e2e_getDocument = async (platform: TestPlatform, id: string | "root" | "trash") => {
const token = await platform.auth.getJWTToken();
return await platform.app.inject({
method: "GET",
url: `${url}/companies/${platform.workspace.company_id}/item/${id}`,
headers: {
authorization: `Bearer ${token}`,
},
});
};
export const e2e_deleteDocument = async (platform: TestPlatform, id: string | "root" | "trash") => {
const token = await platform.auth.getJWTToken();
return await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${platform.workspace.company_id}/item/${id}`,
headers: {
authorization: `Bearer ${token}`,
},
});
};
export const e2e_updateDocument = async (
platform: TestPlatform,
id: string | "root" | "trash",
item: Partial<DriveFile>,
) => {
const token = await platform.auth.getJWTToken();
return await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/item/${id}`,
headers: {
authorization: `Bearer ${token}`,
},
payload: item,
});
};
export const e2e_searchDocument = async (
platform: TestPlatform,
payload: Record<string, string>,
) => {
const token = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/search`,
headers: {
authorization: `Bearer ${token}`,
},
payload,
});
return response;
};
export const e2e_createVersion = async (
platform: TestPlatform,
id: string,
payload: Partial<FileVersion>,
) => {
const token = await platform.auth.getJWTToken();
return await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/item/${id}/version`,
headers: {
authorization: `Bearer ${token}`,
},
payload,
});
};
export const e2e_createDocumentFile = async (platform: TestPlatform) => {
const filePath = `${__dirname}/assets/test.txt`;
const token = await platform.auth.getJWTToken();
const form = formAutoContent({ file: fs.createReadStream(filePath) });
form.headers["authorization"] = `Bearer ${token}`;
return await platform.app.inject({
method: "POST",
url: `/internal/services/files/v1/companies/${platform.workspace.company_id}/files`,
...form,
});
};
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.
@@ -0,0 +1,198 @@
%PDF-1.3
%âãÏÓ
1 0 obj
<<
/Type /Catalog
/Outlines 2 0 R
/Pages 3 0 R
>>
endobj
2 0 obj
<<
/Type /Outlines
/Count 0
>>
endobj
3 0 obj
<<
/Type /Pages
/Count 2
/Kids [ 4 0 R 6 0 R ]
>>
endobj
4 0 obj
<<
/Type /Page
/Parent 3 0 R
/Resources <<
/Font <<
/F1 9 0 R
>>
/ProcSet 8 0 R
>>
/MediaBox [0 0 612.0000 792.0000]
/Contents 5 0 R
>>
endobj
5 0 obj
<< /Length 1074 >>
stream
2 J
BT
0 0 0 rg
/F1 0027 Tf
57.3750 722.2800 Td
( A Simple PDF File ) Tj
ET
BT
/F1 0010 Tf
69.2500 688.6080 Td
( This is a small demonstration .pdf file - ) Tj
ET
BT
/F1 0010 Tf
69.2500 664.7040 Td
( just for use in the Virtual Mechanics tutorials. More text. And more ) Tj
ET
BT
/F1 0010 Tf
69.2500 652.7520 Td
( text. And more text. And more text. And more text. ) Tj
ET
BT
/F1 0010 Tf
69.2500 628.8480 Td
( And more text. And more text. And more text. And more text. And more ) Tj
ET
BT
/F1 0010 Tf
69.2500 616.8960 Td
( text. And more text. Boring, zzzzz. And more text. And more text. And ) Tj
ET
BT
/F1 0010 Tf
69.2500 604.9440 Td
( more text. And more text. And more text. And more text. And more text. ) Tj
ET
BT
/F1 0010 Tf
69.2500 592.9920 Td
( And more text. And more text. ) Tj
ET
BT
/F1 0010 Tf
69.2500 569.0880 Td
( And more text. And more text. And more text. And more text. And more ) Tj
ET
BT
/F1 0010 Tf
69.2500 557.1360 Td
( text. And more text. And more text. Even more. Continued on page 2 ...) Tj
ET
endstream
endobj
6 0 obj
<<
/Type /Page
/Parent 3 0 R
/Resources <<
/Font <<
/F1 9 0 R
>>
/ProcSet 8 0 R
>>
/MediaBox [0 0 612.0000 792.0000]
/Contents 7 0 R
>>
endobj
7 0 obj
<< /Length 676 >>
stream
2 J
BT
0 0 0 rg
/F1 0027 Tf
57.3750 722.2800 Td
( Simple PDF File 2 ) Tj
ET
BT
/F1 0010 Tf
69.2500 688.6080 Td
( ...continued from page 1. Yet more text. And more text. And more text. ) Tj
ET
BT
/F1 0010 Tf
69.2500 676.6560 Td
( And more text. And more text. And more text. And more text. And more ) Tj
ET
BT
/F1 0010 Tf
69.2500 664.7040 Td
( text. Oh, how boring typing this stuff. But not as boring as watching ) Tj
ET
BT
/F1 0010 Tf
69.2500 652.7520 Td
( paint dry. And more text. And more text. And more text. And more text. ) Tj
ET
BT
/F1 0010 Tf
69.2500 640.8000 Td
( Boring. More, a little more text. The end, and just as well. ) Tj
ET
endstream
endobj
8 0 obj
[/PDF /Text]
endobj
9 0 obj
<<
/Type /Font
/Subtype /Type1
/Name /F1
/BaseFont /Helvetica
/Encoding /WinAnsiEncoding
>>
endobj
10 0 obj
<<
/Creator (Rave \(http://www.nevrona.com/rave\))
/Producer (Nevrona Designs)
/CreationDate (D:20060301072826)
>>
endobj
xref
0 11
0000000000 65535 f
0000000019 00000 n
0000000093 00000 n
0000000147 00000 n
0000000222 00000 n
0000000390 00000 n
0000001522 00000 n
0000001690 00000 n
0000002423 00000 n
0000002456 00000 n
0000002574 00000 n
trailer
<<
/Size 11
/Root 1 0 R
/Info 10 0 R
>>
startxref
2714
%%EOF
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.
@@ -0,0 +1,72 @@
import "reflect-metadata";
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { ResourceUpdateResponse } from "../../../src/utils/types";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import fs from "fs";
import { File } from "../../../src/services/files/entities/file";
import { deserialize } from "class-transformer";
import formAutoContent from "form-auto-content";
describe.skip("The Files feature", () => {
const url = "/internal/services/files/v1";
let platform: TestPlatform;
beforeAll(async () => {
platform = await init({
services: ["webserver", "database", "storage", "message-queue", "files", "previews"],
});
});
afterAll(async done => {
await platform?.tearDown();
platform = null;
done();
});
describe("On user send files", () => {
const files = [
"assets/sample.png",
"assets/sample.gif",
"assets/sample.pdf",
"assets/sample.doc",
"assets/sample.zip",
"assets/sample.mp4",
].map(p => `${__dirname}/${p}`);
const thumbnails = [1, 1, 2, 5, 0, 1];
it("should save file and generate previews", async done => {
for (const i in files) {
const file = files[i];
const form = formAutoContent({ file: fs.createReadStream(file) });
form.headers["authorization"] = `Bearer ${await platform.auth.getJWTToken()}`;
const filesUploadRaw = await platform.app.inject({
method: "POST",
url: `${url}/companies/${platform.workspace.company_id}/files?thumbnail_sync=1`,
...form,
});
const filesUpload: ResourceUpdateResponse<File> = deserialize(
ResourceUpdateResponse,
filesUploadRaw.body,
);
expect(filesUpload.resource.id).not.toBeFalsy();
expect(filesUpload.resource.encryption_key).toBeFalsy(); //This must not be disclosed
expect(filesUpload.resource.thumbnails.length).toBe(thumbnails[i]);
for (const thumb of filesUpload.resource.thumbnails) {
const thumbnails = await platform.app.inject({
method: "GET",
url: `${url}/companies/${platform.workspace.company_id}/files/${filesUpload.resource.id}/thumbnails/${thumb.index}`,
});
expect(thumbnails.statusCode).toBe(200);
}
}
done();
}, 120000);
});
});
+104
View File
@@ -0,0 +1,104 @@
/**
* To run all tests in local development mode:
* cd tdrive/; docker-compose -f docker-compose.dev.tests.mongo.yml run -e NODE_OPTIONS=--unhandled-rejections=warn -e SEARCH_DRIVER=mongodb -e DB_DRIVER=mongodb -e PUBSUB_TYPE=local node npm run test:e2e
*
* To run only specific tests:
* cd tdrive/; docker-compose -f docker-compose.dev.tests.mongo.yml run -e NODE_OPTIONS=--unhandled-rejections=warn -e SEARCH_DRIVER=mongodb -e DB_DRIVER=mongodb -e PUBSUB_TYPE=local node npm run test:e2e -- test/e2e/application/app-create-update.spec.ts test/e2e/application/application-events.spec.ts
*/
const fs = require("fs");
const path = require("path");
const cp = require("child_process");
let localDevTests = process.argv.slice(2);
//If we are in the CI tests we will run all the tests
if (process.env.CI || localDevTests.length === 0) {
localDevTests = false;
}
if (localDevTests) {
console.log("Only this tests will be run:", localDevTests);
} else {
console.log("Will run all the tests");
}
function exec(command, args, debug = false) {
return new Promise(done => {
const cmd = cp.spawn(command, args, {
shell: true,
});
let data = "";
let error = "";
cmd.stdout.on("data", function (data) {
if (debug) console.log(data.toString());
data += data.toString() + "\n";
});
cmd.stderr.on("data", function (data) {
if (debug) console.log(data.toString());
error += data.toString() + "\n";
});
cmd.on("exit", function (code) {
cmd.kill(9);
//The delay is to make sure we get all the missing logs
setTimeout(() => done({ code, data, error }), code === 0 ? 1 : 5000);
});
});
}
let srcFiles = [];
let srcPath = __dirname;
function throughDirectory(directory) {
fs.readdirSync(directory).forEach(file => {
const abs = path.join(directory, file);
if (fs.statSync(abs).isDirectory()) return throughDirectory(abs);
else return srcFiles.push(abs);
});
}
throughDirectory(srcPath);
srcFiles = srcFiles.filter(p => p.indexOf(".spec.ts") >= 0 || p.indexOf(".test.ts") >= 0);
(async () => {
let failed = 0;
let passed = 0;
let summary = "";
for (const path of localDevTests || srcFiles) {
const test = path.split("test/e2e/")[1];
const testName = `test/e2e/${test}`;
const args = `${testName} --forceExit --detectOpenHandles --coverage --coverageDirectory=coverage/e2e/${test} --runInBand --testTimeout=60000 --verbose=true`;
try {
//Show logs in the console if we are doing local dev tests
const out = await exec("jest", args.split(" "), !!localDevTests);
if (out.code !== 0) {
//To get all the logs, we run it again
console.log(`FAIL ${testName}`);
console.log(out.data);
console.log(out.error);
if (!localDevTests) await exec("jest", args.split(" "), true);
failed++;
summary += `FAIL ${testName}\n`;
} else {
passed++;
console.log(`PASS ${testName}`);
}
} catch (err) {
console.log(`ERROR ${testName}`);
console.log(`-- Error\n ${err}`);
failed++;
}
}
console.log(`\nResults: ${passed} passed, ${failed} failed, total ${failed + passed}`);
console.log(summary);
process.exit(failed > 0 ? 1 : 0);
})();
@@ -0,0 +1,24 @@
{
"services": [],
"webserver": {
"port": 3000,
"logger": {
"level": "warn"
}
},
"websocket": {
"path": "/socket",
"adapters": {
"types": ["redis"],
"redis": {
"host": "localhost",
"port": 6379
}
}
},
"auth": {
"jwt": {
"secret": "supersecret"
}
}
}
+125
View File
@@ -0,0 +1,125 @@
import { resolve as pathResolve } from "path";
import { v1 as uuidv1 } from "uuid";
import { FastifyInstance } from "fastify";
import { TdrivePlatform, TdrivePlatformConfiguration } from "../../../src/core/platform/platform";
import WebServerAPI from "../../../src/core/platform/services/webserver/provider";
import { DatabaseServiceAPI } from "../../../src/core/platform/services/database/api";
import AuthServiceAPI from "../../../src/core/platform/services/auth/provider";
import { Workspace } from "../../../src/utils/types";
import { MessageQueueServiceAPI } from "../../../src/core/platform/services/message-queue/api";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import config from "config";
import globalResolver from "../../../src/services/global-resolver";
type TokenPayload = {
sub: string;
org?: {
[companyId: string]: {
role: string;
};
};
};
type User = {
id: string;
isWorkspaceModerator?: boolean;
};
export interface TestPlatform {
currentUser: User;
platform: TdrivePlatform;
workspace: Workspace;
app: FastifyInstance;
database: DatabaseServiceAPI;
messageQueue: MessageQueueServiceAPI;
authService: AuthServiceAPI;
auth: {
getJWTToken(payload?: TokenPayload): Promise<string>;
};
tearDown(): Promise<void>;
}
export interface TestPlatformConfiguration {
services: string[];
}
let testPlatform: TestPlatform = null;
export async function init(
testConfig?: TestPlatformConfiguration,
prePlatformStartCallback?: (fastify: FastifyInstance) => void,
): Promise<TestPlatform> {
if (!testPlatform) {
const configuration: TdrivePlatformConfiguration = {
services: config.get("services"),
servicesPath: pathResolve(__dirname, "../../../src/services/"),
};
const platform = new TdrivePlatform(configuration);
await platform.init();
await globalResolver.doInit(platform);
const app = platform.getProvider<WebServerAPI>("webserver").getServer();
if (prePlatformStartCallback) {
prePlatformStartCallback(app);
}
await platform.start();
const database = platform.getProvider<DatabaseServiceAPI>("database");
const messageQueue = platform.getProvider<MessageQueueServiceAPI>("message-queue");
const auth = platform.getProvider<AuthServiceAPI>("auth");
testPlatform = {
platform,
app,
messageQueue,
database,
workspace: { company_id: "", workspace_id: "" },
currentUser: { id: "" },
authService: auth,
auth: {
getJWTToken,
},
tearDown,
};
}
testPlatform.app.server.close();
testPlatform.currentUser = { id: uuidv1() };
testPlatform.workspace = {
company_id: uuidv1(),
workspace_id: uuidv1(),
};
testPlatform.app.server.listen(3000);
//await testPlatform.messageQueue.start();
async function getJWTToken(
payload: TokenPayload = { sub: testPlatform.currentUser.id },
): Promise<string> {
if (!payload.sub) {
payload.sub = testPlatform.currentUser.id;
}
if (testPlatform.currentUser.isWorkspaceModerator) {
payload.org = {};
payload.org[testPlatform.workspace.company_id] = {
role: "",
};
}
return testPlatform.authService.sign(payload);
}
async function tearDown(): Promise<void> {
if (testPlatform) {
testPlatform.app.server.close();
//await testPlatform.messageQueue.stop();
}
}
return testPlatform;
}
@@ -0,0 +1,149 @@
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import { v1 as uuidv1 } from "uuid";
describe("The /users API", () => {
const url = "/internal/services/users/v1";
let platform: TestPlatform;
beforeEach(async ends => {
platform = await init({
services: [
"database",
"search",
"message-queue",
"websocket",
"webserver",
"user",
"auth",
"applications",
"storage",
"counter",
"workspaces",
"console",
"statistics",
"platform-services",
],
});
ends();
});
afterEach(async ends => {
platform && (await platform.tearDown());
platform = null;
ends();
});
describe("The GET /users/?search=... route", () => {
it("Should find the searched users", async done => {
const testDbService = new TestDbService(platform);
await testDbService.createCompany(platform.workspace.company_id);
const workspacePk = {
id: platform.workspace.workspace_id,
company_id: platform.workspace.company_id,
};
const workspacePk2 = {
id: uuidv1(),
company_id: uuidv1(),
};
await testDbService.createWorkspace(workspacePk);
await testDbService.createWorkspace(workspacePk2);
await testDbService.createUser([workspacePk], {
firstName: "Ha",
lastName: "Nguyen",
email: "hnguyen@tdrive.app",
});
await testDbService.createUser([workspacePk], {
firstName: "Harold",
lastName: "Georges",
email: "hgeorges@tdrive.app",
});
await testDbService.createUser([workspacePk], {
firstName: "Bob",
lastName: "Smith",
email: "bob@tdrive.app",
});
await testDbService.createUser([workspacePk], {
firstName: "Bob",
lastName: "Rabiot",
email: "rabiot.b@tdrive.app",
});
await testDbService.createUser([workspacePk, workspacePk2], {
firstName: "Bob",
lastName: "Smith-Rabiot",
email: "rbs@tdrive.app",
});
await testDbService.createUser([workspacePk], {
firstName: "Alexïs",
lastName: "Goélâns",
email: "alexis.goelans@tdrive.app",
});
//Wait for indexation to happen
await new Promise(r => setTimeout(r, 5000));
let resources = await search("ha");
expect(resources.length).toBe(2);
resources = await search("bob rabiot");
expect(resources.map(e => e.email).includes("rabiot.b@tdrive.app")).toBe(true);
expect(resources.map(e => e.email).includes("rbs@tdrive.app")).toBe(true);
expect(resources.map(e => e.email).includes("bob@tdrive.app")).toBe(true);
resources = await search("alexis");
expect(resources[0].email).toBe("alexis.goelans@tdrive.app");
resources = await search("ALEXIS");
expect(resources[0].email).toBe("alexis.goelans@tdrive.app");
resources = await search("AleXis");
expect(resources[0].email).toBe("alexis.goelans@tdrive.app");
resources = await search("alex");
expect(resources[0].email).toBe("alexis.goelans@tdrive.app");
resources = await search("àlèXïs");
expect(resources[0].email).toBe("alexis.goelans@tdrive.app");
resources = await search("rbs");
expect(resources[0].email).toBe("rbs@tdrive.app");
resources = await search("rbs@tdrive.app");
expect(resources[0].email).toBe("rbs@tdrive.app");
resources = await search("bob", workspacePk2.company_id);
expect(resources.length).toBe(1);
resources = await search("rbs@tdrive.app", workspacePk.company_id);
expect(resources[0].email).toBe("rbs@tdrive.app");
resources = await search("rbs@tdrive.app", uuidv1());
expect(resources.length).toBe(0);
done();
});
});
async function search(search: string, companyId?: string): Promise<any[]> {
const jwtToken = await platform.auth.getJWTToken();
const response = await platform.app.inject({
method: "GET",
url: `${url}/users`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
query: {
search: search,
...(companyId ? { search_company_id: companyId } : {}),
},
});
expect(response.statusCode).toBe(200);
const json = response.json();
expect(json).toMatchObject({ resources: expect.any(Array) });
const resources = json.resources;
return resources;
}
});
@@ -0,0 +1,553 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import { v1 as uuidv1 } from "uuid";
import { CompanyLimitsEnum } from "../../../src/services/user/web/types";
describe("The /users API", () => {
const url = "/internal/services/users/v1";
let platform: TestPlatform;
let testDbService: TestDbService;
const nonExistentId = uuidv1();
beforeEach(async ends => {
platform = await init();
ends();
});
afterEach(async ends => {
await platform.tearDown();
platform = null;
ends();
});
beforeAll(async ends => {
const platform = await init({
services: [
"database",
"search",
"message-queue",
"websocket",
"applications",
"webserver",
"user",
"auth",
"storage",
"counter",
"console",
"workspaces",
"statistics",
"platform-services",
],
});
testDbService = await TestDbService.getInstance(platform);
await testDbService.createCompany();
const workspacePk = { id: uuidv1(), company_id: testDbService.company.id };
await testDbService.createWorkspace(workspacePk);
await testDbService.createUser([workspacePk], {
workspaceRole: "moderator",
companyRole: "admin",
email: "admin@admin.admin",
username: "adminuser",
firstName: "admin",
});
await testDbService.createUser([workspacePk]);
ends();
});
afterAll(async ends => {
ends();
});
describe("The GET /users/:id route", () => {
it("should 401 when not authenticated", async done => {
const response = await platform.app.inject({
method: "GET",
url: `${url}/users/1`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 404 when user does not exists", async done => {
const jwtToken = await platform.auth.getJWTToken({ sub: testDbService.users[0].id });
const response = await platform.app.inject({
method: "GET",
url: `${url}/users/${nonExistentId}`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toBe(404);
expect(response.json()).toEqual({
error: "Not Found",
message: `User ${nonExistentId} not found`,
statusCode: 404,
});
done();
});
it("should 200 and big response for myself", async done => {
const myId = testDbService.users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/users/${myId}`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toBe(200);
const resource = response.json()["resource"];
expect(resource).toMatchObject({
id: myId,
provider: expect.any(String),
provider_id: expect.any(String),
email: expect.any(String),
is_verified: expect.any(Boolean),
picture: expect.any(String),
first_name: expect.any(String),
last_name: expect.any(String),
created_at: expect.any(Number),
deleted: expect.any(Boolean),
status: expect.any(String),
last_activity: expect.any(Number),
//Below is only if this is myself
preference: expect.objectContaining({
locale: expect.any(String),
timezone: expect.any(Number),
}),
});
expect(resource["companies"]).toEqual(
expect.arrayContaining([
expect.objectContaining({
role: expect.stringMatching(/owner|admin|member|guest/),
status: expect.stringMatching(/active|deactivated|invited/),
company: {
id: expect.any(String),
name: expect.any(String),
logo: expect.any(String),
},
}),
]),
);
done();
});
it("should 200 and short response for another user", async done => {
const myId = testDbService.users[0].id;
const anotherUserId = testDbService.users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/users/${anotherUserId}`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toBe(200);
const resource = response.json()["resource"];
expect(resource).toMatchObject({
id: anotherUserId,
provider: expect.any(String),
provider_id: expect.any(String),
email: expect.any(String),
is_verified: expect.any(Boolean),
picture: expect.any(String),
first_name: expect.any(String),
last_name: expect.any(String),
created_at: expect.any(Number),
deleted: expect.any(Boolean),
status: expect.any(String),
last_activity: expect.any(Number),
});
expect(resource).not.toMatchObject({
locale: expect.anything(),
timezone: expect.anything(),
companies: expect.anything(),
});
done();
});
});
describe("The GET /users route", () => {
it("should 401 when user is not authenticated", async done => {
const response = await platform.app.inject({
method: "GET",
url: `${url}/users`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 200 with array of users", async done => {
const myId = testDbService.users[0].id;
const anotherUserId = testDbService.users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/users`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
query: {
user_ids: `${myId},${anotherUserId}`,
company_ids: "fd96c8a8-ae77-11eb-a1a1-0242ac120005",
},
});
expect(response.statusCode).toBe(200);
const json = response.json();
expect(json).toMatchObject({ resources: expect.any(Array) });
const resources = json.resources;
done();
});
});
describe("The GET /users/:user_id/companies route", () => {
it("should 401 when not authenticated", async done => {
const response = await platform.app.inject({
method: "GET",
url: `${url}/users/1/companies`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 404 when user does not exists", async done => {
const jwtToken = await platform.auth.getJWTToken({ sub: testDbService.users[0].id });
const response = await platform.app.inject({
method: "GET",
url: `${url}/users/${nonExistentId}/companies`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toBe(404);
expect(response.json()).toEqual({
error: "Not Found",
message: `User ${nonExistentId} not found`,
statusCode: 404,
});
done();
});
it("should 200 and on correct request", async done => {
const myId = testDbService.users[0].id;
const anotherUserId = testDbService.users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/users/${anotherUserId}/companies`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toBe(200);
const resources = response.json()["resources"];
expect(resources.length).toBeGreaterThan(0);
for (const resource of resources) {
expect(resource).toMatchObject({
id: expect.any(String),
name: expect.any(String),
logo: expect.any(String),
role: expect.stringMatching(/owner|admin|member|guest/),
status: expect.stringMatching(/active|deactivated|invited/),
});
if (resource.plan) {
expect(resource.plan).toMatchObject({
name: expect.any(String),
limits: expect.objectContaining({
[CompanyLimitsEnum.CHAT_MESSAGE_HISTORY_LIMIT]: expect.any(Number || undefined),
[CompanyLimitsEnum.COMPANY_MEMBERS_LIMIT]: expect.any(Number || undefined),
}),
});
}
if (resources.stats) {
expect(resource.plan).toMatchObject({
created_at: expect.any(Number),
total_members: expect.any(Number),
total_guests: expect.any(Number),
});
}
}
done();
});
});
describe("The GET /companies/:company_id route", () => {
it("should 404 when company does not exists", async done => {
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/11111111-1111-1111-1111-111111111111`,
});
expect(response.statusCode).toBe(404);
done();
});
it("should 200 when company exists", async done => {
const companyId = testDbService.company.id;
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}`,
});
expect(response.statusCode).toBe(200);
const json = response.json();
expect(json.resource).toMatchObject({
id: expect.any(String),
name: expect.any(String),
logo: expect.any(String),
});
if (json.resource.plan) {
expect(json.resource.plan).toMatchObject({
name: expect.any(String),
limits: expect.objectContaining({
[CompanyLimitsEnum.CHAT_MESSAGE_HISTORY_LIMIT]: expect.any(Number || undefined),
[CompanyLimitsEnum.COMPANY_MEMBERS_LIMIT]: expect.any(Number || undefined),
}),
});
}
expect(json.resource.stats).toMatchObject({
created_at: expect.any(Number),
total_members: expect.any(Number),
total_guests: expect.any(Number),
total_messages: expect.any(Number),
});
done();
});
});
describe("User's device management", () => {
const deviceToken = "testDeviceToken";
describe("Register device (POST)", () => {
it("should 400 when type is not FCM", async done => {
const myId = testDbService.users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/devices`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: {
type: "another",
value: "value",
version: "version",
},
},
});
const resp = response.json();
expect(response.statusCode).toBe(400);
expect(resp).toMatchObject({
statusCode: 400,
error: "Bad Request",
message: "Type should be FCM only",
});
done();
});
it("should 200 when ok", async done => {
const firstId = testDbService.users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: firstId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/devices`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: {
type: "FCM",
value: deviceToken,
version: "1",
},
},
});
const resp = response.json();
expect(response.statusCode).toBe(200);
expect(resp.resource).toMatchObject({
type: "FCM",
value: deviceToken,
version: "1",
});
const user = await testDbService.getUserFromDb({ id: firstId });
expect(user.devices).toMatchObject([deviceToken]);
const device = await testDbService.getDeviceFromDb(deviceToken);
expect(device).toMatchObject({
id: deviceToken,
user_id: firstId,
type: "FCM",
version: "1",
});
done();
});
it("should 200 when register token to another person", async done => {
const firstId = testDbService.users[0].id;
const secondId = testDbService.users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: secondId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/devices`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
payload: {
resource: {
type: "FCM",
value: deviceToken,
version: "1",
},
},
});
const resp = response.json();
expect(response.statusCode).toBe(200);
expect(resp.resource).toMatchObject({
type: "FCM",
value: deviceToken,
version: "1",
});
// second user should have now this token
let user = await testDbService.getUserFromDb({ id: secondId });
expect(user.devices).toMatchObject([deviceToken]);
const device = await testDbService.getDeviceFromDb(deviceToken);
expect(device).toMatchObject({
id: deviceToken,
user_id: secondId,
type: "FCM",
version: "1",
});
// and first — not
user = await testDbService.getUserFromDb({ id: firstId });
expect(user.devices).toMatchObject([]);
done();
});
});
describe("List registered devices (GET)", () => {
it("should 200 when request devices", async done => {
const myId = testDbService.users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/devices`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
const resp = response.json();
expect(response.statusCode).toBe(200);
expect(resp).toMatchObject({
resources: [
{
type: "FCM",
value: "testDeviceToken",
version: "1",
},
],
});
done();
});
});
describe("De-register device (DELETE)", () => {
it("should 200 when device not found for the user", async done => {
const myId = testDbService.users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/devices/somethingRandom`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toBe(204);
const user = await testDbService.getUserFromDb({ id: myId });
expect(user.devices).toMatchObject([deviceToken]);
const device = await testDbService.getDeviceFromDb(deviceToken);
expect(device).toMatchObject({
id: deviceToken,
user_id: myId,
type: "FCM",
version: "1",
});
done();
});
it("should 200 when device found and device should be removed", async done => {
const myId = testDbService.users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: myId });
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/devices/${deviceToken}`,
headers: {
authorization: `Bearer ${jwtToken}`,
},
});
expect(response.statusCode).toBe(204);
const user = await testDbService.getUserFromDb({ id: myId });
expect(user.devices).toMatchObject([]);
const device = await testDbService.getDeviceFromDb(deviceToken);
expect(device).toBeFalsy();
done();
});
});
});
});
+73
View File
@@ -0,0 +1,73 @@
import { TestPlatform } from "./setup";
import { InjectPayload, Response } from "light-my-request";
import { logger as log } from "../../src/core/platform/framework";
declare global {
interface ApiResponse extends Response {
resources: any[];
resource: any;
}
}
export class Api {
constructor(protected platform: TestPlatform) {}
private async convertResponse(response: Promise<Response>): Promise<ApiResponse> {
const apiResponse = (await response) as ApiResponse;
if (apiResponse.statusCode !== 204) {
const json = apiResponse.json();
apiResponse.resources = json.resources;
apiResponse.resource = json.resource;
}
return apiResponse;
}
private getJwtToken(userId: string) {
return this.platform.auth.getJWTToken({ sub: userId });
}
async request(
method: "GET" | "POST",
url: string,
payload: InjectPayload,
userId: string,
headers: any,
): Promise<ApiResponse> {
if (!userId) userId = this.platform.currentUser.id;
let totalHeaders = { authorization: `Bearer ${await this.getJwtToken(userId)}` };
if (headers) {
totalHeaders = { ...totalHeaders, ...headers };
}
return this.convertResponse(
this.platform.app
.inject({
method,
url,
headers: totalHeaders,
payload,
})
.then(a => {
if (a.statusCode !== 204) {
log.debug(a.json(), `${method} ${url}`);
}
return a;
}),
);
}
public async get(url: string, userId?: string, headers?: any): Promise<ApiResponse> {
return this.request("GET", url, undefined, userId, headers);
}
public async post(
url: string,
payload: InjectPayload,
userId?: string,
headers?: any,
): Promise<ApiResponse> {
return this.request("POST", url, payload, userId, headers);
}
}
@@ -0,0 +1,260 @@
import { TestPlatform } from "./setup";
import User from "./../../src/services/user/entities/user";
import Company, {
getInstance as getCompanyInstance,
} from "./../../src/services/user/entities/company";
import Workspace, {
getInstance as getWorkspaceInstance,
WorkspacePrimaryKey,
} from "./../../src/services/workspaces/entities/workspace";
import { v1 as uuidv1 } from "uuid";
import CompanyUser from "../../src/services/user/entities/company_user";
import { DatabaseServiceAPI } from "../../src/core/platform/services/database/api";
import Repository from "../../src/core/platform/services/database/services/orm/repository/repository";
import Device from "../../src/services/user/entities/device";
import gr from "../../src/services/global-resolver";
export type uuid = string;
export class TestDbService {
private deviceRepository: Repository<Device>;
public static async getInstance(
testPlatform: TestPlatform,
createDefault = false,
): Promise<TestDbService> {
const instance = new this(testPlatform);
await instance.init();
if (createDefault) {
await instance.createDefault(testPlatform);
}
return instance;
}
public company: Company;
public users: User[];
private workspacesMap: Map<string, { workspace: Workspace; users: User[] }>;
private userService;
rand = () => Math.floor(Math.random() * 100000);
private database: DatabaseServiceAPI;
private companyUserRepository: Repository<CompanyUser>;
private userRepository: Repository<User>;
constructor(protected testPlatform: TestPlatform) {
this.database = this.testPlatform.platform.getProvider<DatabaseServiceAPI>("database");
this.users = [];
this.workspacesMap = new Map<string, { workspace: Workspace; users: User[] }>();
this.workspacesMap.set("direct", {
workspace: { id: "direct" } as Workspace,
users: [],
});
}
private async init() {
this.userRepository = await this.database.getRepository<User>("user", User);
this.companyUserRepository = await this.database.getRepository<CompanyUser>(
"group_user",
CompanyUser,
);
this.deviceRepository = await this.database.getRepository<Device>("device", Device);
}
public get workspaces() {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return [...this.workspacesMap.values()].filter(w => w.workspace.id !== "direct");
}
async createCompany(id?: uuid, name?: string): Promise<Company> {
if (!name) {
name = `TdriveAutotests-test-company-${this.rand()}`;
}
this.company = await gr.services.companies.createCompany(
getCompanyInstance({
id: id || uuidv1(),
name: name,
displayName: name,
identity_provider_id: id,
}),
);
return this.company;
}
async createWorkspace(
workspacePk: WorkspacePrimaryKey,
name = `TdriveAutotests-test-workspace-${this.rand()}`,
): Promise<Workspace> {
if (!workspacePk.company_id) throw new Error("company_id is not defined for workspace");
const workspace = await gr.services.workspaces.create(
getWorkspaceInstance({
id: workspacePk.id,
name: name,
logo: "workspace_logo",
company_id: workspacePk.company_id,
}),
{ user: { id: "", server_request: true } },
);
const createdWorkspace = await gr.services.workspaces.get({
id: workspacePk.id,
company_id: workspacePk.company_id,
});
if (!createdWorkspace) {
throw new Error("workspace wasn't created");
}
const createdWorkspaceEntity = workspace.entity;
this.workspacesMap.set(createdWorkspaceEntity.id, {
workspace: createdWorkspaceEntity,
users: [],
});
return createdWorkspaceEntity;
}
async createUser(
workspacesPk?: Array<WorkspacePrimaryKey>,
options: {
companyRole?: "member" | "admin" | "guest";
workspaceRole?: "member" | "moderator";
firstName?: string;
lastName?: string;
email?: string;
username?: string;
password?: string;
cache?: User["cache"];
} = {},
id: string = uuidv1(),
): Promise<User> {
const user = new User();
const random = this.rand();
user.id = id;
user.username_canonical = options.username || `test${random}`;
user.first_name = options.firstName || `test${random}_first_name`;
user.last_name = options.lastName || `test${random}_last_name`;
user.email_canonical = options.email || `test${random}@tdrive.app`;
user.identity_provider_id = user.id;
user.cache = options.cache || user.cache || { companies: [] };
//Fixme this is cheating, we should correctly set the cache in internal mode in the code
user.cache.companies = [
...(user.cache.companies || []),
...workspacesPk.map(w => w.company_id),
];
if (options.email) {
user.email_canonical = options.email;
}
const createdUser = (await gr.services.users.create(user)).entity;
if (options.password) {
await gr.services.users.setPassword({ id: createdUser.id }, options.password);
}
this.users.push(createdUser);
await gr.services.companies.setUserRole(
this.company ? this.company.id : workspacesPk[0].company_id,
createdUser.id,
options.companyRole ? options.companyRole : "member",
);
if (workspacesPk && workspacesPk.length) {
for (const workspacePk of workspacesPk) {
await gr.services.workspaces.addUser(
workspacePk,
{ id: createdUser.id },
options.workspaceRole ? options.workspaceRole : "member",
);
const wsContainer = this.workspacesMap.get(workspacePk.id);
wsContainer.users.push(createdUser);
}
}
return createdUser;
}
async getUserFromDb(user: Partial<Pick<User, "id" | "identity_provider_id">>): Promise<User> {
if (user.id) {
return gr.services.users.get({ id: user.id });
} else if (user.identity_provider_id) {
return gr.services.users.getByConsoleId(user.identity_provider_id);
} else {
throw new Error("getUserFromDb: Id not provided");
}
}
async getDeviceFromDb(id: string): Promise<Device> {
return this.deviceRepository.findOne({ id });
}
getCompanyFromDb(companyId: uuid) {
return gr.services.companies.getCompany({ id: companyId });
}
getCompanyFromDbByCode(code: uuid) {
return gr.services.companies.getCompany({ identity_provider_id: code });
}
async getCompanyUsers(companyId: uuid): Promise<User[]> {
const allUsers = await this.userRepository.find({}).then(a => a.getEntities());
const companyUsers: User[] = [];
for (const user of allUsers) {
const userInCompany = await this.companyUserRepository.findOne({
user_id: user.id,
group_id: companyId,
});
if (userInCompany) {
companyUsers.push(user);
}
}
return companyUsers;
}
getCompanyUser(companyId: uuid, userId: uuid): Promise<CompanyUser> {
return gr.services.companies.getCompanyUser({ id: companyId }, { id: userId });
}
getWorkspaceUsersCountFromDb(workspaceId: string) {
return gr.services.workspaces.getUsersCount(workspaceId);
}
async getCompanyUsersCountFromDb(companyId: string) {
return gr.services.companies.getUsersCount(companyId);
}
async createDefault(
platform: TestPlatform = this.testPlatform,
isAdmin: boolean = true,
): Promise<TestDbService> {
await this.createCompany(platform.workspace.company_id);
const ws0pk = {
id: platform.workspace.workspace_id,
company_id: platform.workspace.company_id,
};
await this.createWorkspace(ws0pk);
await this.createUser(
[ws0pk],
{
firstName: "defaultUser",
companyRole: isAdmin ? "admin" : "member",
workspaceRole: isAdmin ? "moderator" : "member",
},
platform.currentUser.id,
);
return this;
}
getRepository = (type, entity) => {
return this.database.getRepository<typeof entity>(type, entity);
};
defaultWorkspace() {
return this.workspaces[0].workspace;
}
}
@@ -0,0 +1,469 @@
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { TestDbService, uuid } from "../utils.prepare.db";
import { v1 as uuidv1 } from "uuid";
describe("The /workspace users API", () => {
const url = "/internal/services/workspaces/v1";
let platform: TestPlatform;
let testDbService: TestDbService;
const nonExistentId = uuidv1();
let companyId = "";
const checkUserObject = (resource: any) => {
expect(resource).toMatchObject({
id: expect.any(String),
company_id: expect.any(String),
workspace_id: expect.any(String),
user_id: expect.any(String),
created_at: expect.any(Number),
role: expect.stringMatching(/moderator|member/),
user: {
id: expect.any(String),
provider: expect.any(String),
provider_id: expect.any(String),
email: expect.any(String),
is_verified: expect.any(Boolean),
picture: expect.any(String),
first_name: expect.any(String),
last_name: expect.any(String),
created_at: expect.any(Number),
deleted: expect.any(Boolean),
status: expect.any(String),
last_activity: expect.any(Number),
},
});
};
beforeAll(async ends => {
platform = await init({
services: [
"database",
"message-queue",
"search",
"webserver",
"user",
"workspaces",
"applications",
"auth",
"console",
"counter",
"storage",
"statistics",
"platform-services",
],
});
companyId = platform.workspace.company_id;
await platform.database.getConnector().init();
testDbService = new TestDbService(platform);
await testDbService.createCompany(companyId);
const ws0pk = { id: uuidv1(), company_id: companyId };
const ws1pk = { id: uuidv1(), company_id: companyId };
const ws2pk = { id: uuidv1(), company_id: companyId };
const ws3pk = { id: uuidv1(), company_id: companyId };
await testDbService.createWorkspace(ws0pk);
await testDbService.createWorkspace(ws1pk);
await testDbService.createWorkspace(ws2pk);
await testDbService.createWorkspace(ws3pk);
await testDbService.createUser([ws0pk, ws1pk]);
await testDbService.createUser([ws2pk], { companyRole: "admin" });
await testDbService.createUser([ws2pk], { workspaceRole: "moderator" });
await testDbService.createUser([ws2pk], { workspaceRole: "member" });
await testDbService.createUser([ws2pk], { workspaceRole: "member" });
await testDbService.createUser([], { companyRole: "member" });
await testDbService.createUser([ws3pk], { companyRole: "guest", workspaceRole: "member" });
ends();
});
afterAll(async ends => {
await platform.tearDown();
ends();
});
describe("The GET /workspaces/users route", () => {
it("should 401 when not authenticated", async done => {
const companyId = testDbService.company.id;
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 404 when workspace not found", async done => {
const userId = testDbService.users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(404);
done();
});
it("should 200 when ok", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(200);
const resources = response.json()["resources"];
expect(resources.length).toBeGreaterThan(0);
for (const resource of resources) {
checkUserObject(resource);
}
done();
});
});
describe("The GET /workspaces/users/:user_id route", () => {
it("should 401 when not authenticated", async done => {
const companyId = testDbService.company.id;
const userId = testDbService.users[0].id;
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/${userId}`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 404 when workspace not found", async done => {
const userId = testDbService.users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/${userId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(404);
done();
});
it("should 200 when ok", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[0].workspace.id;
const userId = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${userId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(200);
const resource = response.json()["resource"];
checkUserObject(resource);
done();
});
});
describe("The POST /workspaces/users route (add)", () => {
it("should 401 when not authenticated", async done => {
const companyId = testDbService.company.id;
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 403 user is not workspace moderator", async done => {
const userId = testDbService.users[0].id;
const anotherUserId = testDbService.users[1].id;
const workspaceId = testDbService.workspaces[0].workspace.id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
user_id: anotherUserId,
role: "moderator",
},
},
});
expect(response.statusCode).toBe(403);
done();
});
it("should 400 when requested user not in company", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
user_id: nonExistentId,
role: "moderator",
},
},
});
expect(response.statusCode).toBe(400);
done();
});
it("should 201 when requested already in workspace (ignore)", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
user_id: userId,
role: "moderator",
},
},
});
expect(response.statusCode).toBe(201);
done();
});
it("should 200 when ok", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[1].id;
const anotherUserId = testDbService.workspaces[0].users[0].id;
let workspaceUsersCount = await testDbService.getWorkspaceUsersCountFromDb(workspaceId);
let companyUsersCount = await testDbService.getCompanyUsersCountFromDb(companyId);
console.log(testDbService.workspaces[2].users);
console.log(workspaceUsersCount);
expect(workspaceUsersCount).toBe(4);
// expect(companyUsersCount).toBe(6);
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
user_id: anotherUserId,
role: "moderator",
},
},
});
expect(response.statusCode).toBe(201);
const resource = response.json()["resource"];
checkUserObject(resource);
workspaceUsersCount = await testDbService.getWorkspaceUsersCountFromDb(workspaceId);
companyUsersCount = await testDbService.getCompanyUsersCountFromDb(companyId);
expect(workspaceUsersCount).toBe(5);
// expect(companyUsersCount).toBe(6);
done();
});
});
describe("The POST /workspaces/users/:user_id route (update)", () => {
it("should 401 when not authenticated", async done => {
const companyId = testDbService.company.id;
const userId = testDbService.users[0].id;
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/${userId}`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 403 user is not workspace moderator", async done => {
const userId = testDbService.users[0].id;
const anotherUserId = testDbService.users[1].id;
const workspaceId = testDbService.workspaces[0].workspace.id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${userId}`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
user_id: anotherUserId,
role: "moderator",
},
},
});
expect(response.statusCode).toBe(403);
done();
});
it("should 404 when user not found in workspace", async done => {
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[1].id;
const anotherWorkspaceUserId = testDbService.workspaces[3].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${anotherWorkspaceUserId}`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
role: "moderator",
},
},
});
expect(response.statusCode).toBe(404);
done();
});
it("should 200 when ok", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[1].id;
const anotherUserId = testDbService.workspaces[2].users[2].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${anotherUserId}`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
role: "moderator",
},
},
});
expect(response.statusCode).toBe(201);
const resource = response.json()["resource"];
checkUserObject(resource);
expect(resource["role"]).toBe("moderator");
const usersCount = await testDbService.getWorkspaceUsersCountFromDb(workspaceId);
expect(usersCount).toBe(5);
done();
});
});
describe("The DELETE /workspaces/users/:user_id route", () => {
it("should 401 when not authenticated", async done => {
const companyId = testDbService.company.id;
const anotherUserId = testDbService.users[1].id;
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}/users/${anotherUserId}`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 403 user is not workspace moderator", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[3].id;
const anotherUserId = testDbService.workspaces[2].users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${anotherUserId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
console.log(response.body);
expect(response.statusCode).toBe(403);
done();
});
it("should 404 when user not found in workspace", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[1].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${nonExistentId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(404);
done();
});
it("should 200 when ok", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[1].id;
const anotherUserId = testDbService.workspaces[2].users[2].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
let response = await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users/${anotherUserId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(204);
response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}/users`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(200);
const resources = response.json()["resources"];
expect(resources.find((a: { user_id: uuid }) => a.user_id === anotherUserId)).toBeUndefined();
const usersCount = await testDbService.getWorkspaceUsersCountFromDb(workspaceId);
expect(usersCount).toBe(4);
done();
});
});
});
@@ -0,0 +1,513 @@
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { init, TestPlatform } from "../setup";
import { TestDbService } from "../utils.prepare.db";
import { v1 as uuidv1 } from "uuid";
describe("The /workspaces API", () => {
const url = "/internal/services/workspaces/v1";
let platform: TestPlatform;
let testDbService: TestDbService;
const nonExistentId = uuidv1();
let companyId = "";
beforeAll(async ends => {
platform = await init({
services: [
"database",
"message-queue",
"webserver",
"user",
"search",
"workspaces",
"auth",
"console",
"counter",
"storage",
"applications",
"statistics",
"platform-services",
],
});
companyId = platform.workspace.company_id;
await platform.database.getConnector().init();
testDbService = new TestDbService(platform);
await testDbService.createCompany(companyId);
const ws0pk = { id: uuidv1(), company_id: companyId };
const ws1pk = { id: uuidv1(), company_id: companyId };
const ws2pk = { id: uuidv1(), company_id: companyId };
await testDbService.createWorkspace(ws0pk);
await testDbService.createWorkspace(ws1pk);
await testDbService.createWorkspace(ws2pk);
await testDbService.createUser([ws0pk, ws1pk]);
await testDbService.createUser([ws2pk], { companyRole: "admin" });
await testDbService.createUser([ws2pk], { companyRole: undefined, workspaceRole: "moderator" });
await testDbService.createUser([], { companyRole: "guest" });
ends();
});
afterAll(async ends => {
await platform.tearDown();
ends();
});
describe("The GET /workspaces/ route", () => {
it("should 401 when not authenticated", async done => {
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${nonExistentId}/workspaces`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 404 when company not found", async done => {
const userId = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${nonExistentId}/workspaces`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(404);
done();
});
it("should 200 when company belongs to user", async done => {
const userId = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const companyId = testDbService.company.id;
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(200);
const resources = response.json()["resources"];
expect(resources.length).toBe(2);
for (const resource of resources) {
expect(resource).toMatchObject({
id: expect.any(String),
company_id: expect.any(String),
name: expect.any(String),
logo: expect.any(String),
default: expect.any(Boolean),
archived: expect.any(Boolean),
role: expect.stringMatching(/moderator|member/),
});
if (resource.stats) {
expect(resource.stats).toMatchObject({
created_at: expect.any(Number),
total_members: 1,
});
}
}
done();
});
});
describe("The GET /workspaces/:workspace_id route", () => {
it("should 401 when not authenticated", async done => {
const workspaceId = testDbService.workspaces[0].workspace.id;
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${nonExistentId}/workspaces/${workspaceId}`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 404 when workspace not found", async done => {
const userId = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${uuidv1()}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(404);
done();
});
it("should 403 when user not belong to workspace and not company_admin", async done => {
const workspaceId = testDbService.workspaces[2].workspace.id;
const userIdFromAnotherWorkspace = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromAnotherWorkspace });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(403);
expect(response.json()).toEqual({
error: "Forbidden",
message: `You are not belong to workspace ${workspaceId}`,
statusCode: 403,
});
done();
});
it("should 200 when user is company_admin", async done => {
const workspaceId = testDbService.workspaces[0].workspace.id;
const userIdFromAnotherWorkspace = testDbService.workspaces[2].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromAnotherWorkspace });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(200);
const resource = response.json()["resource"];
expect(resource).toMatchObject({
id: expect.any(String),
company_id: expect.any(String),
name: expect.any(String),
logo: expect.any(String),
default: expect.any(Boolean),
archived: expect.any(Boolean),
});
if (resource.stats) {
expect(resource.stats).toMatchObject({
created_at: expect.any(Number),
total_members: 1,
});
}
done();
});
it("should 200 when user is belong to workspace", async done => {
const workspaceId = testDbService.workspaces[0].workspace.id;
const userIdFromThisWorkspace = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userIdFromThisWorkspace });
const response = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(200);
const resource = response.json()["resource"];
expect(resource).toMatchObject({
id: expect.any(String),
company_id: expect.any(String),
name: expect.any(String),
logo: expect.any(String),
default: expect.any(Boolean),
archived: expect.any(Boolean),
role: expect.stringMatching(/moderator|member/),
});
if (resource.stats) {
expect(resource.stats).toMatchObject({
created_at: expect.any(Number),
total_members: 1,
});
}
done();
});
});
// create
describe("The POST /workspaces route (creating workspace)", () => {
it("should 401 when not authenticated", async done => {
const companyId = testDbService.company.id;
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 403 when user is not (company member or company admin) ", async done => {
const companyId = testDbService.company.id;
const userId = testDbService.users[3].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
name: "Some channel name",
logo: "",
default: false,
},
},
});
expect(response.statusCode).toBe(403);
done();
});
it("should 201 when workspace created well", async done => {
const companyId = testDbService.company.id;
const userId = testDbService.users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
name: "Random channel name",
logo: "logo",
default: false,
},
},
});
expect(response.statusCode).toBe(201);
const resource = response.json()["resource"];
expect(resource).toMatchObject({
id: expect.any(String),
company_id: expect.any(String),
name: expect.any(String),
logo: expect.any(String),
default: expect.any(Boolean),
archived: expect.any(Boolean),
role: expect.stringMatching(/moderator/),
});
done();
});
});
// update
describe("The POST /workspaces/:workspace_id route (updating workspace)", () => {
it("should 401 when not authenticated", async done => {
const companyId = testDbService.company.id;
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}`,
payload: { resource: {} },
});
expect(response.statusCode).toBe(401);
done();
});
it("should 403 when not workspace not found", async done => {
const companyId = testDbService.company.id;
const userId = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: { resource: {} },
});
expect(response.statusCode).toBe(403);
done();
});
it("should 403 when not belong to workspace", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[1].workspace.id;
const userId = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: { resource: {} },
});
expect(response.statusCode).toBe(403);
done();
});
it("should 403 when not workspace moderator", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[1].workspace.id;
const userId = testDbService.workspaces[0].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: { resource: {} },
});
expect(response.statusCode).toBe(403);
done();
});
it("should 200 when admin of company (full update)", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[0].id; // company owner
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
name: "Another workspace name",
logo: "logo",
default: false,
archived: false,
},
},
});
expect(response.statusCode).toBe(200);
const resource = response.json()["resource"];
expect(resource).toMatchObject({
id: workspaceId,
company_id: companyId,
name: "Another workspace name",
logo: expect.any(String),
default: false,
archived: false,
role: "moderator", //Company admin is a moderator
});
done();
});
it("should 200 when moderator of workspace (partial update)", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[1].id; // workspace admin
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "POST",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
payload: {
resource: {
name: "My awesome workspace",
default: true,
logo: "",
},
},
});
expect(response.statusCode).toBe(200);
const resource = response.json()["resource"];
expect(resource).toMatchObject({
id: workspaceId,
company_id: companyId,
name: "My awesome workspace",
logo: expect.any(String),
default: true,
archived: false,
role: "moderator",
});
done();
});
});
// delete
describe("The DELETE /workspaces route", () => {
it("should 401 when not authenticated", async done => {
const companyId = testDbService.company.id;
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${companyId}/workspaces/${nonExistentId}`,
});
expect(response.statusCode).toBe(401);
done();
});
it("should 403 when user is not (company member or company admin) ", async done => {
const companyId = testDbService.company.id;
const userId = testDbService.users[3].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const workspaceId = testDbService.workspaces[0].workspace.id;
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(403);
done();
});
it("should 204 when workspace deleted", async done => {
const companyId = testDbService.company.id;
const workspaceId = testDbService.workspaces[2].workspace.id;
const userId = testDbService.workspaces[2].users[0].id;
const jwtToken = await platform.auth.getJWTToken({ sub: userId });
const response = await platform.app.inject({
method: "DELETE",
url: `${url}/companies/${companyId}/workspaces/${workspaceId}`,
headers: { authorization: `Bearer ${jwtToken}` },
});
expect(response.statusCode).toBe(204);
const checkResponse = await platform.app.inject({
method: "GET",
url: `${url}/companies/${companyId}/workspaces`,
headers: { authorization: `Bearer ${jwtToken}` },
});
const checkResponseJson = checkResponse.json();
expect(checkResponseJson.resources.find((a: any) => a.id === workspaceId)).toBe(undefined);
done();
});
});
});
+3
View File
@@ -0,0 +1,3 @@
# Sample HTTP Requests
Files in this folder works with the [REST Client VSCode extension](https://github.com/Huachao/vscode-restclient).
+19
View File
@@ -0,0 +1,19 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
@user_id = 3328552c-5ccd-4172-b84a-d876d56aa71c
@baseURL = http://localhost:3000
@badgesURL = {{baseURL}}/internal/services/notifications/v1/badges
# @name login
GET {{baseURL}}/api/auth/login
@authToken = {{login.response.body.token}}
@currentUserId = {{login.response.body.user.id}}
### List badges with all websockets
GET {{badgesURL}}/?company_id={{company_id}}&websockets=true&limit=5
Content-Type: application/json
Authorization: Bearer {{authToken}}
@@ -0,0 +1,61 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
@user_id = 3328552c-5ccd-4172-b84a-d876d56aa71c
@baseURL = http://localhost:3000
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
# @name login
GET {{baseURL}}/api/auth/login
@authToken = {{login.response.body.token}}
@currentUserId = {{login.response.body.user.id}}
### Create a channel
# @name createChannel
POST {{channelsURL}}/channels
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"name": "My channel",
"icon": "tdrive logo",
"description": "This channel allow tdrive's team to chat easily",
"channel_group": "tdrive",
"visibility": "public",
"is_default": true,
"archived": false
}
}
### Get a single channel
@getId = {{createChannel.response.body.resource.id}}
GET {{channelsURL}}/channels/{{getId}}
Authorization: Bearer {{authToken}}
### Add current user as member to a channel (join channel)
POST {{channelsURL}}/channels/{{getId}}/members
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"user_id": "{{currentUserId}}"
}
}
### Mark the channel as read/unread
POST {{channelsURL}}/channels/{{getId}}/read
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"value": true
}
+133
View File
@@ -0,0 +1,133 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
@user_id = 3328552c-5ccd-4172-b84a-d876d56aa71c
@baseURL = http://localhost:3000
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
# @name login
GET {{baseURL}}/api/auth/login
@authToken = {{login.response.body.token}}
@currentUserId = {{login.response.body.user.id}}
### List workspace channels with all websockets
GET {{channelsURL}}/channels?websockets=true&limit=5
Content-Type: application/json
Authorization: Bearer {{authToken}}
### List user channels with all websockets
@authToken = {{login.response.body.token}}
GET {{channelsURL}}/channels?websockets=true&mine=true&limit=5
Content-Type: application/json
Authorization: Bearer {{authToken}}
### Create a channel
# @name createChannel
POST {{channelsURL}}/channels
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"name": "My channel",
"icon": "tdrive logo",
"description": "This channel allow tdrive's team to chat easily",
"channel_group": "tdrive",
"visibility": "public",
"is_default": true,
"archived": false
}
}
### Get a single channel
@getId = {{createChannel.response.body.resource.id}}
GET {{channelsURL}}/channels/{{getId}}
Authorization: Bearer {{authToken}}
### Update a channel
@updateId = {{createChannel.response.body.resource.id}}
POST {{channelsURL}}/channels/{{updateId}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"name": "My channel",
"description": "Hello world",
"is_default": false
}
}
### Delete a channel
@deleteId = {{createChannel.response.body.resource.id}}
DELETE {{channelsURL}}/channels/{{deleteId}}
Authorization: Bearer {{authToken}}
### Get all channel members
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authToken}}
### Add current user as member to a channel (join channel)
POST {{channelsURL}}/channels/{{getId}}/members
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"user_id": "{{currentUserId}}"
}
}
### Get a channel member
GET {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
### Update current channel member
POST {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"favorite": true,
"notification_level": "none",
"hello": 1
}
}
### Current user quits the channel
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
### Errors Tests
### Call without the JWT token should HTTP 401
GET {{channelsURL}}/channels
Content-Type: application/json
### Get a channel which may not exists
GET {{channelsURL}}/channels/0b0e1492-f596-46b9-a4fb-c12d71b2696e
Authorization: Bearer {{authToken}}
@@ -0,0 +1,163 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
@baseURL = http://localhost:3000
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
### Login as user 1
# @name login
GET {{baseURL}}/api/auth/login
@authToken1 = {{login.response.body.token}}
@userId1 = {{login.response.body.user.id}}
### Login as user 2
# @name login2
GET {{baseURL}}/api/auth/login
@authToken2 = {{login2.response.body.token}}
@userId2 = {{login2.response.body.user.id}}
### Login as user 3
# @name login3
GET {{baseURL}}/api/auth/login
@authToken3 = {{login3.response.body.token}}
@userId3 = {{login3.response.body.user.id}}
### Create a direct channel
# @name createDirectChannel
POST {{directChannelsURL}}/channels
Content-Type: application/json
Authorization: Bearer {{authToken1}}
{
"options": {
"members": ["{{userId2}}"]
},
"resource": {
"icon": "hello",
"description": "A direct channel",
"channel_group": "tdrive",
"is_default": false,
"archived": false
}
}
### Direct channel details as user 1 should work
@directId = {{createDirectChannel.response.body.resource.id}}
GET {{directChannelsURL}}/channels/{{directId}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
### Direct channel details as user 2 (member) should work
GET {{directChannelsURL}}/channels/{{directId}}
Content-Type: application/json
Authorization: Bearer {{authToken2}}
### Direct channel details as user 3 (not member) should not work
GET {{directChannelsURL}}/channels/{{directId}}
Content-Type: application/json
Authorization: Bearer {{authToken3}}
### Direct channel members
GET {{directChannelsURL}}/channels/{{directId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authToken1}}
### List direct channels for user in company
@authToken = {{login.response.body.token}}
GET {{directChannelsURL}}/channels?websockets=true&limit=5
Content-Type: application/json
Authorization: Bearer {{authToken1}}
### Update the direct channel description
POST {{directChannelsURL}}/channels/{{directId}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
{
"resource": {
"description": "A new direct channel description"
}
}
### Update the direct channel name will do nothing since the name is useless
POST {{directChannelsURL}}/channels/{{directId}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
{
"resource": {
"name": "A new direct channel name"
}
}
### Update the direct channel member settings for current user
POST {{directChannelsURL}}/channels/{{directId}}/members/{{userId1}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
{
"resource": {
"favorite": true,
"notification_level": "all"
}
}
### Update another user member settings should fail
POST {{directChannelsURL}}/channels/{{directId}}/members/{{userId2}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
{
"resource": {
"favorite": true,
"notification_level": "none"
}
}
### Get member settings as user1
GET {{directChannelsURL}}/channels/{{directId}}/members/{{userId1}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
### Get member settings as user2
GET {{directChannelsURL}}/channels/{{directId}}/members/{{userId2}}
Content-Type: application/json
Authorization: Bearer {{authToken2}}
### Get other member settings should fail
GET {{directChannelsURL}}/channels/{{directId}}/members/{{userId2}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
### Leave a direct channel of another user should fail
DELETE {{directChannelsURL}}/channels/{{directId}}/members/{{userId2}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
### Leave a direct channel should not fail
DELETE {{directChannelsURL}}/channels/{{directId}}/members/{{userId1}}
Content-Type: application/json
Authorization: Bearer {{authToken1}}
@@ -0,0 +1,108 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
@baseURL = http://localhost:3000
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
### Login as user 1
# @name login
GET {{baseURL}}/api/auth/login
@authTokenUser1 = {{login.response.body.token}}
@currentUserId1 = {{login.response.body.user.id}}
### Login as user 2
# @name login2
GET {{baseURL}}/api/auth/login
@authTokenUser2 = {{login2.response.body.token}}
@currentUserId2 = {{login2.response.body.user.id}}
### User 1 creates a private channel
# @name createChannel
POST {{channelsURL}}/channels
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
{
"resource": {
"name": "My private channel",
"icon": "tdrive logo",
"description": "This channel allow tdrive's team to chat easily",
"channel_group": "tdrive",
"visibility": "private",
"is_default": true,
"archived": false
}
}
### Get the private channel
@getId = {{createChannel.response.body.resource.id}}
GET {{channelsURL}}/channels/{{getId}}
Authorization: Bearer {{authTokenUser1}}
### Get all channel members
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
### The user 2 tries to join the private channel, this should reject
POST {{channelsURL}}/channels/{{getId}}/members
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
{
"resource": {
"user_id": "{{currentUserId2}}"
}
}
### The user 1 adds the user 2 as channel member, this should be OK
POST {{channelsURL}}/channels/{{getId}}/members
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
{
"resource": {
"user_id": "{{currentUserId2}}"
}
}
### User 2 lists his channels
GET {{channelsURL}}/channels?websockets=true&mine=true&limit=5
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
### Get all channel members as user 1
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
### Get all channel members as user 2
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
### User 1 leaves the channel he created
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId1}}
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
### User 2 leaves the channel: Error since he is the last member, he can not leave
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId2}}
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
@@ -0,0 +1,70 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
@user_id = 3328552c-5ccd-4172-b84a-d876d56aa71c
@baseURL = http://localhost:3000
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
# @name login
GET {{baseURL}}/api/auth/login
@authToken = {{login.response.body.token}}
@currentUserId = {{login.response.body.user.id}}
### List workspace channels with all websockets
GET {{channelsURL}}/channels?websockets=true&limit=5
Content-Type: application/json
Authorization: Bearer {{authToken}}
### List user channels with all websockets
@authToken = {{login.response.body.token}}
GET {{channelsURL}}/channels?websockets=true&mine=true&limit=5
Content-Type: application/json
Authorization: Bearer {{authToken}}
### Create a private channel
# @name createChannel
POST {{channelsURL}}/channels
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"name": "My private channel",
"icon": "tdrive logo",
"description": "A private channel",
"channel_group": "tdrive",
"visibility": "private",
"is_default": true,
"archived": false
}
}
### Get the private channel
@getId = {{createChannel.response.body.resource.id}}
GET {{channelsURL}}/channels/{{getId}}
Authorization: Bearer {{authToken}}
### Get members of the private channel
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authToken}}
### Get current user as member
GET {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
### Current user quits the private channel will fail because he is the only one in it
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
@@ -0,0 +1,108 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
@baseURL = http://localhost:3000
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
@directChannelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/direct
### Login as user 1
# @name login
GET {{baseURL}}/api/auth/login
@authTokenUser1 = {{login.response.body.token}}
@currentUserId1 = {{login.response.body.user.id}}
### Login as user 2
# @name login2
GET {{baseURL}}/api/auth/login
@authTokenUser2 = {{login2.response.body.token}}
@currentUserId2 = {{login2.response.body.user.id}}
### User 1 creates a public channel
# @name createChannel
POST {{channelsURL}}/channels
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
{
"resource": {
"name": "A public channel",
"icon": "tdrive logo",
"description": "This channel allow tdrive's team to chat easily",
"channel_group": "tdrive",
"visibility": "public",
"is_default": true,
"archived": false
}
}
### Get the public channel
@getId = {{createChannel.response.body.resource.id}}
GET {{channelsURL}}/channels/{{getId}}
Authorization: Bearer {{authTokenUser1}}
### Get all channel members
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
### The user 2 joins the public channel, this should be OK
POST {{channelsURL}}/channels/{{getId}}/members
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
{
"resource": {
"user_id": "{{currentUserId2}}"
}
}
### Get all channel members, there are now 2 members
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
### User 1 lists his channels
GET {{channelsURL}}/channels?mine=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
### User 2 lists his channels
GET {{channelsURL}}/channels?mine=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
### User 2 leaves the channel
DELETE {{channelsURL}}/channels/{{getId}}/members/{{currentUserId2}}
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
### Get all channel members, there are now 1 member, the initial one
GET {{channelsURL}}/channels/{{getId}}/members?websockets=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser1}}
### List channels as user 2, current channel appears since it is public
GET {{channelsURL}}/channels
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
### User 2 list his public channels, current channel does not appear since he left it
GET {{channelsURL}}/channels?mine=true
Content-Type: application/json
Authorization: Bearer {{authTokenUser2}}
+85
View File
@@ -0,0 +1,85 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71a
@baseURL = http://localhost:3000
@tabsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}/channels
@channelsURL = {{baseURL}}/internal/services/channels/v1/companies/{{company_id}}/workspaces/{{workspace_id}}
# @name login
GET {{baseURL}}/api/auth/login
@authToken = {{login.response.body.token}}
@currentUserId = {{login.response.body.user.id}}
### List channel's tab with all websockets
GET {{tabsURL}}/{{channelId}}/tabs?websockets=true&limit=5
Content-Type: application/json
Authorization: Bearer {{authToken}}
### Create a channel
# @name createChannel
POST {{channelsURL}}/channels
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"name": "My channel",
"icon": "tdrive logo",
"description": "This channel allow tdrive's team to chat easily",
"channel_group": "tdrive",
"visibility": "public",
"is_default": true,
"archived": false
}
}
### Create a tab
# @name createTab
@channelId = {{createChannel.response.body.resource.id}}
POST {{tabsURL}}/{{channelId}}/tabs
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
// WARNING : special caracter in tab's name does not work
"name": "My tabs name",
"configuration": "JSON"
}
}
### Get a single tab
@getId = {{createTab.response.body.resource.id}}
GET {{tabsURL}}/{{channelId}}/tabs/{{getId}}
Authorization: Bearer {{authToken}}
### Update a tab
@updateId = {{createTab.response.body.resource.id}}
POST {{tabsURL}}/{{channelId}}/tabs/{{updateId}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"name": "My tab updated",
"configuration": "JSON"
}
}
### Delete a tab
@deleteId = {{createTab.response.body.resource.id}}
DELETE {{tabsURL}}/{{channelId}}/tabs/{{deleteId}}
Authorization: Bearer {{authToken}}
+18
View File
@@ -0,0 +1,18 @@
@company_id = bcfe2f79-8e81-42a3-b551-3a32d49b2b4c
@workspace_id = 3328552c-5ccd-4172-b84a-d876d56aa71b
@user_id = 508c8c1a-706f-11eb-b6be-0242ac120002
@baseURL = http://localhost:3000
@usersURL = {{baseURL}}/internal/services/users/v1
# @name login
GET {{baseURL}}/api/auth/login
@authToken = {{login.response.body.token}}
@currentUserId = {{login.response.body.user.id}}
### Get a single user
GET {{usersURL}}/users/{{user_id}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
@@ -0,0 +1,58 @@
@baseURL = http://localhost:8000
@workspacesURL = {{baseURL}}/internal/services/workspaces/v1
@usersURL = {{baseURL}}/internal/services/users/v1
@company_id = 357d0f1c-9dc9-11eb-ae20-0242ac120002
@workspace_id = 361a5be0-f509-11eb-a69b-d9862196e0cd
@user_id = ca68bc2a-81a4-11eb-8cf1-0242ac1e0002
# @name login
POST {{baseURL}}/internal/services/console/v1/login
Content-Type: application/json
{
"email": "",
"password": ""
}
### AUTH - GET TOKEN
@authToken = {{login.response.body.access_token.value}}
### USERS - GET
GET {{usersURL}}/users/{{user_id}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
### WORKSPACES - LIST
GET {{workspacesURL}}/companies/{{company_id}}/workspaces
Content-Type: application/json
Authorization: Bearer {{authToken}}
### WORKSPACES - CREATE
POST {{workspacesURL}}/companies/{{company_id}}/workspaces
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"name": "created workspace",
"logo": "",
"default": false,
"archived": false
}
}
### WORKSPACES - UPDATE
POST {{workspacesURL}}/companies/{{company_id}}/workspaces/{{workspace_id}}
Content-Type: application/json
Authorization: Bearer {{authToken}}
{
"resource": {
"name": "updated workspace",
"logo": "",
"default": false,
"archived": false
}
}
@@ -0,0 +1,116 @@
import { describe, expect, it, jest } from "@jest/globals";
import { CreateResult } from "../../../../../../../src/core/platform/framework/api/crud-service";
import { RealtimeCreated } from "../../../../../../../src/core/platform/framework/decorators";
import { websocketEventBus } from "../../../../../../../src/core/platform/services/realtime/bus";
import { ResourcePath } from "../../../../../../../src/core/platform/services/realtime/types";
describe("The RealtimeCreated decorator", () => {
it("should call the original method send back original result but do not emit event if result type is wrong", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeCreated({ room: "/foo/bar" })
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
reverseMeBaby(input: string): Promise<string> {
return Promise.resolve(input.split("").reverse().join(""));
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(0);
emitSpy.mockRestore();
done();
});
it("should call the original method send back original result and emit event", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeCreated({ room: "/foo/bar", path: "/foo/bar/baz" })
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async reverseMeBaby(input: string): Promise<CreateResult<string>> {
return new CreateResult<string>("string", input.split("").reverse().join(""));
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result.entity).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(1);
expect(emitSpy).toHaveBeenCalledWith("created", {
room: {
name: "default",
path: ["/foo/bar"],
} as ResourcePath,
resourcePath: "/foo/bar/baz",
entity: "oloy",
type: "string",
result: {
entity: "oloy",
type: "string",
context: undefined,
operation: "create",
raw: undefined,
} as CreateResult<string>,
});
emitSpy.mockRestore();
done();
});
it("should emit event with path computed from function", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeCreated<string>(input => [
{ room: ResourcePath.get(`/foo/bar/${input}`), path: "/foo/bar/baz" },
])
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async reverseMeBaby(input: string): Promise<CreateResult<string>> {
return new CreateResult<string>("string", input.split("").reverse().join(""));
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result.entity).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(1);
expect(emitSpy).toHaveBeenCalledWith("created", {
room: {
name: "default",
path: ["/foo/bar/oloy"],
} as ResourcePath,
resourcePath: "/foo/bar/baz",
entity: "oloy",
type: "string",
result: {
entity: "oloy",
context: undefined,
operation: "create",
type: "string",
raw: undefined,
} as CreateResult<string>,
});
emitSpy.mockRestore();
done();
});
});
@@ -0,0 +1,116 @@
import { describe, expect, it, jest } from "@jest/globals";
import { DeleteResult } from "../../../../../../../src/core/platform/framework/api/crud-service";
import { RealtimeDeleted } from "../../../../../../../src/core/platform/framework/decorators";
import { websocketEventBus } from "../../../../../../../src/core/platform/services/realtime/bus";
import { ResourcePath } from "../../../../../../../src/core/platform/services/realtime/types";
describe("The RealtimeDeleted decorator", () => {
it("should call the original method send back original result but do not emit event if result type is wrong", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeDeleted({ room: "/foo/bar" })
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
reverseMeBaby(input: string): Promise<string> {
return Promise.resolve(input.split("").reverse().join(""));
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(0);
emitSpy.mockRestore();
done();
});
it("should call the original method send back original result and emit event", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeDeleted({ room: "/foo/bar", path: "/foo/bar/baz" })
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async reverseMeBaby(input: string): Promise<DeleteResult<string>> {
return new DeleteResult<string>("string", input.split("").reverse().join(""), true);
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result.entity).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(1);
expect(emitSpy).toHaveBeenCalledWith("deleted", {
room: {
name: "default",
path: ["/foo/bar"],
} as ResourcePath,
resourcePath: "/foo/bar/baz",
entity: "oloy",
type: "string",
result: {
entity: "oloy",
context: undefined,
operation: "delete",
deleted: true,
type: "string",
} as DeleteResult<string>,
});
emitSpy.mockRestore();
done();
});
it("should emit event with path computed from function", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeDeleted(result => [
{ room: ResourcePath.get(`/foo/bar/${result}`), path: "/foo/bar/baz" },
])
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async reverseMeBaby(input: string): Promise<DeleteResult<string>> {
return new DeleteResult<string>("string", input.split("").reverse().join(""), true);
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result.entity).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(1);
expect(emitSpy).toHaveBeenCalledWith("deleted", {
room: {
name: "default",
path: ["/foo/bar/oloy"],
} as ResourcePath,
resourcePath: "/foo/bar/baz",
entity: "oloy",
type: "string",
result: {
entity: "oloy",
context: undefined,
operation: "delete",
deleted: true,
type: "string",
} as DeleteResult<string>,
});
emitSpy.mockRestore();
done();
});
});
@@ -0,0 +1,118 @@
import { describe, expect, it, jest } from "@jest/globals";
import { UpdateResult } from "../../../../../../../src/core/platform/framework/api/crud-service";
import { RealtimeUpdated } from "../../../../../../../src/core/platform/framework/decorators";
import { websocketEventBus } from "../../../../../../../src/core/platform/services/realtime/bus";
import { ResourcePath } from "../../../../../../../src/core/platform/services/realtime/types";
describe("The RealtimeUpdated decorator", () => {
it("should call the original method send back original result but do not emit event if result type is wrong", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeUpdated({ room: "/foo/bar" })
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
reverseMeBaby(input: string): Promise<string> {
return Promise.resolve(input.split("").reverse().join(""));
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(0);
emitSpy.mockRestore();
done();
});
it("should call the original method send back original result and emit event", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeUpdated({ room: "/foo/bar", path: "/foo/bar/baz" })
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async reverseMeBaby(input: string): Promise<UpdateResult<string>> {
return new UpdateResult<string>("string", input.split("").reverse().join(""));
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result.entity).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(1);
expect(emitSpy).toHaveBeenCalledWith("updated", {
entity: "oloy",
room: {
name: "default",
path: ["/foo/bar"],
} as ResourcePath,
resourcePath: "/foo/bar/baz",
type: "string",
result: {
type: "string",
entity: "oloy",
affected: undefined,
context: undefined,
operation: "update",
raw: undefined,
} as UpdateResult<string>,
});
emitSpy.mockRestore();
done();
});
it("should emit event with path computed from function", async done => {
const emitSpy = jest.spyOn(websocketEventBus, "emit");
class TestMe {
@RealtimeUpdated(result => [
{ room: ResourcePath.get(`/foo/bar/${result}`), path: "/foo/bar/baz" },
])
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async reverseMeBaby(input: string): Promise<UpdateResult<string>> {
return new UpdateResult<string>("string", input.split("").reverse().join(""));
}
}
const test = new TestMe();
const originalSpy = jest.spyOn(test, "reverseMeBaby");
const result = await test.reverseMeBaby("yolo");
expect(result.entity).toEqual("oloy");
expect(originalSpy).toHaveBeenCalledTimes(1);
expect(originalSpy).toHaveBeenCalledWith("yolo");
expect(emitSpy).toHaveBeenCalledTimes(1);
expect(emitSpy).toHaveBeenCalledWith("updated", {
entity: "oloy",
room: {
name: "default",
path: ["/foo/bar/oloy"],
} as ResourcePath,
resourcePath: "/foo/bar/baz",
type: "string",
result: {
type: "string",
context: undefined,
operation: "update",
entity: "oloy",
affected: undefined,
raw: undefined,
} as UpdateResult<string>,
});
emitSpy.mockRestore();
done();
});
});
@@ -0,0 +1,181 @@
import "reflect-metadata";
import { describe, expect, it } from "@jest/globals";
import {
buildSelectQuery,
buildComparison,
buildIn,
} from "../../../../../../../../../src/core/platform/services/database/services/orm/connectors/cassandra/query-builder";
import { ChannelMemberNotificationPreference } from "../../../../../../../../../src/services/notifications/entities/channel-member-notification-preferences";
describe("The QueryBuilder module", () => {
describe("The buildSelectQuery function", () => {
it("should build a valid query from primary key parameters", () => {
const filters = {
company_id: "comp1",
channel_id: "chan1",
};
const result = buildSelectQuery<ChannelMemberNotificationPreference>(
ChannelMemberNotificationPreference,
filters,
{},
{ keyspace: "tdrive" },
);
expect(result).toEqual(
"SELECT * FROM tdrive.channel_members_notification_preferences WHERE company_id = comp1 AND channel_id = chan1;",
);
});
it("should build a valid query from primary key parameters and comparison", () => {
const filters = {
company_id: "comp1",
channel_id: "chan1",
};
const result = buildSelectQuery<ChannelMemberNotificationPreference>(
ChannelMemberNotificationPreference,
filters,
{
$lt: [["last_read", 1000]],
},
{ keyspace: "tdrive" },
);
expect(result).toEqual(
"SELECT * FROM tdrive.channel_members_notification_preferences WHERE company_id = comp1 AND channel_id = chan1 AND last_read < 1000;",
);
});
it("should build IN query from array parameters", () => {
const filters = {
company_id: "comp1",
channel_id: "chan1",
user_id: ["u1", "u2", "u3"],
};
const result = buildSelectQuery<ChannelMemberNotificationPreference>(
ChannelMemberNotificationPreference,
filters,
{},
{ keyspace: "tdrive" },
);
expect(result).toEqual(
"SELECT * FROM tdrive.channel_members_notification_preferences WHERE company_id = comp1 AND channel_id = chan1 AND user_id IN (u1,u2,u3);",
);
});
it("should not build IN query from array parameters when array is empty", () => {
const filters = {
company_id: "comp1",
channel_id: "chan1",
user_id: [],
};
const result = buildSelectQuery<ChannelMemberNotificationPreference>(
ChannelMemberNotificationPreference,
filters,
{},
{ keyspace: "tdrive" },
);
expect(result).toEqual(
"SELECT * FROM tdrive.channel_members_notification_preferences WHERE company_id = comp1 AND channel_id = chan1;",
);
});
});
describe("The buildComparison function", () => {
it("should create a valid < string", () => {
expect(
buildComparison({
$lt: [["foo", 1]],
}),
).toContain("foo < 1");
const result = buildComparison({
$lt: [
["foo", 1],
["bar", 2],
],
});
expect(result).toContain("foo < 1");
expect(result).toContain("bar < 2");
});
it("should create a valid <= string", () => {
expect(
buildComparison({
$lte: [["foo", 1]],
}),
).toContain("foo <= 1");
const result = buildComparison({
$lte: [
["foo", 1],
["bar", 2],
],
});
expect(result).toContain("foo <= 1");
expect(result).toContain("bar <= 2");
});
it("should create a valid > string", () => {
expect(
buildComparison({
$gt: [["foo", 1]],
}),
).toContain("foo > 1");
const result = buildComparison({
$gt: [
["foo", 1],
["bar", 2],
],
});
expect(result).toContain("foo > 1");
expect(result).toContain("bar > 2");
});
it("should create a valid >= string", () => {
expect(
buildComparison({
$gte: [["foo", 1]],
}),
).toContain("foo >= 1");
const result = buildComparison({
$gte: [
["foo", 1],
["bar", 2],
],
});
expect(result).toContain("foo >= 1");
expect(result).toContain("bar >= 2");
});
it("should combine conditions", () => {
const result = buildComparison({
$gt: [["foo", 1]],
$gte: [["bar", 2]],
$lt: [["baz", 3]],
$lte: [["qix", 4]],
});
expect(result).toContain("foo > 1");
expect(result).toContain("bar >= 2");
expect(result).toContain("baz < 3");
expect(result).toContain("qix <= 4");
});
});
describe("The buildIn function", () => {
it("should create a id IN (ids) string", () => {
expect(
buildIn({
$in: [["id", ["1", "2", "3"]]],
}),
).toContain("id IN (1,2,3)");
});
});
});
@@ -0,0 +1,31 @@
import "reflect-metadata";
import { describe, expect, it } from "@jest/globals";
import {
fromMongoDbOrderable,
toMongoDbOrderable,
} from "../../../../../../src/core/platform/services/database/services/orm/utils";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import _ from "lodash";
import { v1 as uuidv1 } from "uuid";
describe("The MongoDb to Orderable module", () => {
describe("The to/from orderable function", () => {
it("should be unique", () => {
const uuid1 = toMongoDbOrderable(uuidv1());
const uuid2 = toMongoDbOrderable(uuidv1());
const uuid3 = toMongoDbOrderable(uuidv1());
const uuid4 = toMongoDbOrderable(uuidv1());
expect(_.uniq([uuid1, uuid2, uuid3, uuid4]).length).toBe(4);
});
it("should convert both ways", () => {
const uuid = uuidv1();
const orderable = toMongoDbOrderable(uuid);
expect(fromMongoDbOrderable(orderable)).toBe(uuid);
expect(orderable).toBe(toMongoDbOrderable(fromMongoDbOrderable(orderable)));
});
});
});
@@ -0,0 +1,31 @@
import { describe, expect, it } from "@jest/globals";
import { decrypt } from "../../../../../src/core/crypto/index";
import v2 from "../../../../../src/core/crypto/v2";
import v1 from "../../../../../src/core/crypto/v1";
import legacy from "../../../../../src/core/crypto/legacy";
describe("Encryption", () => {
const encryptionKey = "a7c06651a7c063bb3e90c0c9a17eab88ab8977665127196a";
describe("The encrypt/decrypt functions", () => {
it("should successfully describe legacy encrypted values", async () => {
const legacyEncrypted = "encrypted_DwMLnKhuFbIanqBJPA5rcw==";
expect(legacy.decrypt(legacyEncrypted, encryptionKey).data).toBe("My company");
expect(decrypt(legacyEncrypted, encryptionKey).data).toBe("My company");
});
it("should successfully describe all versions", async () => {
const myData = { key: "some data" };
const v1Encrypted = v1.encrypt(myData, encryptionKey);
const v2Encrypted = v2.encrypt(myData, encryptionKey);
expect(v1.decrypt(v1Encrypted.data, encryptionKey).data).toMatchObject(myData);
expect(v2.decrypt(v2Encrypted.data, encryptionKey).data).toMatchObject(myData);
expect(decrypt(v1Encrypted.data, encryptionKey).data).toMatchObject(myData);
expect(decrypt(v2Encrypted.data, encryptionKey).data).toMatchObject(myData);
});
});
});
@@ -0,0 +1,35 @@
import { describe, expect, it } from "@jest/globals";
import * as pickUtils from "../../src/utils/pick";
describe("The pick utils", () => {
describe("The pick function", () => {
it("should return an object wich contains only the defined properties", () => {
class TestClass {
keep: string;
me: string;
skip: string;
}
const keysToKeep = ["keep", "me"] as const;
const object = { keep: "foo", me: "bar", skip: "baz" } as TestClass;
const result = pickUtils.pick(object, ...keysToKeep);
expect(result).toEqual({ keep: "foo", me: "bar" });
expect(result).not.toContain("skip");
});
it("should return an empty object when input is empty", () => {
class TestClass {
keep: string;
me: string;
skip: string;
}
const keysToKeep = [] as const;
const object = { keep: "foo", me: "bar", skip: "baz" } as TestClass;
const result = pickUtils.pick(object, ...keysToKeep);
expect(result).toEqual({});
});
});
});