ToolJet/server/test/controllers/app.e2e-spec.ts

1036 lines
40 KiB
TypeScript
Raw Normal View History

/* eslint-disable @typescript-eslint/no-unused-vars */
2021-07-08 05:40:27 +00:00
import * as request from 'supertest';
2021-07-08 16:43:23 +00:00
import { INestApplication } from '@nestjs/common';
import { getManager, Repository, Not } from 'typeorm';
import { User } from 'src/entities/user.entity';
import { clearDB, createUser, authHeaderForUser, createNestAppInstanceWithEnvMock } from '../test.helper';
import { OrganizationUser } from 'src/entities/organization_user.entity';
import { Organization } from 'src/entities/organization.entity';
import { SSOConfigs } from 'src/entities/sso_config.entity';
import { EmailService } from '@services/email.service';
import { v4 as uuidv4 } from 'uuid';
2021-07-08 05:40:27 +00:00
2021-07-08 16:43:23 +00:00
describe('Authentication', () => {
2021-07-08 05:40:27 +00:00
let app: INestApplication;
2021-07-08 16:43:23 +00:00
let userRepository: Repository<User>;
let orgRepository: Repository<Organization>;
let orgUserRepository: Repository<OrganizationUser>;
let ssoConfigsRepository: Repository<SSOConfigs>;
let mockConfig;
let current_organization: Organization;
let current_user: User;
beforeEach(async () => {
await clearDB();
});
2021-07-08 05:40:27 +00:00
2021-07-08 16:43:23 +00:00
beforeAll(async () => {
({ app, mockConfig } = await createNestAppInstanceWithEnvMock());
2021-07-08 16:43:23 +00:00
userRepository = app.get('UserRepository');
orgRepository = app.get('OrganizationRepository');
orgUserRepository = app.get('OrganizationUserRepository');
ssoConfigsRepository = app.get('SSOConfigsRepository');
2021-07-08 05:40:27 +00:00
});
afterEach(() => {
jest.resetAllMocks();
jest.clearAllMocks();
});
Feature: User access management 🔥 (#918) * create migrations for group permissions setup * define new entities and relationships * revise migrations * rename columns * add migration to populate permission groups for existing users * Feature: User access permission group usage (#883) * create migrations for group permissions setup * define new entities and relationships * revise migrations * rename columns * add migration to populate permission groups for existing users * revise migrations * hide roles usage * setup group permissions for apps and users * fix defaultChecked * fix update permission checkbox * fix casl ability check to have params passed * fix casl apps abilities to check with app specific permission * add ability to delete groups * conditionally render edit and delete options for all and admin users * fix user role to group migration * revise group management pages to disallow updating default group * move manage users and groups to navbar dropdown * show only addable apps and users on dropdowns * rename header as profile settings * scope addable apps and users by organization * scope viewable apps on homepage * hide manage groups link from non admins * make permissions to be used with radio input * add loading state for add apps/users buttons * revise unit tests * revise migrations * fix e2e tests * comment out dead code * fix seeds script * handle folder count * captalize error toast * hide manage users dropdown for non admins * show fobidden error on blank homepage * fix folder app count * fix invalid state set * make group name clickable for edit instead * users with edit permission can deploy apps * not show edit link on homepage if user dont have update permission * remove unused entity from merge * remove roles usage from manage org users page * fix folder count and blank slate on homepage * disable add buttons if there is no selections * humanize default groups on view * make app added onto groups have read permission by default * not show app menu if user is not admin * remove admin users from group user addition dropdown * create default permissions for app cloned * fix querying index page without page params * fix admin scoped out from group add * remove apps from header * fix invitation url not shown * scope admin deletion check by org * scope public apps by organization * add specs for group permissions e2e * removed unused entity and add group permissions spec * remove console logs * remove unused permission * scope public app count by org * remove console log * refactor manage group permission resources component * update group permssion in org scope
2021-10-11 15:15:58 +00:00
describe('Single organization', () => {
beforeEach(async () => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_SIGNUPS':
return 'false';
case 'DISABLE_MULTI_WORKSPACE':
return 'true';
default:
return process.env[key];
}
});
});
it('should create new users and organization', async () => {
const response = await request(app.getHttpServer()).post('/api/signup').send({ email: 'test@tooljet.io' });
expect(response.statusCode).toBe(201);
Feature: User access management 🔥 (#918) * create migrations for group permissions setup * define new entities and relationships * revise migrations * rename columns * add migration to populate permission groups for existing users * Feature: User access permission group usage (#883) * create migrations for group permissions setup * define new entities and relationships * revise migrations * rename columns * add migration to populate permission groups for existing users * revise migrations * hide roles usage * setup group permissions for apps and users * fix defaultChecked * fix update permission checkbox * fix casl ability check to have params passed * fix casl apps abilities to check with app specific permission * add ability to delete groups * conditionally render edit and delete options for all and admin users * fix user role to group migration * revise group management pages to disallow updating default group * move manage users and groups to navbar dropdown * show only addable apps and users on dropdowns * rename header as profile settings * scope addable apps and users by organization * scope viewable apps on homepage * hide manage groups link from non admins * make permissions to be used with radio input * add loading state for add apps/users buttons * revise unit tests * revise migrations * fix e2e tests * comment out dead code * fix seeds script * handle folder count * captalize error toast * hide manage users dropdown for non admins * show fobidden error on blank homepage * fix folder app count * fix invalid state set * make group name clickable for edit instead * users with edit permission can deploy apps * not show edit link on homepage if user dont have update permission * remove unused entity from merge * remove roles usage from manage org users page * fix folder count and blank slate on homepage * disable add buttons if there is no selections * humanize default groups on view * make app added onto groups have read permission by default * not show app menu if user is not admin * remove admin users from group user addition dropdown * create default permissions for app cloned * fix querying index page without page params * fix admin scoped out from group add * remove apps from header * fix invitation url not shown * scope admin deletion check by org * scope public apps by organization * add specs for group permissions e2e * removed unused entity and add group permissions spec * remove console logs * remove unused permission * scope public app count by org * remove console log * refactor manage group permission resources component * update group permssion in org scope
2021-10-11 15:15:58 +00:00
const user = await userRepository.findOneOrFail({
where: { email: 'test@tooljet.io' },
relations: ['organizationUsers'],
});
const organization = await orgRepository.findOneOrFail({
where: { id: user?.organizationUsers?.[0]?.organizationId },
});
expect(user.defaultOrganizationId).toBe(user?.organizationUsers?.[0]?.organizationId);
expect(organization.name).toBe('Untitled workspace');
2021-07-20 09:10:11 +00:00
const groupPermissions = await user.groupPermissions;
const groupNames = groupPermissions.map((x) => x.group);
2021-07-08 16:43:23 +00:00
expect(new Set(['all_users', 'admin'])).toEqual(new Set(groupNames));
const adminGroup = groupPermissions.find((x) => x.group == 'admin');
expect(adminGroup.appCreate).toBeTruthy();
expect(adminGroup.appDelete).toBeTruthy();
expect(adminGroup.folderCreate).toBeTruthy();
[Feature] Organisation level environment variables 🚀 (#3068) * Added new page for env vars * Changed a field name * Added some backend files - Entity, Dto, services * Started working with api endpoints - implmented create - added ability * Added fields validation - Added env variables into module * Added update, delete, get apis - Also implemented delete feature in frontend * Implemented update operation on frontend - Solved an api problem * Added encryption * Added encryption to update operation - Exposed env vars to editor - working on viewer * Exposed env vars in viewer also - Resolved a bug * Updated edit & delete icon sizes * Added specs - Resolved issues that occurred while testing * removed logout code * Changed api endpoint * splitted page into 3 different parts, Form & table * Now, non-admin users can see all org env vars * Resolved divider missing issue * Added variable_type field * Now secret server values will be shown as 'SecureValue' * Now you can't update variable_type * Now server will resolve the secret env values * Resolved variable name issue * Added unique constraints * Resolved some frontend bugs * Changed error text * Fixed failing specs * Added group permissions for org env vars * Added permission checking in the backend * Implemented permission checking in the frontend * Edited spec for new changes * Changed some specs and fixed failing specs * Resolved failing case that showed up after merging with the latest develop * Added default admin seed permissions * Refactored some code * Changed value to organization_id * Fixed a bug * Resolved a failing case * Resolved PR changes - Changed permission name - Changed column type to enum - Fixed some errors - Refactored the code * minor code change * added scope * Fixed: hide table when 0 no of vars available * Fixed table dark theme issues * Fixed encryption switch style * Fixed failing cases and updated a spec * Added %% for environment variables * Added code to resolve single variable * Fixed multi-variable usage * resolved an issue * removed extra divider * Suggestions will also show up for %% too * now, suggestions dropdown will only show env variables results * env vars suggestions will not be included in js search results * You can't resolve env variables from js code - Also, we can't resolve js code from env variable enclosures * added an info text * Resolved variables issue * fixed Viewer issue * Resolved a bug - client variable was not working on query preview and run actions * Update error message while using server variable on canvas * Revert "Update error message while using server variable on canvas" This reverts commit 081e1c9e295509a2db1010ddce0841c60e57387a. * Resolved all PR changes - removed prefix 'environmentVariable' - redefined variable evaluation - removed environmentVariable object from inspector - fixed a small bug * Fixed a server side issue Co-authored-by: Sherfin Shamsudeen <sherfin94@gmail.com>
2022-07-01 10:50:37 +00:00
expect(adminGroup.orgEnvironmentVariableCreate).toBeTruthy();
expect(adminGroup.orgEnvironmentVariableUpdate).toBeTruthy();
expect(adminGroup.orgEnvironmentVariableDelete).toBeTruthy();
expect(adminGroup.folderUpdate).toBeTruthy();
expect(adminGroup.folderDelete).toBeTruthy();
const allUserGroup = groupPermissions.find((x) => x.group == 'all_users');
expect(allUserGroup.appCreate).toBeFalsy();
expect(allUserGroup.appDelete).toBeFalsy();
expect(allUserGroup.folderCreate).toBeFalsy();
[Feature] Organisation level environment variables 🚀 (#3068) * Added new page for env vars * Changed a field name * Added some backend files - Entity, Dto, services * Started working with api endpoints - implmented create - added ability * Added fields validation - Added env variables into module * Added update, delete, get apis - Also implemented delete feature in frontend * Implemented update operation on frontend - Solved an api problem * Added encryption * Added encryption to update operation - Exposed env vars to editor - working on viewer * Exposed env vars in viewer also - Resolved a bug * Updated edit & delete icon sizes * Added specs - Resolved issues that occurred while testing * removed logout code * Changed api endpoint * splitted page into 3 different parts, Form & table * Now, non-admin users can see all org env vars * Resolved divider missing issue * Added variable_type field * Now secret server values will be shown as 'SecureValue' * Now you can't update variable_type * Now server will resolve the secret env values * Resolved variable name issue * Added unique constraints * Resolved some frontend bugs * Changed error text * Fixed failing specs * Added group permissions for org env vars * Added permission checking in the backend * Implemented permission checking in the frontend * Edited spec for new changes * Changed some specs and fixed failing specs * Resolved failing case that showed up after merging with the latest develop * Added default admin seed permissions * Refactored some code * Changed value to organization_id * Fixed a bug * Resolved a failing case * Resolved PR changes - Changed permission name - Changed column type to enum - Fixed some errors - Refactored the code * minor code change * added scope * Fixed: hide table when 0 no of vars available * Fixed table dark theme issues * Fixed encryption switch style * Fixed failing cases and updated a spec * Added %% for environment variables * Added code to resolve single variable * Fixed multi-variable usage * resolved an issue * removed extra divider * Suggestions will also show up for %% too * now, suggestions dropdown will only show env variables results * env vars suggestions will not be included in js search results * You can't resolve env variables from js code - Also, we can't resolve js code from env variable enclosures * added an info text * Resolved variables issue * fixed Viewer issue * Resolved a bug - client variable was not working on query preview and run actions * Update error message while using server variable on canvas * Revert "Update error message while using server variable on canvas" This reverts commit 081e1c9e295509a2db1010ddce0841c60e57387a. * Resolved all PR changes - removed prefix 'environmentVariable' - redefined variable evaluation - removed environmentVariable object from inspector - fixed a small bug * Fixed a server side issue Co-authored-by: Sherfin Shamsudeen <sherfin94@gmail.com>
2022-07-01 10:50:37 +00:00
expect(allUserGroup.orgEnvironmentVariableCreate).toBeFalsy();
expect(allUserGroup.orgEnvironmentVariableUpdate).toBeFalsy();
expect(allUserGroup.orgEnvironmentVariableDelete).toBeFalsy();
expect(allUserGroup.folderUpdate).toBeFalsy();
expect(allUserGroup.folderDelete).toBeFalsy();
});
describe('Single organization operations', () => {
beforeEach(async () => {
current_organization = (await createUser(app, { email: 'admin@tooljet.io' })).organization;
});
it('should not create new users since organization already exist', async () => {
const response = await request(app.getHttpServer()).post('/api/signup').send({ email: 'test@tooljet.io' });
expect(response.statusCode).toBe(406);
});
it('authenticate if valid credentials', async () => {
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'password' })
.expect(201);
});
it('authenticate to organization if valid credentials', async () => {
await request(app.getHttpServer())
.post('/api/authenticate/' + current_organization.id)
.send({ email: 'admin@tooljet.io', password: 'password' })
.expect(201);
});
it('throw unauthorized error if user does not exist in given organization if valid credentials', async () => {
await request(app.getHttpServer())
.post('/api/authenticate/82249621-efc1-4cd2-9986-5c22182fa8a7')
.send({ email: 'admin@tooljet.io', password: 'password' })
.expect(401);
});
it('throw 401 if user is archived', async () => {
await createUser(app, { email: 'user@tooljet.io', status: 'archived' });
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'user@tooljet.io', password: 'password' })
.expect(401);
const adminUser = await userRepository.findOneOrFail({
email: 'admin@tooljet.io',
});
await orgUserRepository.update({ userId: adminUser.id }, { status: 'archived' });
await request(app.getHttpServer())
.get('/api/organizations/users')
.set('Authorization', authHeaderForUser(adminUser))
.expect(401);
});
it('throw 401 if user is invited', async () => {
await createUser(app, { email: 'user@tooljet.io', status: 'invited' });
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'user@tooljet.io', password: 'password' })
.expect(401);
const adminUser = await userRepository.findOneOrFail({
email: 'admin@tooljet.io',
});
await orgUserRepository.update({ userId: adminUser.id }, { status: 'invited' });
await request(app.getHttpServer())
.get('/api/organizations/users')
.set('Authorization', authHeaderForUser(adminUser))
.expect(401);
});
it('throw 401 if invalid credentials', async () => {
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'amdin@tooljet.io', password: 'pwd' })
.expect(401);
});
it('should throw 401 if form login is disabled', async () => {
await ssoConfigsRepository.update({ organizationId: current_organization.id }, { enabled: false });
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'password' })
.expect(401);
});
});
});
describe('Multi organization', () => {
beforeEach(async () => {
const { organization, user } = await createUser(app, {
email: 'admin@tooljet.io',
firstName: 'user',
lastName: 'name',
});
current_organization = organization;
current_user = user;
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_SIGNUPS':
return 'false';
default:
return process.env[key];
}
});
});
describe('sign up disabled', () => {
beforeEach(async () => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_SIGNUPS':
return 'true';
default:
return process.env[key];
}
});
});
it('should not create new users', async () => {
const response = await request(app.getHttpServer()).post('/api/signup').send({ email: 'test@tooljet.io' });
expect(response.statusCode).toBe(403);
});
});
describe('sign up enabled and authorization', () => {
it('should create new users', async () => {
const response = await request(app.getHttpServer()).post('/api/signup').send({ email: 'test@tooljet.io' });
expect(response.statusCode).toBe(201);
const user = await userRepository.findOneOrFail({
where: { email: 'test@tooljet.io' },
relations: ['organizationUsers'],
});
const organization = await orgRepository.findOneOrFail({
where: { id: user?.organizationUsers?.[0]?.organizationId },
});
expect(user.defaultOrganizationId).toBe(user?.organizationUsers?.[0]?.organizationId);
expect(organization?.name).toBe('Untitled workspace');
const groupPermissions = await user.groupPermissions;
const groupNames = groupPermissions.map((x) => x.group);
expect(new Set(['all_users', 'admin'])).toEqual(new Set(groupNames));
const adminGroup = groupPermissions.find((x) => x.group == 'admin');
expect(adminGroup.appCreate).toBeTruthy();
expect(adminGroup.appDelete).toBeTruthy();
expect(adminGroup.folderCreate).toBeTruthy();
[Feature] Organisation level environment variables 🚀 (#3068) * Added new page for env vars * Changed a field name * Added some backend files - Entity, Dto, services * Started working with api endpoints - implmented create - added ability * Added fields validation - Added env variables into module * Added update, delete, get apis - Also implemented delete feature in frontend * Implemented update operation on frontend - Solved an api problem * Added encryption * Added encryption to update operation - Exposed env vars to editor - working on viewer * Exposed env vars in viewer also - Resolved a bug * Updated edit & delete icon sizes * Added specs - Resolved issues that occurred while testing * removed logout code * Changed api endpoint * splitted page into 3 different parts, Form & table * Now, non-admin users can see all org env vars * Resolved divider missing issue * Added variable_type field * Now secret server values will be shown as 'SecureValue' * Now you can't update variable_type * Now server will resolve the secret env values * Resolved variable name issue * Added unique constraints * Resolved some frontend bugs * Changed error text * Fixed failing specs * Added group permissions for org env vars * Added permission checking in the backend * Implemented permission checking in the frontend * Edited spec for new changes * Changed some specs and fixed failing specs * Resolved failing case that showed up after merging with the latest develop * Added default admin seed permissions * Refactored some code * Changed value to organization_id * Fixed a bug * Resolved a failing case * Resolved PR changes - Changed permission name - Changed column type to enum - Fixed some errors - Refactored the code * minor code change * added scope * Fixed: hide table when 0 no of vars available * Fixed table dark theme issues * Fixed encryption switch style * Fixed failing cases and updated a spec * Added %% for environment variables * Added code to resolve single variable * Fixed multi-variable usage * resolved an issue * removed extra divider * Suggestions will also show up for %% too * now, suggestions dropdown will only show env variables results * env vars suggestions will not be included in js search results * You can't resolve env variables from js code - Also, we can't resolve js code from env variable enclosures * added an info text * Resolved variables issue * fixed Viewer issue * Resolved a bug - client variable was not working on query preview and run actions * Update error message while using server variable on canvas * Revert "Update error message while using server variable on canvas" This reverts commit 081e1c9e295509a2db1010ddce0841c60e57387a. * Resolved all PR changes - removed prefix 'environmentVariable' - redefined variable evaluation - removed environmentVariable object from inspector - fixed a small bug * Fixed a server side issue Co-authored-by: Sherfin Shamsudeen <sherfin94@gmail.com>
2022-07-01 10:50:37 +00:00
expect(adminGroup.orgEnvironmentVariableCreate).toBeTruthy();
expect(adminGroup.orgEnvironmentVariableUpdate).toBeTruthy();
expect(adminGroup.orgEnvironmentVariableDelete).toBeTruthy();
expect(adminGroup.folderUpdate).toBeTruthy();
expect(adminGroup.folderDelete).toBeTruthy();
const allUserGroup = groupPermissions.find((x) => x.group == 'all_users');
expect(allUserGroup.appCreate).toBeFalsy();
expect(allUserGroup.appDelete).toBeFalsy();
expect(allUserGroup.folderCreate).toBeFalsy();
[Feature] Organisation level environment variables 🚀 (#3068) * Added new page for env vars * Changed a field name * Added some backend files - Entity, Dto, services * Started working with api endpoints - implmented create - added ability * Added fields validation - Added env variables into module * Added update, delete, get apis - Also implemented delete feature in frontend * Implemented update operation on frontend - Solved an api problem * Added encryption * Added encryption to update operation - Exposed env vars to editor - working on viewer * Exposed env vars in viewer also - Resolved a bug * Updated edit & delete icon sizes * Added specs - Resolved issues that occurred while testing * removed logout code * Changed api endpoint * splitted page into 3 different parts, Form & table * Now, non-admin users can see all org env vars * Resolved divider missing issue * Added variable_type field * Now secret server values will be shown as 'SecureValue' * Now you can't update variable_type * Now server will resolve the secret env values * Resolved variable name issue * Added unique constraints * Resolved some frontend bugs * Changed error text * Fixed failing specs * Added group permissions for org env vars * Added permission checking in the backend * Implemented permission checking in the frontend * Edited spec for new changes * Changed some specs and fixed failing specs * Resolved failing case that showed up after merging with the latest develop * Added default admin seed permissions * Refactored some code * Changed value to organization_id * Fixed a bug * Resolved a failing case * Resolved PR changes - Changed permission name - Changed column type to enum - Fixed some errors - Refactored the code * minor code change * added scope * Fixed: hide table when 0 no of vars available * Fixed table dark theme issues * Fixed encryption switch style * Fixed failing cases and updated a spec * Added %% for environment variables * Added code to resolve single variable * Fixed multi-variable usage * resolved an issue * removed extra divider * Suggestions will also show up for %% too * now, suggestions dropdown will only show env variables results * env vars suggestions will not be included in js search results * You can't resolve env variables from js code - Also, we can't resolve js code from env variable enclosures * added an info text * Resolved variables issue * fixed Viewer issue * Resolved a bug - client variable was not working on query preview and run actions * Update error message while using server variable on canvas * Revert "Update error message while using server variable on canvas" This reverts commit 081e1c9e295509a2db1010ddce0841c60e57387a. * Resolved all PR changes - removed prefix 'environmentVariable' - redefined variable evaluation - removed environmentVariable object from inspector - fixed a small bug * Fixed a server side issue Co-authored-by: Sherfin Shamsudeen <sherfin94@gmail.com>
2022-07-01 10:50:37 +00:00
expect(allUserGroup.orgEnvironmentVariableCreate).toBeFalsy();
expect(allUserGroup.orgEnvironmentVariableUpdate).toBeFalsy();
expect(allUserGroup.orgEnvironmentVariableDelete).toBeFalsy();
expect(allUserGroup.folderUpdate).toBeFalsy();
expect(allUserGroup.folderDelete).toBeFalsy();
});
it('authenticate if valid credentials', async () => {
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'password' })
.expect(201);
});
it('authenticate to organization if valid credentials', async () => {
await request(app.getHttpServer())
.post('/api/authenticate/' + current_organization.id)
.send({ email: 'admin@tooljet.io', password: 'password' })
.expect(201);
});
it('throw unauthorized error if user does not exist in given organization if valid credentials', async () => {
await request(app.getHttpServer())
.post('/api/authenticate/82249621-efc1-4cd2-9986-5c22182fa8a7')
.send({ email: 'admin@tooljet.io', password: 'password' })
.expect(401);
});
it('throw 401 if user is archived', async () => {
const { orgUser } = await createUser(app, { email: 'user@tooljet.io', status: 'archived' });
await request(app.getHttpServer())
.post(`/api/authenticate/${orgUser.organizationId}`)
.send({ email: 'user@tooljet.io', password: 'password' })
.expect(401);
const adminUser = await userRepository.findOneOrFail({
email: 'admin@tooljet.io',
});
await orgUserRepository.update({ userId: adminUser.id }, { status: 'archived' });
await request(app.getHttpServer())
.get('/api/organizations/users')
.set('Authorization', authHeaderForUser(adminUser))
.expect(401);
});
it('throw 401 if user is invited', async () => {
const { orgUser } = await createUser(app, { email: 'user@tooljet.io', status: 'invited' });
const response = await request(app.getHttpServer())
.post(`/api/authenticate/${orgUser.organizationId}`)
.send({ email: 'user@tooljet.io', password: 'password' })
.expect(401);
const adminUser = await userRepository.findOneOrFail({
email: 'admin@tooljet.io',
});
await orgUserRepository.update({ userId: adminUser.id }, { status: 'invited' });
await request(app.getHttpServer())
.get('/api/organizations/users')
.set('Authorization', authHeaderForUser(adminUser))
.expect(401);
});
it('login to new organization if user is archived', async () => {
const { orgUser } = await createUser(app, { email: 'user@tooljet.io', status: 'archived' });
const response = await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'user@tooljet.io', password: 'password' });
expect(response.statusCode).toBe(201);
expect(response.body.organization_id).not.toBe(orgUser.organizationId);
expect(response.body.organization).toBe('Untitled workspace');
});
it('login to new organization if user is invited', async () => {
const { orgUser } = await createUser(app, { email: 'user@tooljet.io', status: 'invited' });
const response = await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'user@tooljet.io', password: 'password' });
expect(response.statusCode).toBe(201);
expect(response.body.organization_id).not.toBe(orgUser.organizationId);
expect(response.body.organization).toBe('Untitled workspace');
});
it('throw 401 if invalid credentials', async () => {
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'amdin@tooljet.io', password: 'pwd' })
.expect(401);
});
it('throw 401 if invalid credentials, maximum retry limit reached error after 5 retries', async () => {
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
const invalidCredentialResp = await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' });
expect(invalidCredentialResp.statusCode).toBe(401);
expect(invalidCredentialResp.body.message).toBe('Invalid credentials');
const response = await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' });
expect(response.statusCode).toBe(401);
expect(response.body.message).toBe(
'Maximum password retry limit reached, please reset your password using forget password option'
);
});
it('throw 401 if invalid credentials, maximum retry limit reached error will not throw if DISABLE_PASSWORD_RETRY_LIMIT is set to true', async () => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_PASSWORD_RETRY_LIMIT':
return 'true';
default:
return process.env[key];
}
});
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
const response = await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' });
expect(response.statusCode).toBe(401);
expect(response.body.message).toBe('Invalid credentials');
});
it('throw 401 if invalid credentials, maximum retry limit reached error will not throw after the count configured in PASSWORD_RETRY_LIMIT', async () => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'PASSWORD_RETRY_LIMIT':
return '3';
default:
return process.env[key];
}
});
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' })
.expect(401);
const invalidCredentialResp = await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' });
expect(invalidCredentialResp.statusCode).toBe(401);
expect(invalidCredentialResp.body.message).toBe('Invalid credentials');
const response = await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'pwd' });
expect(response.statusCode).toBe(401);
expect(response.body.message).toBe(
'Maximum password retry limit reached, please reset your password using forget password option'
);
});
it('should throw 401 if form login is disabled', async () => {
await ssoConfigsRepository.update({ organizationId: current_organization.id }, { enabled: false });
await request(app.getHttpServer())
.post('/api/authenticate/' + current_organization.id)
.send({ email: 'admin@tooljet.io', password: 'password' })
.expect(401);
});
it('should create new organization if login is disabled for default organization', async () => {
await ssoConfigsRepository.update({ organizationId: current_organization.id }, { enabled: false });
const response = await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'password' });
expect(response.statusCode).toBe(201);
expect(response.body.organization_id).not.toBe(current_organization.id);
expect(response.body.organization).toBe('Untitled workspace');
});
it('should be able to switch between organizations with admin privilege', async () => {
const { organization: invited_organization } = await createUser(
app,
{ organizationName: 'New Organization' },
current_user
);
const response = await request(app.getHttpServer())
.get('/api/switch/' + invited_organization.id)
.set('Authorization', authHeaderForUser(current_user));
expect(response.statusCode).toBe(200);
expect(Object.keys(response.body).sort()).toEqual(
[
'id',
'email',
'first_name',
'last_name',
'auth_token',
'admin',
'organization_id',
'organization',
'group_permissions',
'app_group_permissions',
].sort()
);
const {
email,
first_name,
last_name,
admin,
group_permissions,
app_group_permissions,
organization_id,
organization,
} = response.body;
expect(email).toEqual(current_user.email);
expect(first_name).toEqual(current_user.firstName);
expect(last_name).toEqual(current_user.lastName);
expect(admin).toBeTruthy();
expect(organization_id).toBe(invited_organization.id);
expect(organization).toBe(invited_organization.name);
expect(group_permissions).toHaveLength(2);
expect(group_permissions.some((gp) => gp.group === 'all_users')).toBeTruthy();
expect(group_permissions.some((gp) => gp.group === 'admin')).toBeTruthy();
expect(Object.keys(group_permissions[0]).sort()).toEqual(
[
'id',
'organization_id',
'group',
'app_create',
'app_delete',
'updated_at',
'created_at',
'folder_create',
[Feature] Organisation level environment variables 🚀 (#3068) * Added new page for env vars * Changed a field name * Added some backend files - Entity, Dto, services * Started working with api endpoints - implmented create - added ability * Added fields validation - Added env variables into module * Added update, delete, get apis - Also implemented delete feature in frontend * Implemented update operation on frontend - Solved an api problem * Added encryption * Added encryption to update operation - Exposed env vars to editor - working on viewer * Exposed env vars in viewer also - Resolved a bug * Updated edit & delete icon sizes * Added specs - Resolved issues that occurred while testing * removed logout code * Changed api endpoint * splitted page into 3 different parts, Form & table * Now, non-admin users can see all org env vars * Resolved divider missing issue * Added variable_type field * Now secret server values will be shown as 'SecureValue' * Now you can't update variable_type * Now server will resolve the secret env values * Resolved variable name issue * Added unique constraints * Resolved some frontend bugs * Changed error text * Fixed failing specs * Added group permissions for org env vars * Added permission checking in the backend * Implemented permission checking in the frontend * Edited spec for new changes * Changed some specs and fixed failing specs * Resolved failing case that showed up after merging with the latest develop * Added default admin seed permissions * Refactored some code * Changed value to organization_id * Fixed a bug * Resolved a failing case * Resolved PR changes - Changed permission name - Changed column type to enum - Fixed some errors - Refactored the code * minor code change * added scope * Fixed: hide table when 0 no of vars available * Fixed table dark theme issues * Fixed encryption switch style * Fixed failing cases and updated a spec * Added %% for environment variables * Added code to resolve single variable * Fixed multi-variable usage * resolved an issue * removed extra divider * Suggestions will also show up for %% too * now, suggestions dropdown will only show env variables results * env vars suggestions will not be included in js search results * You can't resolve env variables from js code - Also, we can't resolve js code from env variable enclosures * added an info text * Resolved variables issue * fixed Viewer issue * Resolved a bug - client variable was not working on query preview and run actions * Update error message while using server variable on canvas * Revert "Update error message while using server variable on canvas" This reverts commit 081e1c9e295509a2db1010ddce0841c60e57387a. * Resolved all PR changes - removed prefix 'environmentVariable' - redefined variable evaluation - removed environmentVariable object from inspector - fixed a small bug * Fixed a server side issue Co-authored-by: Sherfin Shamsudeen <sherfin94@gmail.com>
2022-07-01 10:50:37 +00:00
'org_environment_variable_create',
'org_environment_variable_update',
'org_environment_variable_delete',
'folder_delete',
'folder_update',
].sort()
);
expect(app_group_permissions).toHaveLength(0);
await current_user.reload();
expect(current_user.defaultOrganizationId).toBe(invited_organization.id);
});
it('should be able to switch between organizations with user privilege', async () => {
const { organization: invited_organization } = await createUser(
app,
{ groups: ['all_users'], organizationName: 'New Organization' },
current_user
);
const response = await request(app.getHttpServer())
.get('/api/switch/' + invited_organization.id)
.set('Authorization', authHeaderForUser(current_user));
expect(response.statusCode).toBe(200);
expect(Object.keys(response.body).sort()).toEqual(
[
'id',
'email',
'first_name',
'last_name',
'auth_token',
'admin',
'organization_id',
'organization',
'group_permissions',
'app_group_permissions',
].sort()
);
const {
email,
first_name,
last_name,
admin,
group_permissions,
app_group_permissions,
organization_id,
organization,
} = response.body;
expect(email).toEqual(current_user.email);
expect(first_name).toEqual(current_user.firstName);
expect(last_name).toEqual(current_user.lastName);
expect(admin).toBeFalsy();
expect(organization_id).toBe(invited_organization.id);
expect(organization).toBe(invited_organization.name);
expect(group_permissions).toHaveLength(1);
expect(group_permissions[0].group).toEqual('all_users');
expect(Object.keys(group_permissions[0]).sort()).toEqual(
[
'id',
'organization_id',
'group',
'app_create',
'app_delete',
'updated_at',
'created_at',
'folder_create',
[Feature] Organisation level environment variables 🚀 (#3068) * Added new page for env vars * Changed a field name * Added some backend files - Entity, Dto, services * Started working with api endpoints - implmented create - added ability * Added fields validation - Added env variables into module * Added update, delete, get apis - Also implemented delete feature in frontend * Implemented update operation on frontend - Solved an api problem * Added encryption * Added encryption to update operation - Exposed env vars to editor - working on viewer * Exposed env vars in viewer also - Resolved a bug * Updated edit & delete icon sizes * Added specs - Resolved issues that occurred while testing * removed logout code * Changed api endpoint * splitted page into 3 different parts, Form & table * Now, non-admin users can see all org env vars * Resolved divider missing issue * Added variable_type field * Now secret server values will be shown as 'SecureValue' * Now you can't update variable_type * Now server will resolve the secret env values * Resolved variable name issue * Added unique constraints * Resolved some frontend bugs * Changed error text * Fixed failing specs * Added group permissions for org env vars * Added permission checking in the backend * Implemented permission checking in the frontend * Edited spec for new changes * Changed some specs and fixed failing specs * Resolved failing case that showed up after merging with the latest develop * Added default admin seed permissions * Refactored some code * Changed value to organization_id * Fixed a bug * Resolved a failing case * Resolved PR changes - Changed permission name - Changed column type to enum - Fixed some errors - Refactored the code * minor code change * added scope * Fixed: hide table when 0 no of vars available * Fixed table dark theme issues * Fixed encryption switch style * Fixed failing cases and updated a spec * Added %% for environment variables * Added code to resolve single variable * Fixed multi-variable usage * resolved an issue * removed extra divider * Suggestions will also show up for %% too * now, suggestions dropdown will only show env variables results * env vars suggestions will not be included in js search results * You can't resolve env variables from js code - Also, we can't resolve js code from env variable enclosures * added an info text * Resolved variables issue * fixed Viewer issue * Resolved a bug - client variable was not working on query preview and run actions * Update error message while using server variable on canvas * Revert "Update error message while using server variable on canvas" This reverts commit 081e1c9e295509a2db1010ddce0841c60e57387a. * Resolved all PR changes - removed prefix 'environmentVariable' - redefined variable evaluation - removed environmentVariable object from inspector - fixed a small bug * Fixed a server side issue Co-authored-by: Sherfin Shamsudeen <sherfin94@gmail.com>
2022-07-01 10:50:37 +00:00
'org_environment_variable_create',
'org_environment_variable_update',
'org_environment_variable_delete',
'folder_delete',
'folder_update',
].sort()
);
expect(app_group_permissions).toHaveLength(0);
await current_user.reload();
expect(current_user.defaultOrganizationId).toBe(invited_organization.id);
});
});
});
describe('POST /api/forgot-password', () => {
beforeEach(async () => {
await createUser(app, {
email: 'admin@tooljet.io',
firstName: 'user',
lastName: 'name',
});
});
it('should return error if required params are not present', async () => {
const response = await request(app.getHttpServer()).post('/api/forgot-password');
expect(response.statusCode).toBe(400);
expect(response.body.message).toStrictEqual(['email should not be empty', 'email must be an email']);
});
it('should set token and send email', async () => {
const emailServiceMock = jest.spyOn(EmailService.prototype, 'sendPasswordResetEmail');
emailServiceMock.mockImplementation();
const response = await request(app.getHttpServer())
.post('/api/forgot-password')
.send({ email: 'admin@tooljet.io' });
expect(response.statusCode).toBe(201);
const user = await getManager().findOne(User, {
where: { email: 'admin@tooljet.io' },
});
expect(emailServiceMock).toHaveBeenCalledWith(user.email, user.forgotPasswordToken);
});
});
describe('POST /api/reset-password', () => {
beforeEach(async () => {
await createUser(app, {
email: 'admin@tooljet.io',
firstName: 'user',
lastName: 'name',
});
});
it('should return error if required params are not present', async () => {
const response = await request(app.getHttpServer()).post('/api/reset-password');
expect(response.statusCode).toBe(400);
expect(response.body.message).toStrictEqual([
'password should not be empty',
'password must be a string',
'token should not be empty',
'token must be a string',
]);
});
it('should reset password', async () => {
const user = await getManager().findOne(User, {
where: { email: 'admin@tooljet.io' },
});
user.forgotPasswordToken = 'token';
await user.save();
const response = await request(app.getHttpServer()).post('/api/reset-password').send({
password: 'new_password',
token: 'token',
});
expect(response.statusCode).toBe(201);
await request(app.getHttpServer())
.post('/api/authenticate')
.send({ email: 'admin@tooljet.io', password: 'new_password' })
.expect(201);
});
});
describe('POST /api/set-password-from-token', () => {
beforeEach(() => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_MULTI_WORKSPACE':
return 'false';
default:
return process.env[key];
}
});
});
it('should allow users to setup account after sign up using Multi-Workspace', async () => {
const invitationToken = uuidv4();
const userData = await createUser(app, {
email: 'signup@tooljet.io',
invitationToken,
status: 'invited',
});
const { user, organization } = userData;
const response = await request(app.getHttpServer()).post('/api/set-password-from-token').send({
first_name: 'signupuser',
last_name: 'user',
organization: 'org1',
password: uuidv4(),
token: invitationToken,
role: 'developer',
});
expect(response.statusCode).toBe(201);
const updatedUser = await getManager().findOneOrFail(User, { where: { email: user.email } });
expect(updatedUser.firstName).toEqual('signupuser');
expect(updatedUser.lastName).toEqual('user');
expect(updatedUser.defaultOrganizationId).toEqual(organization.id);
const organizationUser = await getManager().findOneOrFail(OrganizationUser, { where: { userId: user.id } });
expect(organizationUser.status).toEqual('active');
});
it('should return error if required params are not present - Multi-Workspace', async () => {
const invitationToken = uuidv4();
await createUser(app, {
email: 'signup@tooljet.io',
invitationToken,
status: 'invited',
});
const response = await request(app.getHttpServer()).post('/api/set-password-from-token');
expect(response.statusCode).toBe(400);
expect(response.body.message).toStrictEqual([
'password should not be empty',
'password must be a string',
'token should not be empty',
'token must be a string',
]);
});
it('should allow users to signup for single organization only once', async () => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_MULTI_WORKSPACE':
return 'true';
default:
return process.env[key];
}
});
await request(app.getHttpServer()).post('/api/signup').send({ email: 'invited@tooljet.io' }).expect(201);
await request(app.getHttpServer()).post('/api/signup').send({ email: 'newinvited@tooljet.io' }).expect(406);
});
it('should allow users to signup - Multi-Workspace', async () => {
await request(app.getHttpServer()).post('/api/signup').send({ email: 'invited@tooljet.io' }).expect(201);
await request(app.getHttpServer()).post('/api/signup').send({ email: 'newinvited@tooljet.io' }).expect(201);
await request(app.getHttpServer()).post('/api/signup').send({ email: 'newinvited1@tooljet.io' }).expect(201);
});
Merge main to develop (#4049) * Fix: User group permissions error on Openshift platform (#4041) * update dockerfile for file permissions on root group * add permissions from the user group on dockerfile * bump to v1.24.4 * bump to v1.25.0 * [feature] Added pagination and filtering features to users page (#3921) * added pagination and filtering in backend * added pagination - created a seperate component for users table - added pagination * Added filter UI * temporary css fix for pagination footer * fixed pagination width issue * now result will also clear when user clicks on clear icon * Added seperate api for comment mentions * Now we can search mentions by email, first and last names * Fixed a bug - email didn't send for comment mentions * refactoring the code * resolved PR changes * Added isAdmin guard * adding some checks * fixed lint errors * added wild card search * Added no result found text * fixed failing test case * Working on PR changes * Now users table avatars will load image too * replaced skeleton classes with skeleton library component * Completed PR changes * added orderby * Fixed some issues * fixed failed test case * have fixed some css issues * replaced query with quersrting package * fixed minor width issue * Fixed some css issues * fixed darkMode issue * implemented on enter press search * Refactored the code * fixed white space issue * refactored the code * fixed overlapping issue * refactored the code * fixing some issues * fixes * removed guard * code cleanup * comments notification fix * fixed conflict issues * fixed css height issue Co-authored-by: gsmithun4 <gsmithun4@gmail.com> * Remove signup guard from set-password-from-token API (#4050) * Remove sign up guard set-password-from-token API * test cases fix * Bump to v1.25.1 * Feature: Add PG_DB_OWNER env var to disable db and extension creation (#4055) * add PG_DB_OWNER env var to disable db and extension creation * update docs * bump to v1.25.2 Co-authored-by: Akshay <akshaysasidharan93@gmail.com> Co-authored-by: Muhsin Shah C P <muhsinshah21@gmail.com>
2022-09-16 15:38:45 +00:00
it('should allow users to setup account for Multi-Workspace and sign up disabled', async () => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_SIGNUPS':
return 'true';
default:
return process.env[key];
}
});
const invitationToken = uuidv4();
await createUser(app, {
email: 'signup@tooljet.io',
invitationToken,
status: 'invited',
});
const response = await request(app.getHttpServer()).post('/api/set-password-from-token').send({
first_name: 'signupuser',
last_name: 'user',
organization: 'org1',
password: uuidv4(),
token: invitationToken,
role: 'developer',
});
Merge main to develop (#4049) * Fix: User group permissions error on Openshift platform (#4041) * update dockerfile for file permissions on root group * add permissions from the user group on dockerfile * bump to v1.24.4 * bump to v1.25.0 * [feature] Added pagination and filtering features to users page (#3921) * added pagination and filtering in backend * added pagination - created a seperate component for users table - added pagination * Added filter UI * temporary css fix for pagination footer * fixed pagination width issue * now result will also clear when user clicks on clear icon * Added seperate api for comment mentions * Now we can search mentions by email, first and last names * Fixed a bug - email didn't send for comment mentions * refactoring the code * resolved PR changes * Added isAdmin guard * adding some checks * fixed lint errors * added wild card search * Added no result found text * fixed failing test case * Working on PR changes * Now users table avatars will load image too * replaced skeleton classes with skeleton library component * Completed PR changes * added orderby * Fixed some issues * fixed failed test case * have fixed some css issues * replaced query with quersrting package * fixed minor width issue * Fixed some css issues * fixed darkMode issue * implemented on enter press search * Refactored the code * fixed white space issue * refactored the code * fixed overlapping issue * refactored the code * fixing some issues * fixes * removed guard * code cleanup * comments notification fix * fixed conflict issues * fixed css height issue Co-authored-by: gsmithun4 <gsmithun4@gmail.com> * Remove signup guard from set-password-from-token API (#4050) * Remove sign up guard set-password-from-token API * test cases fix * Bump to v1.25.1 * Feature: Add PG_DB_OWNER env var to disable db and extension creation (#4055) * add PG_DB_OWNER env var to disable db and extension creation * update docs * bump to v1.25.2 Co-authored-by: Akshay <akshaysasidharan93@gmail.com> Co-authored-by: Muhsin Shah C P <muhsinshah21@gmail.com>
2022-09-16 15:38:45 +00:00
expect(response.statusCode).toBe(201);
});
it('should allow users to sign up and setup account if already invited to an organization but not setup the account', async () => {
const { organization: org, user: adminUser } = await createUser(app, {
email: 'admin@tooljet.io',
});
await request(app.getHttpServer())
.post(`/api/organization_users/`)
.set('Authorization', authHeaderForUser(adminUser))
.send({ email: 'invited@tooljet.io' })
.expect(201);
const signUpResponse = await request(app.getHttpServer())
.post('/api/signup')
.send({ email: 'invited@tooljet.io' });
expect(signUpResponse.statusCode).toBe(201);
const invitedUserDetails = await getManager().findOneOrFail(User, { where: { email: 'invited@tooljet.io' } });
expect(invitedUserDetails.defaultOrganizationId).not.toBe(org.id);
const response = await request(app.getHttpServer()).post('/api/set-password-from-token').send({
first_name: 'signupuser',
last_name: 'user',
organization: 'org1',
password: uuidv4(),
token: invitedUserDetails.invitationToken,
role: 'developer',
});
expect(response.statusCode).toBe(201);
const updatedUser = await getManager().findOneOrFail(User, { where: { email: 'invited@tooljet.io' } });
expect(updatedUser.firstName).toEqual('signupuser');
expect(updatedUser.lastName).toEqual('user');
expect(updatedUser.defaultOrganizationId).not.toBe(org.id);
const organizationUser = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: Not(adminUser.id), organizationId: org.id },
});
const defaultOrganizationUser = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: Not(adminUser.id), organizationId: invitedUserDetails.defaultOrganizationId },
});
expect(organizationUser.status).toEqual('invited');
expect(defaultOrganizationUser.status).toEqual('active');
const acceptInviteResponse = await request(app.getHttpServer()).post('/api/accept-invite').send({
token: organizationUser.invitationToken,
});
expect(acceptInviteResponse.statusCode).toBe(201);
const organizationUserUpdated = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: Not(adminUser.id), organizationId: org.id },
});
expect(organizationUserUpdated.status).toEqual('active');
});
it('should allow users setup account and accept invite', async () => {
const { organization: org, user: adminUser } = await createUser(app, {
email: 'admin@tooljet.io',
});
await request(app.getHttpServer())
.post(`/api/organization_users/`)
.set('Authorization', authHeaderForUser(adminUser))
.send({ email: 'invited@tooljet.io' })
.expect(201);
const invitedUserDetails = await getManager().findOneOrFail(User, { where: { email: 'invited@tooljet.io' } });
expect(invitedUserDetails.defaultOrganizationId).not.toBe(org.id);
const organizationUserBeforeUpdate = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: Not(adminUser.id), organizationId: org.id },
});
const response = await request(app.getHttpServer()).post('/api/set-password-from-token').send({
first_name: 'signupuser',
last_name: 'user',
organization: 'org1',
password: uuidv4(),
token: invitedUserDetails.invitationToken,
organizationToken: organizationUserBeforeUpdate.invitationToken,
role: 'developer',
});
expect(response.statusCode).toBe(201);
const updatedUser = await getManager().findOneOrFail(User, { where: { email: 'invited@tooljet.io' } });
expect(updatedUser.firstName).toEqual('signupuser');
expect(updatedUser.lastName).toEqual('user');
expect(updatedUser.defaultOrganizationId).toBe(org.id);
const organizationUser = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: Not(adminUser.id), organizationId: org.id },
});
const defaultOrganizationUser = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: Not(adminUser.id), organizationId: invitedUserDetails.defaultOrganizationId },
});
expect(organizationUser.status).toEqual('active');
expect(defaultOrganizationUser.status).toEqual('active');
const acceptInviteResponse = await request(app.getHttpServer()).post('/api/accept-invite').send({
token: organizationUser.invitationToken,
});
expect(acceptInviteResponse.statusCode).toBe(400);
});
it('should not allow users to setup account if already invited to an organization and trying to accept invite before setting up account', async () => {
const { organization: org, user: adminUser } = await createUser(app, {
email: 'admin@tooljet.io',
});
await request(app.getHttpServer())
.post(`/api/organization_users/`)
.set('Authorization', authHeaderForUser(adminUser))
.send({ email: 'invited@tooljet.io' })
.expect(201);
const signUpResponse = await request(app.getHttpServer())
.post('/api/signup')
.send({ email: 'invited@tooljet.io' });
expect(signUpResponse.statusCode).toBe(201);
const invitedUserDetails = await getManager().findOneOrFail(User, { where: { email: 'invited@tooljet.io' } });
const orgUser = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: invitedUserDetails.id, organizationId: org.id },
});
expect(invitedUserDetails.defaultOrganizationId).not.toBe(org.id);
const acceptInviteResponse = await request(app.getHttpServer()).post('/api/accept-invite').send({
token: orgUser.invitationToken,
});
expect(acceptInviteResponse.statusCode).toBe(401);
const organizationUser = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: invitedUserDetails.id, organizationId: org.id },
});
const defaultOrganizationUser = await getManager().findOneOrFail(OrganizationUser, {
where: { userId: invitedUserDetails.id, organizationId: invitedUserDetails.defaultOrganizationId },
});
expect(organizationUser.status).toEqual('invited');
expect(defaultOrganizationUser.status).toEqual('invited');
const response = await request(app.getHttpServer()).post('/api/set-password-from-token').send({
first_name: 'signupuser',
last_name: 'user',
organization: 'org1',
password: uuidv4(),
token: invitedUserDetails.invitationToken,
role: 'developer',
});
expect(response.statusCode).toBe(201);
});
});
describe('POST /api/accept-invite', () => {
describe('Multi-Workspace Enabled', () => {
beforeEach(() => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_MULTI_WORKSPACE':
return 'false';
default:
return process.env[key];
}
});
});
it('should allow users to accept invitation when Multi-Workspace is enabled', async () => {
const userData = await createUser(app, {
email: 'organizationUser@tooljet.io',
status: 'invited',
});
const { user, orgUser } = userData;
const response = await request(app.getHttpServer()).post('/api/accept-invite').send({
token: orgUser.invitationToken,
});
expect(response.statusCode).toBe(201);
const organizationUser = await getManager().findOneOrFail(OrganizationUser, { where: { userId: user.id } });
expect(organizationUser.status).toEqual('active');
});
it('should not allow users to accept invitation when user sign up is not completed', async () => {
const userData = await createUser(app, {
email: 'organizationUser@tooljet.io',
invitationToken: uuidv4(),
status: 'invited',
});
const { user, orgUser } = userData;
const response = await request(app.getHttpServer()).post('/api/accept-invite').send({
token: orgUser.invitationToken,
});
expect(response.statusCode).toBe(401);
expect(response.body.message).toBe(
'Please setup your account using account setup link shared via email before accepting the invite'
);
});
});
describe('Multi-Workspace Disabled', () => {
beforeEach(() => {
jest.spyOn(mockConfig, 'get').mockImplementation((key: string) => {
switch (key) {
case 'DISABLE_MULTI_WORKSPACE':
return 'true';
default:
return process.env[key];
}
});
});
it('should allow users to accept invitation when Multi-Workspace is disabled', async () => {
const userData = await createUser(app, {
email: 'organizationUser@tooljet.io',
status: 'invited',
});
const { user, orgUser } = userData;
const response = await request(app.getHttpServer()).post('/api/accept-invite').send({
token: orgUser.invitationToken,
password: uuidv4(),
});
expect(response.statusCode).toBe(201);
const organizationUser = await getManager().findOneOrFail(OrganizationUser, { where: { userId: user.id } });
expect(organizationUser.status).toEqual('active');
});
it('should not allow users to accept invitation when user not entered password for single workspace', async () => {
const userData = await createUser(app, {
email: 'organizationUser@tooljet.io',
invitationToken: uuidv4(),
status: 'invited',
});
const { orgUser } = userData;
const response = await request(app.getHttpServer()).post('/api/accept-invite').send({
token: orgUser.invitationToken,
});
expect(response.statusCode).toBe(400);
expect(response.body.message).toBe('Please enter password');
});
});
});
2021-07-08 16:43:23 +00:00
afterAll(async () => {
await app.close();
2021-07-08 05:40:27 +00:00
});
});