From 830f1273430f02b146f6b6ab1ccb969a3c8d90ef Mon Sep 17 00:00:00 2001 From: Dean Date: Tue, 14 Jun 2022 10:14:05 +0100 Subject: [PATCH 01/21] Context binding for authenticated user in REST API querys. Includes fix for REST datasource UI --- .../builder/src/builderStore/dataBinding.js | 37 +++++++++- .../rest/RestExtraConfigForm.svelte | 24 +++++- .../integration/QueryBindingBuilder.svelte | 3 +- .../[selectedDatasource]/_layout.svelte | 4 +- .../rest/[query]/index.svelte | 73 ++++++++++++++++--- .../server/src/api/controllers/query/index.ts | 3 + packages/server/src/threads/query.js | 20 ++++- 7 files changed, 147 insertions(+), 17 deletions(-) diff --git a/packages/builder/src/builderStore/dataBinding.js b/packages/builder/src/builderStore/dataBinding.js index 8cbc62929..cddb061e2 100644 --- a/packages/builder/src/builderStore/dataBinding.js +++ b/packages/builder/src/builderStore/dataBinding.js @@ -49,6 +49,42 @@ export const getBindableProperties = (asset, componentId) => { ] } +/** + * Gets all rest bindable data fields + */ +export const getRestBindings = () => { + const userBindings = getUserBindings() + return [...userBindings] +} + +/** + * Utility - coverting a map of readable bindings to runtime + */ +export const readableToRuntimeMap = (bindings, ctx) => { + if (!bindings || !ctx) { + return {} + } + return Object.keys(ctx).reduce((acc, key) => { + let parsedQuery = readableToRuntimeBinding(bindings, ctx[key]) + acc[key] = parsedQuery + return acc + }, {}) +} + +/** + * Utility - coverting a map of runtime bindings to readable + */ +export const runtimeToReadableMap = (bindings, ctx) => { + if (!bindings || !ctx) { + return {} + } + return Object.keys(ctx).reduce((acc, key) => { + let parsedQuery = runtimeToReadableBinding(bindings, ctx[key]) + acc[key] = parsedQuery + return acc + }, {}) +} + /** * Gets the bindable properties exposed by a certain component. */ @@ -298,7 +334,6 @@ const getUserBindings = () => { providerId: "user", }) }) - return bindings } diff --git a/packages/builder/src/components/backend/DatasourceNavigator/TableIntegrationMenu/rest/RestExtraConfigForm.svelte b/packages/builder/src/components/backend/DatasourceNavigator/TableIntegrationMenu/rest/RestExtraConfigForm.svelte index 2c8b69984..e049e0cbd 100644 --- a/packages/builder/src/components/backend/DatasourceNavigator/TableIntegrationMenu/rest/RestExtraConfigForm.svelte +++ b/packages/builder/src/components/backend/DatasourceNavigator/TableIntegrationMenu/rest/RestExtraConfigForm.svelte @@ -10,11 +10,31 @@ import KeyValueBuilder from "components/integration/KeyValueBuilder.svelte" import RestAuthenticationBuilder from "./auth/RestAuthenticationBuilder.svelte" import ViewDynamicVariables from "./variables/ViewDynamicVariables.svelte" + import { + getRestBindings, + readableToRuntimeBinding, + runtimeToReadableMap, + } from "builderStore/dataBinding" + import { cloneDeep } from "lodash/fp" export let datasource export let queries let addHeader + + let parsedHeaders = runtimeToReadableMap( + getRestBindings(), + cloneDeep(datasource?.config?.defaultHeaders) + ) + + const onDefaultHeaderUpdate = headers => { + const flatHeaders = cloneDeep(headers).reduce((acc, entry) => { + acc[entry.name] = readableToRuntimeBinding(getRestBindings(), entry.value) + return acc + }, {}) + + datasource.config.defaultHeaders = flatHeaders + } @@ -30,8 +50,8 @@ onDefaultHeaderUpdate(evt.detail)} noAddButton />
diff --git a/packages/builder/src/components/integration/QueryBindingBuilder.svelte b/packages/builder/src/components/integration/QueryBindingBuilder.svelte index 9bcf9d36f..7f6bd5ffd 100644 --- a/packages/builder/src/components/integration/QueryBindingBuilder.svelte +++ b/packages/builder/src/components/integration/QueryBindingBuilder.svelte @@ -57,7 +57,8 @@ placeholder="Default" thin disabled={bindable} - bind:value={binding.default} + on:change={evt => onBindingChange(binding.name, evt.detail)} + value={runtimeToReadableBinding(bindings, binding.default)} /> {#if bindable} - +{#key $params.selectedDatasource} + +{/key} diff --git a/packages/builder/src/pages/builder/app/[application]/data/datasource/[selectedDatasource]/rest/[query]/index.svelte b/packages/builder/src/pages/builder/app/[application]/data/datasource/[selectedDatasource]/rest/[query]/index.svelte index 2baa6aab4..ab01d4224 100644 --- a/packages/builder/src/pages/builder/app/[application]/data/datasource/[selectedDatasource]/rest/[query]/index.svelte +++ b/packages/builder/src/pages/builder/app/[application]/data/datasource/[selectedDatasource]/rest/[query]/index.svelte @@ -40,13 +40,22 @@ import { cloneDeep } from "lodash/fp" import { RawRestBodyTypes } from "constants/backend" + import { + getRestBindings, + readableToRuntimeBinding, + runtimeToReadableBinding, + runtimeToReadableMap, + readableToRuntimeMap, + } from "builderStore/dataBinding" + let query, datasource let breakQs = {}, - bindings = {} + requestBindings = {} let saveId, url let response, schema, enabledHeaders let authConfigId let dynamicVariables, addVariableModal, varBinding + let restBindings = getRestBindings() $: datasourceType = datasource?.source $: integrationInfo = $integrations[datasourceType] @@ -63,8 +72,10 @@ Object.keys(schema || {}).length !== 0 || Object.keys(query?.schema || {}).length !== 0 + $: runtimeUrlQueries = readableToRuntimeMap(restBindings, breakQs) + function getSelectedQuery() { - return cloneDeep( + const cloneQuery = cloneDeep( $queries.list.find(q => q._id === $queries.selected) || { datasourceId: $params.selectedDatasource, parameters: [], @@ -76,6 +87,30 @@ queryVerb: "read", } ) + + if (cloneQuery?.fields?.headers) { + cloneQuery.fields.headers = runtimeToReadableMap( + restBindings, + cloneQuery.fields.headers + ) + } + + if (cloneQuery?.fields?.requestBody) { + cloneQuery.fields.requestBody = runtimeToReadableBinding( + restBindings, + cloneQuery.fields.requestBody + ) + } + + if (cloneQuery?.parameters) { + const flatParams = restUtils.queryParametersToKeyValue( + cloneQuery.parameters + ) + const updatedParams = runtimeToReadableMap(restBindings, flatParams) + cloneQuery.parameters = restUtils.keyValueToQueryParameters(updatedParams) + } + + return cloneQuery } function checkQueryName(inputUrl = null) { @@ -89,7 +124,9 @@ if (!base) { return base } - const qs = restUtils.buildQueryString(qsObj) + const qs = restUtils.buildQueryString( + runtimeToReadableMap(restBindings, qsObj) + ) let newUrl = base if (base.includes("?")) { newUrl = base.split("?")[0] @@ -98,14 +135,30 @@ } function buildQuery() { - const newQuery = { ...query } - const queryString = restUtils.buildQueryString(breakQs) + const newQuery = cloneDeep(query) + const queryString = restUtils.buildQueryString(runtimeUrlQueries) + newQuery.fields.headers = readableToRuntimeMap( + restBindings, + newQuery.fields.headers + ) + newQuery.fields.requestBody = readableToRuntimeBinding( + restBindings, + newQuery.fields.requestBody + ) newQuery.fields.path = url.split("?")[0] newQuery.fields.queryString = queryString newQuery.fields.authConfigId = authConfigId newQuery.fields.disabledHeaders = restUtils.flipHeaderState(enabledHeaders) newQuery.schema = restUtils.fieldsToSchema(schema) - newQuery.parameters = restUtils.keyValueToQueryParameters(bindings) + + const parsedRequestBindings = readableToRuntimeMap( + restBindings, + requestBindings + ) + newQuery.parameters = restUtils.keyValueToQueryParameters( + parsedRequestBindings + ) + return newQuery } @@ -127,7 +180,7 @@ async function runQuery() { try { - response = await queries.preview(buildQuery(query)) + response = await queries.preview(buildQuery()) if (response.rows.length === 0) { notifications.info("Request did not return any data") } else { @@ -250,6 +303,8 @@ const datasourceUrl = datasource?.config.url const qs = query?.fields.queryString breakQs = restUtils.breakQueryString(qs) + breakQs = runtimeToReadableMap(restBindings, breakQs) + const path = query.fields.path if ( datasourceUrl && @@ -260,7 +315,7 @@ } url = buildUrl(query.fields.path, breakQs) schema = restUtils.schemaToFields(query.schema) - bindings = restUtils.queryParametersToKeyValue(query.parameters) + requestBindings = restUtils.queryParametersToKeyValue(query.parameters) authConfigId = getAuthConfigId() if (!query.fields.disabledHeaders) { query.fields.disabledHeaders = {} @@ -344,7 +399,7 @@ Date: Wed, 15 Jun 2022 10:09:47 +0100 Subject: [PATCH 02/21] Fix to ignore global rest query headers when they are not configured. --- packages/server/src/integrations/queries/sql.ts | 4 +++- packages/server/src/threads/query.js | 10 ++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/server/src/integrations/queries/sql.ts b/packages/server/src/integrations/queries/sql.ts index cf71f2ee2..271a414d4 100644 --- a/packages/server/src/integrations/queries/sql.ts +++ b/packages/server/src/integrations/queries/sql.ts @@ -9,7 +9,9 @@ export function enrichQueryFields( parameters = {} ) { const enrichedQuery: { [key: string]: any } = Array.isArray(fields) ? [] : {} - + if (!fields || !parameters) { + return enrichedQuery + } // enrich the fields with dynamic parameters for (let key of Object.keys(fields)) { if (fields[key] == null) { diff --git a/packages/server/src/threads/query.js b/packages/server/src/threads/query.js index b6454e758..36f73b154 100644 --- a/packages/server/src/threads/query.js +++ b/packages/server/src/threads/query.js @@ -47,10 +47,12 @@ class QueryRunner { const enrichedContext = { ...enrichedParameters, ...this.ctx } // Parse global headers - datasource.config.defaultHeaders = enrichQueryFields( - datasource.config.defaultHeaders, - enrichedContext - ) + if (datasource.config.defaultHeaders) { + datasource.config.defaultHeaders = enrichQueryFields( + datasource.config.defaultHeaders, + enrichedContext + ) + } let query // handle SQL injections by interpolating the variables From 18f2e13a303161f8ff7ae8f102720c7d786b0e7e Mon Sep 17 00:00:00 2001 From: Dean Date: Fri, 17 Jun 2022 12:00:42 +0100 Subject: [PATCH 03/21] Fixes for Rest API request UI. Rest test fixes for XML API request body. Fix for raw XML api request body parsing issue. General fixes for query testing. --- .../rest/[query]/index.svelte | 20 ++- packages/server/__mocks__/node-fetch.ts | 9 + .../server/src/api/routes/tests/query.spec.js | 166 ++++++++++++++++++ packages/server/src/integrations/rest.ts | 2 +- .../src/integrations/tests/rest.spec.js | 17 +- .../server/src/migrations/tests/index.spec.ts | 20 ++- .../src/tests/utilities/TestConfiguration.js | 25 ++- 7 files changed, 244 insertions(+), 15 deletions(-) diff --git a/packages/builder/src/pages/builder/app/[application]/data/datasource/[selectedDatasource]/rest/[query]/index.svelte b/packages/builder/src/pages/builder/app/[application]/data/datasource/[selectedDatasource]/rest/[query]/index.svelte index ab01d4224..f236eaaf3 100644 --- a/packages/builder/src/pages/builder/app/[application]/data/datasource/[selectedDatasource]/rest/[query]/index.svelte +++ b/packages/builder/src/pages/builder/app/[application]/data/datasource/[selectedDatasource]/rest/[query]/index.svelte @@ -96,10 +96,13 @@ } if (cloneQuery?.fields?.requestBody) { - cloneQuery.fields.requestBody = runtimeToReadableBinding( - restBindings, - cloneQuery.fields.requestBody - ) + cloneQuery.fields.requestBody = + typeof cloneQuery.fields.requestBody === "object" + ? runtimeToReadableMap(restBindings, cloneQuery.fields.requestBody) + : runtimeToReadableBinding( + restBindings, + cloneQuery.fields.requestBody + ) } if (cloneQuery?.parameters) { @@ -141,10 +144,11 @@ restBindings, newQuery.fields.headers ) - newQuery.fields.requestBody = readableToRuntimeBinding( - restBindings, - newQuery.fields.requestBody - ) + newQuery.fields.requestBody = + typeof newQuery.fields.requestBody === "object" + ? readableToRuntimeMap(restBindings, newQuery.fields.requestBody) + : readableToRuntimeBinding(restBindings, newQuery.fields.requestBody) + newQuery.fields.path = url.split("?")[0] newQuery.fields.queryString = queryString newQuery.fields.authConfigId = authConfigId diff --git a/packages/server/__mocks__/node-fetch.ts b/packages/server/__mocks__/node-fetch.ts index 350680691..1a7015fa5 100644 --- a/packages/server/__mocks__/node-fetch.ts +++ b/packages/server/__mocks__/node-fetch.ts @@ -15,6 +15,15 @@ module FetchMock { }, }, json: async () => { + //x-www-form-encoded body is a URLSearchParams + //The call to stringify it leaves it blank + if (body?.opts?.body instanceof URLSearchParams) { + const paramArray = Array.from(body.opts.body.entries()) + body.opts.body = paramArray.reduce((acc: any, pair: any) => { + acc[pair[0]] = pair[1] + return acc + }, {}) + } return body }, } diff --git a/packages/server/src/api/routes/tests/query.spec.js b/packages/server/src/api/routes/tests/query.spec.js index 5dacda350..273bdb999 100644 --- a/packages/server/src/api/routes/tests/query.spec.js +++ b/packages/server/src/api/routes/tests/query.spec.js @@ -346,4 +346,170 @@ describe("/queries", () => { expect(contents).toBe(null) }) }) + + describe("Current User Request Mapping", () => { + + async function previewGet(datasource, fields, params) { + return config.previewQuery(request, config, datasource, fields, params) + } + + async function previewPost(datasource, fields, params) { + return config.previewQuery(request, config, datasource, fields, params, "create") + } + + it("should parse global and query level header mappings", async () => { + const userDetails = config.getUserDetails() + + const datasource = await config.restDatasource({ + defaultHeaders: { + "test": "headerVal", + "emailHdr": "{{[user].[email]}}" + } + }) + const res = await previewGet(datasource, { + path: "www.google.com", + queryString: "email={{[user].[email]}}", + headers: { + queryHdr : "{{[user].[firstName]}}", + secondHdr : "1234" + } + }) + + const parsedRequest = JSON.parse(res.body.extra.raw) + expect(parsedRequest.opts.headers).toEqual({ + "test": "headerVal", + "emailHdr": userDetails.email, + "queryHdr": userDetails.firstName, + "secondHdr" : "1234" + }) + expect(res.body.rows[0].url).toEqual("http://www.google.com?email=" + userDetails.email) + }) + + it("should bind the current user to query parameters", async () => { + const userDetails = config.getUserDetails() + + const datasource = await config.restDatasource() + + const res = await previewGet(datasource, { + path: "www.google.com", + queryString: "test={{myEmail}}&testName={{myName}}&testParam={{testParam}}", + }, { + "myEmail" : "{{[user].[email]}}", + "myName" : "{{[user].[firstName]}}", + "testParam" : "1234" + }) + + expect(res.body.rows[0].url).toEqual("http://www.google.com?test=" + userDetails.email + + "&testName=" + userDetails.firstName + "&testParam=1234") + }) + + it("should bind the current user the request body - plain text", async () => { + const userDetails = config.getUserDetails() + const datasource = await config.restDatasource() + + const res = await previewPost(datasource, { + path: "www.google.com", + queryString: "testParam={{testParam}}", + requestBody: "This is plain text and this is my email: {{[user].[email]}}. This is a test param: {{testParam}}", + bodyType: "text" + }, { + "testParam" : "1234" + }) + + const parsedRequest = JSON.parse(res.body.extra.raw) + expect(parsedRequest.opts.body).toEqual(`This is plain text and this is my email: ${userDetails.email}. This is a test param: 1234`) + expect(res.body.rows[0].url).toEqual("http://www.google.com?testParam=1234") + }) + + it("should bind the current user the request body - json", async () => { + const userDetails = config.getUserDetails() + const datasource = await config.restDatasource() + + const res = await previewPost(datasource, { + path: "www.google.com", + queryString: "testParam={{testParam}}", + requestBody: "{\"email\":\"{{[user].[email]}}\",\"queryCode\":{{testParam}},\"userRef\":\"{{userRef}}\"}", + bodyType: "json" + }, { + "testParam" : "1234", + "userRef" : "{{[user].[firstName]}}" + }) + + const parsedRequest = JSON.parse(res.body.extra.raw) + const test = `{"email":"${userDetails.email}","queryCode":1234,"userRef":"${userDetails.firstName}"}` + expect(parsedRequest.opts.body).toEqual(test) + expect(res.body.rows[0].url).toEqual("http://www.google.com?testParam=1234") + }) + + it("should bind the current user the request body - xml", async () => { + const userDetails = config.getUserDetails() + const datasource = await config.restDatasource() + + const res = await previewPost(datasource, { + path: "www.google.com", + queryString: "testParam={{testParam}}", + requestBody: " {{[user].[email]}} {{testParam}} " + + "{{userId}} testing ", + bodyType: "xml" + }, { + "testParam" : "1234", + "userId" : "{{[user].[firstName]}}" + }) + + const parsedRequest = JSON.parse(res.body.extra.raw) + const test = ` ${userDetails.email} 1234 ${userDetails.firstName} testing ` + + expect(parsedRequest.opts.body).toEqual(test) + expect(res.body.rows[0].url).toEqual("http://www.google.com?testParam=1234") + }) + + it("should bind the current user the request body - form-data", async () => { + const userDetails = config.getUserDetails() + const datasource = await config.restDatasource() + + const res = await previewPost(datasource, { + path: "www.google.com", + queryString: "testParam={{testParam}}", + requestBody: "{\"email\":\"{{[user].[email]}}\",\"queryCode\":{{testParam}},\"userRef\":\"{{userRef}}\"}", + bodyType: "form" + }, { + "testParam" : "1234", + "userRef" : "{{[user].[firstName]}}" + }) + + const parsedRequest = JSON.parse(res.body.extra.raw) + + const emailData = parsedRequest.opts.body._streams[1] + expect(emailData).toEqual(userDetails.email) + + const queryCodeData = parsedRequest.opts.body._streams[4] + expect(queryCodeData).toEqual("1234") + + const userRef = parsedRequest.opts.body._streams[7] + expect(userRef).toEqual(userDetails.firstName) + + expect(res.body.rows[0].url).toEqual("http://www.google.com?testParam=1234") + }) + + it("should bind the current user the request body - encoded", async () => { + const userDetails = config.getUserDetails() + const datasource = await config.restDatasource() + + const res = await previewPost(datasource, { + path: "www.google.com", + queryString: "testParam={{testParam}}", + requestBody: "{\"email\":\"{{[user].[email]}}\",\"queryCode\":{{testParam}},\"userRef\":\"{{userRef}}\"}", + bodyType: "encoded" + }, { + "testParam" : "1234", + "userRef" : "{{[user].[firstName]}}" + }) + const parsedRequest = JSON.parse(res.body.extra.raw) + + expect(parsedRequest.opts.body.email).toEqual(userDetails.email) + expect(parsedRequest.opts.body.queryCode).toEqual("1234") + expect(parsedRequest.opts.body.userRef).toEqual(userDetails.firstName) + }) + + }); }) diff --git a/packages/server/src/integrations/rest.ts b/packages/server/src/integrations/rest.ts index 6174613fc..e9c5f59fa 100644 --- a/packages/server/src/integrations/rest.ts +++ b/packages/server/src/integrations/rest.ts @@ -286,7 +286,7 @@ module RestModule { input.body = form break case BodyTypes.XML: - if (object != null) { + if (object != null && Object.keys(object).length) { string = new XmlBuilder().buildObject(object) } input.body = string diff --git a/packages/server/src/integrations/tests/rest.spec.js b/packages/server/src/integrations/tests/rest.spec.js index 8f3c7f7f5..0bb1e3a75 100644 --- a/packages/server/src/integrations/tests/rest.spec.js +++ b/packages/server/src/integrations/tests/rest.spec.js @@ -155,12 +155,27 @@ describe("REST Integration", () => { expect(output.headers["Content-Type"]).toEqual("application/json") }) - it("should allow XML", () => { + it("should allow raw XML", () => { + const output = config.integration.addBody("xml", "12", {}) + expect(output.body.includes("1")).toEqual(true) + expect(output.body.includes("2")).toEqual(true) + expect(output.headers["Content-Type"]).toEqual("application/xml") + }) + + it("should allow a valid js object and parse the contents to xml", () => { const output = config.integration.addBody("xml", input, {}) expect(output.body.includes("1")).toEqual(true) expect(output.body.includes("2")).toEqual(true) expect(output.headers["Content-Type"]).toEqual("application/xml") }) + + it("should allow a valid json string and parse the contents to xml", () => { + const output = config.integration.addBody("xml", JSON.stringify(input), {}) + expect(output.body.includes("1")).toEqual(true) + expect(output.body.includes("2")).toEqual(true) + expect(output.headers["Content-Type"]).toEqual("application/xml") + }) + }) describe("response", () => { diff --git a/packages/server/src/migrations/tests/index.spec.ts b/packages/server/src/migrations/tests/index.spec.ts index ca30fbca0..84400f3df 100644 --- a/packages/server/src/migrations/tests/index.spec.ts +++ b/packages/server/src/migrations/tests/index.spec.ts @@ -91,8 +91,24 @@ describe("migrations", () => { await clearMigrations() const appId = config.prodAppId const roles = { [appId]: "role_12345" } - await config.createUser(undefined, undefined, false, true, roles) // admin only - await config.createUser(undefined, undefined, false, false, roles) // non admin non builder + await config.createUser( + undefined, + undefined, + undefined, + undefined, + false, + true, + roles + ) // admin only + await config.createUser( + undefined, + undefined, + undefined, + undefined, + false, + false, + roles + ) // non admin non builder await config.createTable() await config.createRow() await config.createRow() diff --git a/packages/server/src/tests/utilities/TestConfiguration.js b/packages/server/src/tests/utilities/TestConfiguration.js index fc4d302c6..baa4ec13b 100644 --- a/packages/server/src/tests/utilities/TestConfiguration.js +++ b/packages/server/src/tests/utilities/TestConfiguration.js @@ -28,6 +28,8 @@ const { encrypt } = require("@budibase/backend-core/encryption") const GLOBAL_USER_ID = "us_uuid1" const EMAIL = "babs@babs.com" +const FIRSTNAME = "Barbara" +const LASTNAME = "Barbington" const CSRF_TOKEN = "e3727778-7af0-4226-b5eb-f43cbe60a306" class TestConfiguration { @@ -59,6 +61,15 @@ class TestConfiguration { return this.prodAppId } + getUserDetails() { + return { + globalId: GLOBAL_USER_ID, + email: EMAIL, + firstName: FIRSTNAME, + lastName: LASTNAME, + } + } + async doInContext(appId, task) { if (!appId) { appId = this.appId @@ -118,6 +129,8 @@ class TestConfiguration { // USER / AUTH async globalUser({ id = GLOBAL_USER_ID, + firstName = FIRSTNAME, + lastName = LASTNAME, builder = true, admin = false, email = EMAIL, @@ -135,6 +148,8 @@ class TestConfiguration { ...existing, roles: roles || {}, tenantId: TENANT_ID, + firstName, + lastName, } await createASession(id, { sessionId: "sessionid", @@ -161,6 +176,8 @@ class TestConfiguration { async createUser( id = null, + firstName = FIRSTNAME, + lastName = LASTNAME, email = EMAIL, builder = true, admin = false, @@ -169,6 +186,8 @@ class TestConfiguration { const globalId = !id ? `us_${Math.random()}` : `us_${id}` const resp = await this.globalUser({ id: globalId, + firstName, + lastName, email, builder, admin, @@ -520,14 +539,14 @@ class TestConfiguration { // QUERY - async previewQuery(request, config, datasource, fields) { + async previewQuery(request, config, datasource, fields, params, verb) { return request .post(`/api/queries/preview`) .send({ datasourceId: datasource._id, - parameters: {}, + parameters: params || {}, fields, - queryVerb: "read", + queryVerb: verb || "read", name: datasource.name, }) .set(config.defaultHeaders()) From 523bb634550034b8fa87ccbbcb18626e3093a11b Mon Sep 17 00:00:00 2001 From: Dean Date: Mon, 20 Jun 2022 11:11:15 +0100 Subject: [PATCH 04/21] Added missing request context for user bindings --- packages/server/src/api/controllers/query/index.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/server/src/api/controllers/query/index.ts b/packages/server/src/api/controllers/query/index.ts index 21c9eb2a4..19a547b40 100644 --- a/packages/server/src/api/controllers/query/index.ts +++ b/packages/server/src/api/controllers/query/index.ts @@ -175,6 +175,9 @@ async function execute(ctx: any, opts = { rowsOnly: false }) { parameters: enrichedParameters, transformer: query.transformer, queryId: ctx.params.queryId, + ctx: { + user: ctx.user, + }, }) const { rows, pagination, extra } = await quotas.addQuery(runFn) From dc20ecc5ff474cb33128f15dbfee48c78f9eb8d2 Mon Sep 17 00:00:00 2001 From: Dean Date: Thu, 23 Jun 2022 14:29:19 +0100 Subject: [PATCH 05/21] Merge commit --- .vscode/settings.json | 14 ++++- packages/backend-core/package.json | 1 + packages/backend-core/src/auth.js | 53 +++++++++++++++++++ packages/backend-core/src/db/utils.ts | 16 ++++-- .../src/middleware/passport/oidc.js | 42 +++++++++------ .../src/middleware/passport/utils.js | 25 +++++++++ packages/backend-core/yarn.lock | 10 ++++ .../builder/src/builderStore/dataBinding.js | 51 +++++++++++++++++- .../server/src/api/controllers/query/index.ts | 7 ++- packages/server/src/threads/query.js | 7 +++ .../worker/src/api/controllers/global/auth.ts | 11 ++-- 11 files changed, 211 insertions(+), 26 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index d471924fe..4838a4fd8 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,5 +3,17 @@ "editor.codeActionsOnSave": { "source.fixAll": true }, - "editor.defaultFormatter": "svelte.svelte-vscode" + "editor.defaultFormatter": "svelte.svelte-vscode", + "[json]": { + "editor.defaultFormatter": "vscode.json-language-features" + }, + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "debug.javascript.terminalOptions": { + "skipFiles": [ + "${workspaceFolder}/packages/backend-core/node_modules/**", + "/**" + ] + }, } diff --git a/packages/backend-core/package.json b/packages/backend-core/package.json index d69d57b88..c0f5bf6e0 100644 --- a/packages/backend-core/package.json +++ b/packages/backend-core/package.json @@ -36,6 +36,7 @@ "passport-google-oauth": "2.0.0", "passport-jwt": "4.0.0", "passport-local": "1.0.0", + "passport-oauth2-refresh": "^2.1.0", "posthog-node": "1.3.0", "pouchdb": "7.3.0", "pouchdb-find": "7.2.2", diff --git a/packages/backend-core/src/auth.js b/packages/backend-core/src/auth.js index b13cd932c..58c00c92c 100644 --- a/packages/backend-core/src/auth.js +++ b/packages/backend-core/src/auth.js @@ -2,6 +2,9 @@ const passport = require("koa-passport") const LocalStrategy = require("passport-local").Strategy const JwtStrategy = require("passport-jwt").Strategy const { getGlobalDB } = require("./tenancy") +const refresh = require("passport-oauth2-refresh") +const { Configs } = require("./constants") +const { getScopedConfig } = require("./db/utils") const { jwt, local, @@ -34,6 +37,55 @@ passport.deserializeUser(async (user, done) => { } }) +//requestAccessStrategy +//refreshOAuthAccessToken + +//configId for google and OIDC?? +async function reUpToken(refreshToken, configId) { + const db = getGlobalDB() + console.log(refreshToken, configId) + const config = await getScopedConfig(db, { + type: Configs.OIDC, + group: {}, //ctx.query.group, this was an empty object when authentication initially + }) + + const chosenConfig = config.configs[0] //.filter((c) => c.uuid === configId)[0] + let callbackUrl = await oidc.oidcCallbackUrl(db, chosenConfig) + + //Remote Config + const enrichedConfig = await oidc.fetchOIDCStrategyConfig( + chosenConfig, + callbackUrl + ) + + const strategy = await oidc.strategyFactory(enrichedConfig, () => { + console.log("saveFn RETURN ARGS", JSON.stringify(arguments)) + }) + + try { + refresh.use(strategy, { + setRefreshOAuth2() { + return strategy._getOAuth2Client(enrichedConfig) + }, + }) + console.log("Testing") + + // By default, the strat calls itself "openidconnect" + + // refresh.requestNewAccessToken( + // 'openidconnect', + // refToken, + // (err, accessToken, refreshToken) => { + // console.log("REAUTH CB", err, accessToken, refreshToken); + // }) + } catch (err) { + console.error(err) + throw new Error("Error constructing OIDC refresh strategy", err) + } + + console.log("end") +} + module.exports = { buildAuthMiddleware: authenticated, passport, @@ -46,4 +98,5 @@ module.exports = { authError, buildCsrfMiddleware: csrf, internalApi, + reUpToken, } diff --git a/packages/backend-core/src/db/utils.ts b/packages/backend-core/src/db/utils.ts index dc7a0454c..ac2c7df34 100644 --- a/packages/backend-core/src/db/utils.ts +++ b/packages/backend-core/src/db/utils.ts @@ -384,7 +384,10 @@ export const getScopedFullConfig = async function ( if (type === Configs.SETTINGS) { if (scopedConfig && scopedConfig.doc) { // overrides affected by environment variables - scopedConfig.doc.config.platformUrl = await getPlatformUrl() + scopedConfig.doc.config.platformUrl = await getPlatformUrl( + { tenantAware: true }, + db + ) scopedConfig.doc.config.analyticsEnabled = await events.analytics.enabled() } else { @@ -393,7 +396,7 @@ export const getScopedFullConfig = async function ( doc: { _id: generateConfigID({ type, user, workspace }), config: { - platformUrl: await getPlatformUrl(), + platformUrl: await getPlatformUrl({ tenantAware: true }, db), analyticsEnabled: await events.analytics.enabled(), }, }, @@ -404,7 +407,10 @@ export const getScopedFullConfig = async function ( return scopedConfig && scopedConfig.doc } -export const getPlatformUrl = async (opts = { tenantAware: true }) => { +export const getPlatformUrl = async ( + opts = { tenantAware: true }, + db = null +) => { let platformUrl = env.PLATFORM_URL || "http://localhost:10000" if (!env.SELF_HOSTED && env.MULTI_TENANCY && opts.tenantAware) { @@ -414,11 +420,11 @@ export const getPlatformUrl = async (opts = { tenantAware: true }) => { platformUrl = platformUrl.replace("://", `://${tenantId}.`) } } else if (env.SELF_HOSTED) { - const db = getGlobalDB() + const dbx = db ? db : getGlobalDB() // get the doc directly instead of with getScopedConfig to prevent loop let settings try { - settings = await db.get(generateConfigID({ type: Configs.SETTINGS })) + settings = await dbx.get(generateConfigID({ type: Configs.SETTINGS })) } catch (e: any) { if (e.status !== 404) { throw e diff --git a/packages/backend-core/src/middleware/passport/oidc.js b/packages/backend-core/src/middleware/passport/oidc.js index 1e93e20b1..ef785f8ae 100644 --- a/packages/backend-core/src/middleware/passport/oidc.js +++ b/packages/backend-core/src/middleware/passport/oidc.js @@ -1,6 +1,7 @@ const fetch = require("node-fetch") const OIDCStrategy = require("@techpass/passport-openidconnect").Strategy const { authenticateThirdParty } = require("./third-party-common") +const { ssoCallbackUrl } = require("./utils") const buildVerifyFn = saveUserFn => { /** @@ -89,11 +90,22 @@ function validEmail(value) { * from couchDB rather than environment variables, using this factory is necessary for dynamically configuring passport. * @returns Dynamically configured Passport OIDC Strategy */ -exports.strategyFactory = async function (config, callbackUrl, saveUserFn) { +exports.strategyFactory = async function (config, saveUserFn) { + try { + const verify = buildVerifyFn(saveUserFn) + return new OIDCStrategy(config, verify) + } catch (err) { + console.error(err) + throw new Error("Error constructing OIDC authentication strategy", err) + } +} + +export const fetchOIDCStrategyConfig = async (config, callbackUrl) => { try { const { clientID, clientSecret, configUrl } = config if (!clientID || !clientSecret || !callbackUrl || !configUrl) { + //check for remote config and all required elements throw new Error( "Configuration invalid. Must contain clientID, clientSecret, callbackUrl and configUrl" ) @@ -109,24 +121,24 @@ exports.strategyFactory = async function (config, callbackUrl, saveUserFn) { const body = await response.json() - const verify = buildVerifyFn(saveUserFn) - return new OIDCStrategy( - { - issuer: body.issuer, - authorizationURL: body.authorization_endpoint, - tokenURL: body.token_endpoint, - userInfoURL: body.userinfo_endpoint, - clientID: clientID, - clientSecret: clientSecret, - callbackURL: callbackUrl, - }, - verify - ) + return { + issuer: body.issuer, + authorizationURL: body.authorization_endpoint, + tokenURL: body.token_endpoint, + userInfoURL: body.userinfo_endpoint, + clientID: clientID, + clientSecret: clientSecret, + callbackURL: callbackUrl, + } } catch (err) { console.error(err) - throw new Error("Error constructing OIDC authentication strategy", err) + throw new Error("Error constructing OIDC authentication configuration", err) } } +export const oidcCallbackUrl = async (db, config) => { + return ssoCallbackUrl(db, config, "oidc") +} + // expose for testing exports.buildVerifyFn = buildVerifyFn diff --git a/packages/backend-core/src/middleware/passport/utils.js b/packages/backend-core/src/middleware/passport/utils.js index cbb93bfa3..ddc87c6cd 100644 --- a/packages/backend-core/src/middleware/passport/utils.js +++ b/packages/backend-core/src/middleware/passport/utils.js @@ -1,3 +1,7 @@ +const { getGlobalDB, isMultiTenant, getTenantId } = require("../../tenancy") +const { getScopedConfig } = require("../../db/utils") +const { Configs } = require("../../constants") + /** * Utility to handle authentication errors. * @@ -5,6 +9,7 @@ * @param {*} message Message that will be returned in the response body * @param {*} err (Optional) error that will be logged */ + exports.authError = function (done, message, err = null) { return done( err, @@ -12,3 +17,23 @@ exports.authError = function (done, message, err = null) { { message: message } ) } + +exports.ssoCallbackUrl = async (db, config, type) => { + // incase there is a callback URL from before + if (config && config.callbackURL) { + return config.callbackURL + } + + const dbx = db ? db : getGlobalDB() + const publicConfig = await getScopedConfig(dbx, { + type: Configs.SETTINGS, + }) + + let callbackUrl = `/api/global/auth` + if (isMultiTenant()) { + callbackUrl += `/${getTenantId()}` + } + callbackUrl += `/${type}/callback` + + return `${publicConfig.platformUrl}${callbackUrl}` +} diff --git a/packages/backend-core/yarn.lock b/packages/backend-core/yarn.lock index 01d1a43b6..29ba61d32 100644 --- a/packages/backend-core/yarn.lock +++ b/packages/backend-core/yarn.lock @@ -291,6 +291,11 @@ resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== +"@budibase/types@^1.0.206": + version "1.0.208" + resolved "https://registry.yarnpkg.com/@budibase/types/-/types-1.0.208.tgz#c45cb494fb5b85229e15a34c6ac1805bae5be867" + integrity sha512-zKIHg6TGK+soVxMNZNrGypP3DCrd3jhlUQEFeQ+rZR6/tCue1G74bjzydY5FjnLEsXeLH1a0hkS5HulTmvQ2bA== + "@istanbuljs/load-nyc-config@^1.0.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced" @@ -3965,6 +3970,11 @@ passport-oauth1@1.x.x: passport-strategy "1.x.x" utils-merge "1.x.x" +passport-oauth2-refresh@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/passport-oauth2-refresh/-/passport-oauth2-refresh-2.1.0.tgz#c31cd133826383f5539d16ad8ab4f35ca73ce4a4" + integrity sha512-4ML7ooCESCqiTgdDBzNUFTBcPR8zQq9iM6eppEUGMMvLdsjqRL93jKwWm4Az3OJcI+Q2eIVyI8sVRcPFvxcF/A== + passport-oauth2@1.x.x: version "1.6.1" resolved "https://registry.yarnpkg.com/passport-oauth2/-/passport-oauth2-1.6.1.tgz#c5aee8f849ce8bd436c7f81d904a3cd1666f181b" diff --git a/packages/builder/src/builderStore/dataBinding.js b/packages/builder/src/builderStore/dataBinding.js index 8cbc62929..da3269ba8 100644 --- a/packages/builder/src/builderStore/dataBinding.js +++ b/packages/builder/src/builderStore/dataBinding.js @@ -49,6 +49,43 @@ export const getBindableProperties = (asset, componentId) => { ] } +/** + * Gets all rest bindable data fields + */ +export const getRestBindings = () => { + const userBindings = getUserBindings() + const oauthBindings = getAuthBindings() + return [...userBindings, ...oauthBindings] +} + +/** + * Utility - coverting a map of readable bindings to runtime + */ +export const readableToRuntimeMap = (bindings, ctx) => { + if (!bindings || !ctx) { + return {} + } + return Object.keys(ctx).reduce((acc, key) => { + let parsedQuery = readableToRuntimeBinding(bindings, ctx[key]) + acc[key] = parsedQuery + return acc + }, {}) +} + +/** + * Utility - coverting a map of runtime bindings to readable + */ +export const runtimeToReadableMap = (bindings, ctx) => { + if (!bindings || !ctx) { + return {} + } + return Object.keys(ctx).reduce((acc, key) => { + let parsedQuery = runtimeToReadableBinding(bindings, ctx[key]) + acc[key] = parsedQuery + return acc + }, {}) +} + /** * Gets the bindable properties exposed by a certain component. */ @@ -298,10 +335,22 @@ const getUserBindings = () => { providerId: "user", }) }) - return bindings } +const getAuthBindings = () => { + return [ + { + type: "context", + runtimeBinding: `${makePropSafe("user")}.${makePropSafe( + "oauth2" + )}.${makePropSafe("accessToken")}`, + readableBinding: "OAuthToken", + providerId: "user", + }, + ] +} + /** * Gets all device bindings that are globally available. */ diff --git a/packages/server/src/api/controllers/query/index.ts b/packages/server/src/api/controllers/query/index.ts index 2abd83140..73b508f02 100644 --- a/packages/server/src/api/controllers/query/index.ts +++ b/packages/server/src/api/controllers/query/index.ts @@ -8,6 +8,8 @@ import { QUERY_THREAD_TIMEOUT } from "../../../environment" import { getAppDB } from "@budibase/backend-core/context" import { quotas } from "@budibase/pro" import { events } from "@budibase/backend-core" +import { getCookie } from "@budibase/backend-core/utils" +import { Cookies } from "@budibase/backend-core/constants" const Runner = new Thread(ThreadType.QUERY, { timeoutMs: QUERY_THREAD_TIMEOUT || 10000, @@ -119,6 +121,10 @@ export async function preview(ctx: any) { // this stops dynamic variables from calling the same query const { fields, parameters, queryVerb, transformer, queryId } = query + //check for oAuth elements here? + const configId = getCookie(ctx, Cookies.OIDC_CONFIG) + console.log(configId) + try { const runFn = () => Runner.run({ @@ -130,7 +136,6 @@ export async function preview(ctx: any) { transformer, queryId, }) - const { rows, keys, info, extra } = await quotas.addQuery(runFn) await events.query.previewed(datasource, query) ctx.body = { diff --git a/packages/server/src/threads/query.js b/packages/server/src/threads/query.js index ec9d9a6fa..6e6822d6f 100644 --- a/packages/server/src/threads/query.js +++ b/packages/server/src/threads/query.js @@ -4,6 +4,7 @@ const ScriptRunner = require("../utilities/scriptRunner") const { integrations } = require("../integrations") const { processStringSync } = require("@budibase/string-templates") const { doInAppContext, getAppDB } = require("@budibase/backend-core/context") +// const { reUpToken } = require("@budibase/backend-core/auth") const { isSQL } = require("../integrations/utils") const { enrichQueryFields, @@ -30,6 +31,11 @@ class QueryRunner { async execute() { let { datasource, fields, queryVerb, transformer } = this + + // if(this.ctx.user.oauth2?.refreshToken){ + // reUpToken(this.ctx.user.oauth2?.refreshToken) + // } + const Integration = integrations[datasource.source] if (!Integration) { throw "Integration type does not exist." @@ -79,6 +85,7 @@ class QueryRunner { this.cachedVariables.length > 0 && !this.hasRerun ) { + // return { info } this.hasRerun = true // invalidate the cache value await threadUtils.invalidateDynamicVariables(this.cachedVariables) diff --git a/packages/worker/src/api/controllers/global/auth.ts b/packages/worker/src/api/controllers/global/auth.ts index 896a7c48d..bd399a29f 100644 --- a/packages/worker/src/api/controllers/global/auth.ts +++ b/packages/worker/src/api/controllers/global/auth.ts @@ -224,7 +224,7 @@ export const googleAuth = async (ctx: any, next: any) => { )(ctx, next) } -async function oidcStrategyFactory(ctx: any, configId: any) { +export const oidcStrategyFactory = async (ctx: any, configId: any) => { const db = getGlobalDB() const config = await core.db.getScopedConfig(db, { type: Configs.OIDC, @@ -234,7 +234,12 @@ async function oidcStrategyFactory(ctx: any, configId: any) { const chosenConfig = config.configs.filter((c: any) => c.uuid === configId)[0] let callbackUrl = await exports.oidcCallbackUrl(chosenConfig) - return oidc.strategyFactory(chosenConfig, callbackUrl, users.save) + //Remote Config + const enrichedConfig = await oidc.fetchOIDCStrategyConfig( + chosenConfig, + callbackUrl + ) + return oidc.strategyFactory(enrichedConfig, users.save) } /** @@ -249,7 +254,7 @@ export const oidcPreAuth = async (ctx: any, next: any) => { return passport.authenticate(strategy, { // required 'openid' scope is added by oidc strategy factory - scope: ["profile", "email"], + scope: ["profile", "email", "offline_access"], //auth0 offline_access scope required for the refresh token behaviour. })(ctx, next) } From 94496abe85978632328970a8ab269db89d9e9fdb Mon Sep 17 00:00:00 2001 From: Dean Date: Fri, 1 Jul 2022 17:27:24 +0100 Subject: [PATCH 06/21] Fixes for datasource authentication parsing. Mapping UX updates --- packages/bbui/src/Form/Combobox.svelte | 1 + packages/bbui/src/Form/Core/Combobox.svelte | 5 +- .../builder/src/builderStore/dataBinding.js | 51 ++++++++++- .../rest/auth/RestAuthenticationModal.svelte | 22 ++++- .../bindings/DrawerBindableCombobox.svelte | 38 ++++---- .../integration/KeyValueBuilder.svelte | 12 +++ .../rest/[query]/index.svelte | 89 +++++++++++-------- packages/server/src/threads/query.js | 6 ++ 8 files changed, 165 insertions(+), 59 deletions(-) diff --git a/packages/bbui/src/Form/Combobox.svelte b/packages/bbui/src/Form/Combobox.svelte index 83927b05d..343af559c 100644 --- a/packages/bbui/src/Form/Combobox.svelte +++ b/packages/bbui/src/Form/Combobox.svelte @@ -40,5 +40,6 @@ on:change={onChange} on:pick on:type + on:blur /> diff --git a/packages/bbui/src/Form/Core/Combobox.svelte b/packages/bbui/src/Form/Core/Combobox.svelte index 2a4bac4a2..2835b3cd4 100644 --- a/packages/bbui/src/Form/Core/Combobox.svelte +++ b/packages/bbui/src/Form/Core/Combobox.svelte @@ -52,7 +52,10 @@ {id} type="text" on:focus={() => (focus = true)} - on:blur={() => (focus = false)} + on:blur={() => { + focus = false + dispatch("blur") + }} on:change={onType} value={value || ""} placeholder={placeholder || ""} diff --git a/packages/builder/src/builderStore/dataBinding.js b/packages/builder/src/builderStore/dataBinding.js index cddb061e2..05d17ecf3 100644 --- a/packages/builder/src/builderStore/dataBinding.js +++ b/packages/builder/src/builderStore/dataBinding.js @@ -54,7 +54,56 @@ export const getBindableProperties = (asset, componentId) => { */ export const getRestBindings = () => { const userBindings = getUserBindings() - return [...userBindings] + return [...userBindings, ...getAuthBindings()] +} + +/** + * Gets all rest bindable auth fields + */ +export const getAuthBindings = () => { + let bindings = [] + const safeUser = makePropSafe("user") + const safeOAuth2 = makePropSafe("oauth2") + const safeAccessToken = makePropSafe("accessToken") + + const authBindings = [ + { + runtime: `${safeUser}.${safeOAuth2}.${safeAccessToken}`, + readable: `Current User.OAuthToken`, + key: "accessToken", + }, + ] + + bindings = Object.keys(authBindings).map(key => { + const fieldBinding = authBindings[key] + return { + type: "context", + runtimeBinding: fieldBinding.runtime, + readableBinding: fieldBinding.readable, + fieldSchema: { type: "string", name: fieldBinding.key }, + providerId: "user", + } + }) + return bindings +} + +/** + * Utility - convert a key/value map to an array of custom 'context' bindings + * @param {object} valueMap Key/value pairings + * @param {string} prefix A contextual string prefix/path for a user readable binding + * @return {object[]} An array containing readable/runtime binding objects + */ +export const toBindingsArray = (valueMap, prefix) => { + if (!valueMap) { + return [] + } + return Object.keys(valueMap).map(binding => { + return { + type: "context", + runtimeBinding: binding, + readableBinding: `${prefix}.${binding}`, + } + }) } /** diff --git a/packages/builder/src/components/backend/DatasourceNavigator/TableIntegrationMenu/rest/auth/RestAuthenticationModal.svelte b/packages/builder/src/components/backend/DatasourceNavigator/TableIntegrationMenu/rest/auth/RestAuthenticationModal.svelte index 7f0cc7357..d80b60e96 100644 --- a/packages/builder/src/components/backend/DatasourceNavigator/TableIntegrationMenu/rest/auth/RestAuthenticationModal.svelte +++ b/packages/builder/src/components/backend/DatasourceNavigator/TableIntegrationMenu/rest/auth/RestAuthenticationModal.svelte @@ -2,6 +2,8 @@ import { onMount } from "svelte" import { ModalContent, Layout, Select, Body, Input } from "@budibase/bbui" import { AUTH_TYPE_LABELS, AUTH_TYPES } from "./authTypes" + import DrawerBindableCombobox from "components/common/bindings/DrawerBindableCombobox.svelte" + import { getAuthBindings } from "builderStore/dataBinding" export let configs export let currentConfig @@ -203,11 +205,23 @@ /> {/if} {#if form.type === AUTH_TYPES.BEARER} - (blurred.bearer.token = true)} + value={form.bearer.token} + bindings={getAuthBindings()} + on:change={e => { + form.bearer.token = e.detail + console.log(e.detail) + onFieldChange() + }} + on:blur={() => { + blurred.bearer.token = true + onFieldChange() + }} + allowJS={false} + placeholder="Token" + appendBindingsAsOptions={true} + drawerEnabled={false} error={blurred.bearer.token ? errors.bearer.token : null} /> {/if} diff --git a/packages/builder/src/components/common/bindings/DrawerBindableCombobox.svelte b/packages/builder/src/components/common/bindings/DrawerBindableCombobox.svelte index 44f88e841..2d235c802 100644 --- a/packages/builder/src/components/common/bindings/DrawerBindableCombobox.svelte +++ b/packages/builder/src/components/common/bindings/DrawerBindableCombobox.svelte @@ -18,6 +18,8 @@ export let options export let allowJS = true export let appendBindingsAsOptions = true + export let drawerEnabled = false + export let error const dispatch = createEventDispatcher() let bindingDrawer @@ -59,10 +61,12 @@ value={isJS ? "(JavaScript function)" : readableValue} on:type={e => onChange(e.detail, false)} on:pick={e => onChange(e.detail, true)} + on:blur={() => dispatch("blur")} {placeholder} options={allOptions} + {error} /> - {#if !disabled} + {#if !disabled && drawerEnabled}
{/if}
- - - Add the objects on the left to enrich your text. - - - (tempValue = event.detail)} - {bindings} - {allowJS} - /> - +{#if !drawerEnabled} + + + Add the objects on the left to enrich your text. + + + (tempValue = event.detail)} + {bindings} + {allowJS} + /> + +{/if} diff --git a/packages/builder/src/components/common/bindings/DrawerBindableCombobox.svelte b/packages/builder/src/components/common/bindings/DrawerBindableCombobox.svelte index 2d235c802..9033844dd 100644 --- a/packages/builder/src/components/common/bindings/DrawerBindableCombobox.svelte +++ b/packages/builder/src/components/common/bindings/DrawerBindableCombobox.svelte @@ -18,7 +18,6 @@ export let options export let allowJS = true export let appendBindingsAsOptions = true - export let drawerEnabled = false export let error const dispatch = createEventDispatcher() @@ -66,7 +65,7 @@ options={allOptions} {error} /> - {#if !disabled && drawerEnabled} + {#if !disabled}
{/if}
-{#if !drawerEnabled} - - - Add the objects on the left to enrich your text. - - - (tempValue = event.detail)} - {bindings} - {allowJS} - /> - -{/if} + + + + Add the objects on the left to enrich your text. + + + (tempValue = event.detail)} + {bindings} + {allowJS} + /> +