Skip to content

Commit

Permalink
Merge/v1.25.4 (#42)
Browse files Browse the repository at this point in the history
* [docs] Provide border to the images (#3853)

* replaced class with classname to provide image border

* removed unnecessary div, added alt attribute in image tags

Co-authored-by: Shivang Tiwari <shivangtiwari@Shivangs-MacBook-Pro.local>

* Cypress test for button widget happy path (#3776)

* Add and modify data-cy attribute for elements

* Modify faker file for random rgba hex code

* Add methods specific for button widget

* Add and modify common selector and text file

* Add and modify common widget methods

* Modify button text file

* Modify button widget happy path file

* Remove button selector file

* Modify multiselect widget happy with new methods

* Modify verify box shadow css method

* Add and modify common selector file

* Modify button text file

* add and modify specific methods for button widget

* Add and modify custom commands

* Add and modify common widget methods

* Add app preview and modify button widget happy path

* Add and modify data-cy attribute for elements

* Modify multiselect widget happy with new methods

* Modify data-cy attributes

* Add review changes

* Add data-cy attribute

* Add review changes

Co-authored-by: arpitnath <arpitnath42@gmail.com>

* refactor: update sentry sdk + add profiler (#3938)

* refactor: remove @babel/plugin-proposal-class-properties (2nd PR after CLA problem) (#3959)

* refactor: remove @babel/plugin-proposal-class-properties as plugin

* Remove class properties plugin from babel.config.js, Update frontend package.json, Update frontend,server,plugin package.lock.json

* [docs] how to - Bulk update multiple rows in table (#3864)

* [ Bugfix ] :: calendar preview is broken when events are added as a result of any query (#3928)

* fix :: checking type of events  to assign empty array initially

* cleanup

* checking array

* [docs] renamed filenames to correct redirection links from the editor (#3974)

Co-authored-by: Shivang Tiwari <shivangtiwari@Shivangs-MacBook-Pro.local>

* [docs] how-to: access currentUser properties (#3977)

* how to user and group

* hot-to/access current user props

* [Plugins] Add support for self-hosted Baserow (#3969)

* Add support for self-hosted baserow

* docs:updated

* Make tooltip text for hide query visible (#3918)

* [feature] Hide apps in dashboard (#3888)

* - Added new field under app view permission
- Added new column to appGroupPermission

* added queries for hiding app from dashboard

* changed a column name

* Create query panel component (#3966)

* refactor: create query panel component

* prop typo fix

* [docs] setting up on a subpath (#3984)

* [docs] added image for query body details (#3988)

Co-authored-by: Shivang Tiwari <shivangtiwari@Shivangs-MacBook-Pro.local>

* [docs] created missing svg image doc (#3985)

Co-authored-by: Shivang Tiwari <shivangtiwari@Shivangs-MacBook-Pro.local>

* Bug fixed : canvas background colour is not consistent with the applied theme (#3956)

* Bug fixed : canvas background colour is not consistent with the applied theme

* bug fixed : canvas color is not consistent in the Viewer mode

* reverting back changes made earlier

* reverting back changes made earlier

* bug fixed : canvas background in editor is not consistent with the applied theme

* Bug fixed : Viewer component is not consistent with the applied theme

* [docs] updated new video link (#3998)

Co-authored-by: Shivang Tiwari <shivangtiwari@Shivangs-MacBook-Pro.local>

* bug fixed : Password Input widget is not consistent with the dark theme (#3992)

* Bug fixed : radio button is not consistent with the dark theme (#3929)

* Bug fixed : Button Group widget is not consistent with the dark theme (#3950)

* Fix test in Listview (#4012)

* Bug fixed : Pagination widget is not consistent with the dark theme (#3946)

* bug fixed : Pagination widget is not consistent with the dark theme

* removed console.log

* Bug fixed : Tree Select widget is not consistent with the dark theme (#3948)

* Bug fixed : Tree Select widget is not consistent with the dark theme

* only setting up condition for #000

* removed includes function

* [Bugfix] fixes app freeze, when password widget drops inside a listview (#4018)

* fixes app freeze, when password widget drops inside a listview

* fix:darkmode

* bug fixed : toggle switch is not consistent with the dark theme (#3925)

* bug fixed : Text input widget is not consistent with the dark theme (#3990)

* Bug fixed : dark theme issues (#4009)

* bug fixed : file picker is not consistent with the dark theme

* bug fixed : Map widget is not consistent with the dark theme

* bug fixed : Steps widget is not consistent with the dark theme

* bug fixed : Multi select widget label is not consistent with the dark theme

* bug fixed : search bar in widget manager and label params in Code Hinter is not consistent with the dark theme

* removed unwanted comma in the chart inspector

* bug fix : app dropdown inside go to app in event manager is not consistent with the dark theme

* bug fixed : search select dropdown is not consistent with the dark theme in table inspector

* bug fixed : Organization and Profile avatar in HomePage is not consistent with the dark theme

* bug fixed : search box in the homepage is not consistent with the dark theme

* bug fixed : select dropdown input placeholder is not consistent with the dark theme

* bug fixed :Text area in the Modal to  Share the app link is not consistent with the dark theme

* bug fixed : p tag in pagination in the homepage is not consistent with the dark theme

* replaced undefined to false as default value of darkMode if not defined

* bug fixed : multiselect input placeholder is not consistent with the dark theme

* removed duplicate code from custom.scss and changed rgb to hex in theme.scss

* Bug fix : Container widget background color is not consistent with the dark theme (#3866)

* Bug fix : Container widget background color is not consistent with the dark theme

* replaced two condition checks with one

* made the suggested changes

* removed console.log

* [Feature]: Added Localisation (#3746)

* Added localisation

* Closed modal after language selection

* updated transaltaion setup

* Updated language tooltip

* Added fallback language support

* Adding english library resource for translation (#3844)

* Adding English dictionary for the widget lists in the inspector

* added leftSideBar object in en.json and implemented it for leftSidebar icon text

* renamed leftSideBar to leftSidebar and added resources for tip in the left side bar

* added english translation resources for leftsidebar debugger

* added english language resources for the global settings

* added english language resources for data sources in left sidebar

* added english language resources for the share button and share modal in the editor

* added english language resources for release button, manageOrgUsers, appVersionManager

* added english language resources for Queries and Please select a widget to inspect in the editor

* added english language resources for data source list , data source manager, and query manager(partially)

* added english language resources for queryManager, transformation, preview

* added english language resources for dark mode toggle in the headers inside homepage

* added fallback message for dark mode toggle

* added resources for language change in the headers inside homepage

* added resources for notification center in the header inside homepage

* added resources for organization and manage users components in header inside homepage

* added resources in manageGroupPermission

* added resources for manageGroupPermissionsResources component

* added resources for manageSSO and generalSettings components

* added resources for google sso

* added resources for github sso

* added resources for environment variables in manageSSO

* added resources for profile and setting page

* added resources for app card and app card menu

* added resources for folder section and app list in homepage

* added resources for header section in the homepage

* added resources for pagination in homepage

* added resources for modals in the homepage

* added resources for blank page

* added resources for login page

* added resources for forgot password page

* added resources for sign up page

* added resources for onBoarding component

* added resources for reset password page

* deleted duplicate key for readDocumentation

* deleted duplicate key for cancel in en.json and added translation for cancel at few places

* removing duplicate copy of save key in en.json

* added translation for CommentActions.jsx components

* deleted duplicate copy of search key in en.json and added resources for create and search queries , select keys

* fix typo errors

* fixed typo errors

* shorten the key for loginAndSignUpAndForgotPassword to loginSignupPage in en.json file and related files

* shorten the key noLoginMethodsEnabledForThisWorkspace to noLoginMethodsEnabled

* shorten the key pleaseCheckYourEmailForConfirmationLink to emailConfirmLink

* shorten the key dontHaveAccountYet to dontHaveAccount

* shorten keys from loginSignupPage key in en.json

* shorten keys of shareModal nested object in en.json

* shorten the key in appVersionManager nested object

* shorten the keys for queryManager nested object in the en.json

* delete duplicate copy of environmentVar and shorten manageEnvironmentVariables,environmentVariables

* shorten keys in the organization nested object

* shorten keys in the homePage nested object in en.json file

* added inspector and eventManager empty object

* added resources to RedirectSSO component

* added resources for OAuth2

* added resources for TemplateCard.jsx

* added resources for TemplateLibraryModal.jsx

* added resources for ConfirmationPage.jsx

* added resources for ConfirmationPage component

* removed translation in App.jsx file

* added resources for Slack.jsx

* added resources for GoogleSheets.jsx

* added resources for CodeBuilder.jsx

* added resources for CommentBody and CommentFooter

* added resources for TestConnection component

* added resources for AllignButton.jsx

* added resources for Openapi and Stripe components

* added resources for ErrorBoundary

* added resources for Viewer.jsx

* Translation for widgets, table

Co-authored-by: Kavin Venkatachalam <kavin.saratha@gmail.com>

* Commented Language selection

* Fixed typos

* Updated fr.json file

Co-authored-by: Manish Kushare <kushare.manish9@gmail.com>

* Bug fixed : List view widget background color is not consistent with the dark theme (#3867)

* Bug fixed : list view widget background color is not consistent with the dark theme

* replaced two condition check with one

* Fixed : If we pick white (#FFFFFF) then the dark mode is not handled.

* Add preview for Multiselect and Datepicker happyPaths (#3854)

* Modify data-cy and update spec

* Add data-cy

* Add preview for multiSelect

* Add preview for datePicker

* Fix Text data-cy

* Modify selectors and texts

* Resolve conflicts and commented few lines of code.

* 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

* hotfix: handle pg env vars from env and env file

* bump to v1.25.3

* [Feature] Now multiple users can login through RestAPI-Oauth 🚀  (#4052)

* Implemented multiple access token feature
- working on refresh token case

* worked on refresh token flow

* added multiple token ability to openapi plugin too
- fixed some bugs

* changed tokenData to token_data
- fixed some issues

* added user type with user id

* changed user type

* Rewrote some function
- added switch for enabling and disable multi auth
- fixed some bugs
- refactored the code

* fixed view app issue

* Fixed public app issue

* cleaning some code

* (public_app) add a check to avoid oauth login redirect when there is no access token

* reverted all changes of openapi (temporary)
- will add multi token functionality once done with restapi

* fixed a bug

* fixed a bug

* refactored some code

* changed the switch text

* pr changes

* changed token_data back to tokenData

* cleaning code

* removed token data from datasources query

* removed some lines

* added a comment

* bump to v1.25.4

* audit logs fix

Co-authored-by: Shivang <32157641+shivangT@users.noreply.github.com>
Co-authored-by: Shivang Tiwari <shivangtiwari@Shivangs-MacBook-Pro.local>
Co-authored-by: Ajith KV <ajith.jaban@gmail.com>
Co-authored-by: arpitnath <arpitnath42@gmail.com>
Co-authored-by: Gandharv <gandharvkumargarg@gmail.com>
Co-authored-by: Akshay Sasidharan <akshaysasidharan93@gmail.com>
Co-authored-by: Erfan Naghashlou <62594996+erfan93na@users.noreply.github.com>
Co-authored-by: Kiran Ashok <stepinfwd@gmail.com>
Co-authored-by: Shubhendra Singh Chauhan <withshubh@gmail.com>
Co-authored-by: Roei Yaacobi <roeiyaacobi@gmail.com>
Co-authored-by: Muhsin Shah C P <muhsinshah21@gmail.com>
Co-authored-by: Sherfin Shamsudeen <sherfin94@gmail.com>
Co-authored-by: Manish Kushare <kushare.manish9@gmail.com>
Co-authored-by: mikebarr24 <89523154+mikebarr24@users.noreply.github.com>
Co-authored-by: Kavin Venkatachalam <50441969+kavinvenkatachalam@users.noreply.github.com>
Co-authored-by: Midhun Kumar E <midhun752@gmail.com>
  • Loading branch information
17 people authored Sep 19, 2022
1 parent 3ca23d7 commit 6c14ede
Show file tree
Hide file tree
Showing 21 changed files with 219 additions and 58 deletions.
2 changes: 1 addition & 1 deletion .version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.25.1-ee1.5.1
1.25.4-ee1.5.1
4 changes: 4 additions & 0 deletions docs/docs/setup/env-vars.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ ToolJet server uses PostgreSQL as the database.
If you are using docker-compose setup, you can set PG_HOST as `postgres` which will be DNS resolved by docker
:::

### Disable database and extension creation (optional)

ToolJet by default tries to create database based on `PG_DB` variable set and additionally my try to create postgres extensions. This requires the postgres user to have CREATEDB permission. If this cannot be granted you can disable this behaviour by setting `PG_DB_OWNER` as `false` and will have to manually run them.

#### Redis configuration ( optional )

ToolJet server uses Redis as a message broker. This is currently being used only for realtime multiplayer edit feature.
Expand Down
1 change: 1 addition & 0 deletions frontend/src/_components/DynamicForm.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ const DynamicForm = ({
auth_key: options.auth_key?.value,
custom_auth_params: options.custom_auth_params?.value,
custom_query_params: options.custom_query_params?.value,
multiple_auth_enabled: options.multiple_auth_enabled?.value,
optionchanged,
};
case 'react-component-google-sheets':
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/_helpers/appUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ export function runQuery(_ref, queryId, queryName, confirmed = undefined, mode =
.then((data) => {
if (data.status === 'needs_oauth') {
const url = data.data.auth_url; // Backend generates and return sthe auth url
fetchOAuthToken(url, dataQuery.data_source_id);
fetchOAuthToken(url, dataQuery['data_source_id'] || dataQuery['dataSourceId']);
}

if (data.status === 'failed') {
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/_ui/OAuth/Authentication.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const Authentication = ({
bearer_token,
password,
auth_url,
multiple_auth_enabled,
optionchanged,
}) => {
if (auth_type === 'oauth2') {
Expand Down Expand Up @@ -153,6 +154,15 @@ const Authentication = ({
width={'100%'}
useMenuPortal={false}
/>
<label className="form-check form-switch my-4 ">
<input
className="form-check-input"
type="checkbox"
checked={multiple_auth_enabled}
onChange={() => optionchanged('multiple_auth_enabled', !multiple_auth_enabled)}
/>
<span className="form-check-label">Authentication Required for All Users</span>
</label>
</div>
)}
</div>
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/_ui/OAuth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const OAuth = ({
auth_url,
header_prefix,
add_token_to,
multiple_auth_enabled,
optionchanged,
}) => {
return (
Expand Down Expand Up @@ -48,6 +49,7 @@ const OAuth = ({
client_id={client_id}
client_secret={client_secret}
client_auth={client_auth}
multiple_auth_enabled={multiple_auth_enabled}
scopes={scopes}
username={username}
password={password}
Expand Down
4 changes: 4 additions & 0 deletions plugins/packages/common/lib/app.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type App = {
id: string;
isPublic: boolean;
};
7 changes: 6 additions & 1 deletion plugins/packages/common/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import { QueryError, OAuthUnauthorizedClientError } from './query.error';
import { QueryResult } from './query_result.type';
import { User } from './user.type';
import { App } from './app.type';
import { QueryService } from './query_service.interface';
import { cacheConnection, getCachedConnection, parseJson, cleanSensitiveData } from './utils.helper';
import { cacheConnection, getCachedConnection, parseJson, cleanSensitiveData, getCurrentToken } from './utils.helper';
import { ConnectionTestResult } from './connection_test_result.type';

export {
QueryError,
OAuthUnauthorizedClientError,
QueryResult,
QueryService,
User,
App,
cacheConnection,
getCachedConnection,
parseJson,
ConnectionTestResult,
cleanSensitiveData,
getCurrentToken,
};
6 changes: 4 additions & 2 deletions plugins/packages/common/lib/query_service.interface.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { App } from './app.type';
import { ConnectionTestResult } from './connection_test_result.type';
import { QueryResult } from './query_result.type';

import { User } from './user.type';
export interface QueryService {
run(
sourceOptions: object,
queryOptions: object,
dataSourceId?: string,
dataSourceUpdatedAt?: string
dataSourceUpdatedAt?: string,
context?: { user?: User; app?: App }
): Promise<QueryResult>;
getConnection?(queryOptions: object, options: any, checkCache: boolean, dataSourceId: string): Promise<object>;
testConnection?(sourceOptions: object): Promise<ConnectionTestResult>;
Expand Down
3 changes: 3 additions & 0 deletions plugins/packages/common/lib/user.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type User = {
id: string;
};
13 changes: 13 additions & 0 deletions plugins/packages/common/lib/utils.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,16 @@ function clearData(data, keys) {
}
}
}

export const getCurrentToken = (isMultiAuthEnabled: boolean, tokenData: any, userId: string, isAppPublic: boolean) => {
if (isMultiAuthEnabled) {
if (!tokenData || !Array.isArray(tokenData)) return null;
return !isAppPublic
? tokenData.find((token: any) => token.user_id === userId)
: userId
? tokenData.find((token: any) => token.user_id === userId)
: tokenData[0];
} else {
return tokenData;
}
};
36 changes: 30 additions & 6 deletions plugins/packages/restapi/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
const urrl = require('url');
import { readFileSync } from 'fs';
import * as tls from 'tls';
import { QueryError, QueryResult, QueryService, cleanSensitiveData } from '@tooljet-plugins/common';
import {
QueryError,
QueryResult,
QueryService,
cleanSensitiveData,
User,
App,
getCurrentToken,
} from '@tooljet-plugins/common';
const JSON5 = require('json5');
import got, { Headers, HTTPError, OptionsOfTextResponseBody } from 'got';

Expand Down Expand Up @@ -85,7 +93,13 @@ export default class RestapiQueryService implements QueryService {
return true;
}

async run(sourceOptions: any, queryOptions: any, dataSourceId: string): Promise<RestAPIResult> {
async run(
sourceOptions: any,
queryOptions: any,
dataSourceId: string,
dataSourceUpdatedAt: string,
context?: { user?: User; app?: App }
): Promise<RestAPIResult> {
/* REST API queries can be adhoc or associated with a REST API datasource */
const hasDataSource = dataSourceId !== undefined;
const authType = sourceOptions['auth_type'];
Expand All @@ -94,12 +108,20 @@ export default class RestapiQueryService implements QueryService {
const headers = this.headers(sourceOptions, queryOptions, hasDataSource);
const customQueryParams = sanitizeCustomParams(sourceOptions['custom_query_params']);
const isUrlEncoded = this.checkIfContentTypeIsURLenc(queryOptions['headers']);
const isMultiAuthEnabled = sourceOptions['multiple_auth_enabled'];

/* Chceck if OAuth tokens exists for the source if query requires OAuth */
if (requiresOauth) {
const tokenData = sourceOptions['tokenData'];
const isAppPublic = context?.app.isPublic;
const userData = context?.user;
const currentToken = getCurrentToken(isMultiAuthEnabled, tokenData, userData?.id, isAppPublic);

if (!tokenData) {
if (!currentToken && !userData?.id && isAppPublic) {
throw new QueryError('Missing access token', {}, {});
}

if (!currentToken) {
const tooljetHost = process.env.TOOLJET_HOST;
const authUrl = new URL(
`${sourceOptions['auth_url']}?response_type=code&client_id=${sourceOptions['client_id']}&redirect_uri=${tooljetHost}/oauth2/authorize&scope=${sourceOptions['scopes']}`
Expand All @@ -111,7 +133,7 @@ export default class RestapiQueryService implements QueryService {
data: { auth_url: authUrl },
};
} else {
const accessToken = tokenData['access_token'];
const accessToken = currentToken['access_token'];
if (sourceOptions['add_token_to'] === 'header') {
const headerPrefix = sourceOptions['header_prefix'];
headers['Authorization'] = `${headerPrefix}${accessToken}`;
Expand Down Expand Up @@ -214,8 +236,10 @@ export default class RestapiQueryService implements QueryService {
return contentType === 'application/x-www-form-urlencoded';
}

async refreshToken(sourceOptions, error) {
const refreshToken = sourceOptions['tokenData']['refresh_token'];
async refreshToken(sourceOptions: any, error: any, userId: string, isAppPublic: boolean) {
const isMultiAuthEnabled = sourceOptions['multiple_auth_enabled'];
const currentToken = getCurrentToken(isMultiAuthEnabled, sourceOptions['tokenData'], userId, isAppPublic);
const refreshToken = currentToken['refresh_token'];
if (!refreshToken) {
throw new QueryError('Refresh token not found', error.response, {});
}
Expand Down
37 changes: 9 additions & 28 deletions plugins/packages/restapi/lib/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"password": {
"encrypted": true
},
"bearer_token":{
"bearer_token": {
"encrypted": true
},
"scopes": {
Expand Down Expand Up @@ -105,36 +105,19 @@
"value": "header"
},
"headers": {
"value": [
[
"",
""
]
]
"value": [["", ""]]
},
"custom_query_params": {
"value": [
[
"",
""
]
]
"value": [["", ""]]
},
"custom_auth_params": {
"value": [
[
"",
""
]
]
"value": [["", ""]]
},
"access_token_custom_headers": {
"value": [
[
"",
""
]
]
"value": [["", ""]]
},
"multiple_auth_enabled": {
"value": false
}
},
"properties": {
Expand All @@ -157,7 +140,5 @@
"description": "key-value pair headers for rest api"
}
},
"required": [
"url"
]
"required": ["url"]
}
2 changes: 1 addition & 1 deletion server/.version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.25.1-ee1.5.1
1.25.4-ee1.5.1
20 changes: 14 additions & 6 deletions server/migrations/1625814801415-MaybeCreateExtension.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";

export class MaybeCreateExtension1625814801415 implements MigrationInterface {
import { MigrationInterface, QueryRunner } from 'typeorm';
import * as fs from 'fs';
import * as dotenv from 'dotenv';
import { filePathForEnvVars } from '../scripts/database-config-utils';

export class MaybeCreateExtension1625814801415 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('CREATE EXTENSION IF NOT EXISTS pgcrypto;')
}
let data: any = process.env;
const envVarsFilePath = filePathForEnvVars(process.env.NODE_ENV);

public async down(queryRunner: QueryRunner): Promise<void> {
if (fs.existsSync(envVarsFilePath)) {
data = { ...data, ...dotenv.parse(fs.readFileSync(envVarsFilePath)) };
}
if (data.PG_DB_OWNER !== 'false') {
await queryRunner.query('CREATE EXTENSION IF NOT EXISTS pgcrypto;');
}
}

public async down(queryRunner: QueryRunner): Promise<void> {}
}
5 changes: 5 additions & 0 deletions server/scripts/create-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ function createDatabase(): void {
}
});

if (envVars.PG_DB_OWNER === 'false') {
console.log('Skipping database creation');
return;
}

const createdb =
`PGPASSWORD=${envVars.PG_PASS} createdb ` +
`-h ${envVars.PG_HOST} ` +
Expand Down
11 changes: 11 additions & 0 deletions server/scripts/database-config-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import * as Joi from 'joi';
import * as path from 'path';

export function filePathForEnvVars(env: string | undefined): string {
if (env === 'test') {
return path.resolve(process.cwd(), '../.env.test');
} else {
return path.resolve(process.cwd(), '../.env');
}
}

function buildDatabaseConfig(): any {
return {
Expand All @@ -7,6 +16,7 @@ function buildDatabaseConfig(): any {
PG_PASS: process.env.PG_PASS,
PG_USER: process.env.PG_USER,
PG_DB: process.env.PG_DB,
PG_DB_OWNER: process.env.PG_DB_OWNER,
};
}

Expand All @@ -18,6 +28,7 @@ function validateDatabaseConfig(dbOptions: any): Joi.ValidationResult {
PG_PASS: Joi.string().default(''),
PG_USER: Joi.string().required(),
PG_DB: Joi.string().default('tooljet_db'),
PG_DB_OWNER: Joi.string().default('true'),
})
.unknown();

Expand Down
2 changes: 1 addition & 1 deletion server/src/controllers/data_sources.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,6 @@ export class DataSourcesController {
throw new ForbiddenException('you do not have permissions to perform this action');
}

return await this.dataQueriesService.authorizeOauth2(dataSource, code);
return await this.dataQueriesService.authorizeOauth2(dataSource, code, user.id);
}
}
2 changes: 2 additions & 0 deletions server/src/modules/auth/query-auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export class QueryAuthGuard extends AuthGuard('jwt') {
const dataQuery = await this.dataQueriesService.findOne(request.params.id);
const app = dataQuery.app;

if (app.isPublic === true && request.headers['authorization']) return super.canActivate(context);

if (app.isPublic === true) {
return true;
}
Expand Down
Loading

0 comments on commit 6c14ede

Please sign in to comment.