ToolJet/server/test/controllers/tooljet_db.e2e-spec.ts
Muhsin Shah C P 32740743e1
[Improvement] URLs scoped with workspace id (#5487)
* add: new URL prefix

* fix: working on home page

* add: profile path

* playing with rxjs

* removed context part

* working on path changes

* changing routes
- TODO: replace the workspaceId with actual id

* redo: public apps path

* initial commit

* added authorize API

* remove privileges from auth response

* fixed some api issue
- added subscriptions

* fix: redirect url workspace-id null issue

* fix: switch workspace

* fix: organization list mapping
- menu item paths

* fix: preview url
- editor, viewer permission mapping

* jwt fix

* fix: some url issue
- permission mappings
- workspace login

* fixed some issues
- user invite workspace-id
- org settings menu item default selected item issue

* app viewer fixes

* fixing workspace login issues

* fix

* fixing issues
- tooljet db
- path issues
- refatoring the code

* fix: workspace vars permissions

* fix: multi-page handle

* fix: create app from template

* fix: bulk user upload

* fix: import app
- clone app
- upload profile image

* fix: onboarding

* fix: log out

* fixed multi-workspace logout issue

* fix: launch btn

* fix: oauth2

* fixes

* fix: sso login

* fix: workspace sso login

* fixing sso issues

* fix: moved list of orgs to rxjs
- fixed switching issues

* reverting some changes

* fixed some minor bugs

* fixing sso redirect url issues

* fix: switching network timing issues

* fix: back to workspace-id

* fix: tj-database
- refactored the code - removed org id from some pages
- will get the org id from the service file only

* fix: multi-pages

* fix: infinite loop issue

* fixing workspace switching issue

* fixes
- comment link
- logout & private route redirect url

* fix: wrong uuid error

* fixing subpath
- fixed most of the places
- need to test & fix workspace login, sso, new account

* fix: subpath workspace login

* fix: rxjs handle bug

* Revert "fix: tj-database"

This reverts commit 9632ec2ff0.

* fix: reverted tj-db changes

* fix: subpath sso

* typo fix

* fix: existing session issues

* new: switch workspace page

* fix: modal dark-mode

* added default sso support

* fixes
- subpath workspace switching
- handle wrong routes

* fix: manager user button
- refactored the code

* removed SINGLE Workspace feature

* rebase

* add: change modal text

* fix: added validation

* fixed private app 401 issue

* initial commit

* fix: logged out session multi-tab issue

* refactoring the code

* fix: redirect url issue

* added auth-token in cookies

* Fix: failing e2e specs

* added session API

* fix: backend session guard

* fix: removing user details from local storage

* fix: null wid

* undo and redo

* fix: login page

* fix: viewer login redirection

* fix: login page redirection

* fix: public apps logout issue

* added session storage and scheduler

* added profile api

* fix: sso login
- switch workspace
- login page
- setup admin

* working on fixes

* fix: socket issue

* fix: setup admin api

* connected profile & logout apis

* fix: malfunctioned auth token case

* fix: realtime avatar

* fix: profile avatar

* fix: Realtime cursors avatar

* setting max age for auth token cookie

* add: Go to login page if logout api returns 401

* fix: subpath login

* fix

* fix: app logout [viewer]

* fix: authorize page

* remove expiry from jwt

* fix: integrations route
- session api

* small fix

* fix: updated profile

* fix: workspace login [logged user]

* fix: oauth and another workspace page issue

* fixed app preview logout issue

* subpath fix

* fix: subpath app id

* fix: selected state didnt change for apps page [subpath]

* fix

* add cookie parser to test app

* specs added

* increased user session expiry time

* test: session & new apis

* working on test cases

* fix: onboarding issue

* fixing specs

* fix: test cases

* fix: removing profile api calls

* some fixes

* fixing rebase issues

* fix: global ds issues

* fix: app is crashing

* fix: back to text

* fix: oauth test cases

* fix: test-helper

* fix: onboarding test cases

* fix: tests again

* refactoring the code

* latest develop merging precautions
- fixed a minor null issue

* fix: typo

* fix :menu issues due to the merging

* fix: - clicking on tooljet logo didnt redirect to login page for public apps
- private app preview doesnt load after login

* subpath fixes

* fixed back to issue

* PR changes

* fix: spec fixes for EE

* doc: URL scoped for workspace

---------

Co-authored-by: gsmithun4 <gsmithun4@gmail.com>
Co-authored-by: Shubhendra <withshubh@gmail.com>
2023-04-06 16:42:58 +05:30

267 lines
9.7 KiB
TypeScript

import * as request from 'supertest';
import { INestApplication } from '@nestjs/common';
import { authHeaderForUser, clearDB, createUser, createNestAppInstanceWithEnvMock } from '../test.helper';
import { getManager, QueryFailedError } from 'typeorm';
import { InternalTable } from 'src/entities/internal_table.entity';
import { mocked } from 'ts-jest/utils';
import got from 'got';
jest.mock('got');
const mockedGot = mocked(got);
//TODO: this spec will need postgrest instance to run (skipping for now)
describe.skip('Tooljet DB controller', () => {
let nestApp: INestApplication;
let mockConfig;
beforeEach(async () => {
await clearDB();
});
beforeAll(async () => {
({ app: nestApp, mockConfig } = await createNestAppInstanceWithEnvMock());
});
afterEach(async () => {
jest.resetAllMocks();
jest.clearAllMocks();
const internalTables = await getManager().find(InternalTable);
for (const internalTable of internalTables) {
await getManager('tooljetDb').query(`TRUNCATE "${internalTable.id}" RESTART IDENTITY CASCADE;`);
}
});
describe('GET /api/tooljet_db/organizations/:organizationId/proxy/*', () => {
it('should allow only authenticated users', async () => {
const mockId = 'c8657683-b112-4a36-9ce7-79ebf68c8098';
await request(nestApp.getHttpServer())
.get(`/api/tooljet_db/organizations/${mockId}/proxy/table_name`)
.expect(401);
});
it('should allow only active users in workspace', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const archivedUserData = await createUser(nestApp, {
email: 'developer@tooljet.io',
groups: ['all_users'],
status: 'archived',
organization: adminUserData.organization,
});
await request(nestApp.getHttpServer())
.get(`/api/tooljet_db/organizations/${archivedUserData.organization.id}/proxy/table_name`)
.set('tj-workspace-id', archivedUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(archivedUserData.user))
.expect(401);
});
it('should throw error when internal table is not found', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const response = await request(nestApp.getHttpServer())
.get(`/api/tooljet_db/organizations/${adminUserData.organization.id}/proxy/\${table_name}`)
.set('tj-workspace-id', adminUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(adminUserData.user));
const { message, statusCode } = response.body;
expect(message).toBe('Internal table not found: table_name');
expect(statusCode).toBe(404);
});
xit('should replace the table names and proxy requests to postgrest host', async () => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
if (key === 'PGRST_HOST') {
return 'http://postgrest-mock';
} else {
return process.env[key];
}
});
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const actorsTable = getManager().create(InternalTable, {
tableName: 'actors',
organizationId: adminUserData.organization.id,
});
await actorsTable.save();
const filmsTable = getManager().create(InternalTable, {
tableName: 'films',
organizationId: adminUserData.organization.id,
});
await filmsTable.save();
const postgrestResponse = jest.fn();
postgrestResponse.mockImplementation(() => {
return {
json: () => {
return {
root: [],
};
},
};
});
mockedGot.mockImplementationOnce(postgrestResponse);
const response = await request(nestApp.getHttpServer())
.get(
`/api/tooljet_db/organizations/${adminUserData.organization.id}/proxy/\${actors}?select=first_name,last_name,\${films}(title)}`
)
.set('tj-workspace-id', adminUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(adminUserData.user));
// expect(postgrestResponse).toBeCalledWith(`http://localhost:3001/${actorsTable.id}?select=first_name,last_name,${filmsTable.id}(title)`, expect.anything());
const { message, statusCode } = response.body;
expect(message).toBe('Internal table not found: table_name');
expect(statusCode).toBe(404);
});
});
describe('GET /api/tooljet_db/organizations/table', () => {
it('should allow only authenticated users', async () => {
const mockId = 'c8657683-b112-4a36-9ce7-79ebf68c8098';
await request(nestApp.getHttpServer())
.get(`/api/tooljet_db/organizations/${mockId}/tables`)
.send({ action: 'view_tables' })
.expect(401);
});
it('should allow only active users in workspace', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const archivedUserData = await createUser(nestApp, {
email: 'developer@tooljet.io',
groups: ['all_users'],
status: 'archived',
organization: adminUserData.organization,
});
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/organizations/${archivedUserData.organization.id}/table`)
.set('tj-workspace-id', archivedUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(archivedUserData.user))
.expect(401);
});
it('should be able to create table', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
const { statusCode } = await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/organizations/${adminUserData.organization.id}/table`)
.set('tj-workspace-id', adminUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'create_table',
table_name: 'test_table',
columns: [{ column_name: 'id', data_type: 'serial', constraint: 'PRIMARY KEY' }],
});
expect(statusCode).toBe(201);
const internalTables = await getManager().find(InternalTable);
expect(internalTables).toHaveLength(1);
const [createdInternalTable] = internalTables;
expect(createdInternalTable.tableName).toEqual('test_table');
await expect(
getManager('tooljetDb').query(`SELECT * from "${createdInternalTable.id}"`)
).resolves.not.toThrowError(QueryFailedError);
});
it('should be able to view tables', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/organizations/${adminUserData.organization.id}/table`)
.set('tj-workspace-id', adminUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'create_table',
table_name: 'actors',
columns: [{ column_name: 'id', data_type: 'serial', constraint: 'PRIMARY KEY' }],
});
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/organizations/${adminUserData.organization.id}/table`)
.set('tj-workspace-id', adminUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'create_table',
table_name: 'films',
columns: [{ column_name: 'id', data_type: 'serial', constraint: 'PRIMARY KEY' }],
});
const { statusCode, body } = await request(nestApp.getHttpServer())
.get(`/api/tooljet_db/organizations/${adminUserData.organization.id}/tables`)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({ action: 'view_tables' });
const tableNames = body.result.map((table) => table.table_name);
expect(statusCode).toBe(200);
expect(new Set(tableNames)).toEqual(new Set(['actors', 'films']));
});
it('should be able to add column to table', async () => {
const adminUserData = await createUser(nestApp, {
email: 'admin@tooljet.io',
});
await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/organizations/${adminUserData.organization.id}/table`)
.set('tj-workspace-id', adminUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'create_table',
table_name: 'test_table',
columns: [{ column_name: 'id', data_type: 'serial', constraint: 'PRIMARY KEY' }],
});
const internalTable = await getManager().findOne(InternalTable, { where: { tableName: 'test_table' } });
expect(internalTable.tableName).toEqual('test_table');
await expect(getManager('tooljetDb').query(`SELECT name from "${internalTable.id}"`)).rejects.toThrowError(
QueryFailedError
);
const { statusCode } = await request(nestApp.getHttpServer())
.post(`/api/tooljet_db/organizations/${adminUserData.organization.id}/table/test_table/column`)
.set('tj-workspace-id', adminUserData.user.defaultOrganizationId)
.set('Authorization', authHeaderForUser(adminUserData.user))
.send({
action: 'add_column',
table_name: 'test_table',
column: { column_name: 'name', data_type: 'varchar' },
});
expect(statusCode).toBe(201);
await expect(getManager('tooljetDb').query(`SELECT name from "${internalTable.id}"`)).resolves.not.toThrowError(
QueryFailedError
);
});
});
afterAll(async () => {
await nestApp.close();
});
});