Merge branch 'develop' of github.com:Budibase/budibase into conditional-ui

This commit is contained in:
Andrew Kingston 2021-07-26 13:04:08 +01:00
commit 2715ff77d8
38 changed files with 293 additions and 108 deletions

View File

@ -42,15 +42,3 @@ jobs:
name: codecov-umbrella name: codecov-umbrella
verbose: true verbose: true
- run: yarn test:e2e:ci - run: yarn test:e2e:ci
- name: Build and Push Development Docker Image
# Only run on push
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/develop' }}
run: |
docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
yarn build
yarn build:docker:develop
env:
DOCKER_USER: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_API_KEY }}

52
.github/workflows/release-develop.yml vendored Normal file
View File

@ -0,0 +1,52 @@
name: Budibase Release Staging
on:
push:
branches:
- develop
env:
POSTHOG_TOKEN: ${{ secrets.POSTHOG_TOKEN }}
POSTHOG_URL: ${{ secrets.POSTHOG_URL }}
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12.x
- run: yarn
- run: yarn bootstrap
- run: yarn lint
- run: yarn build
- run: yarn test
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: eu-west-1
- name: Publish budibase packages to NPM
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
# setup the username and email. I tend to use 'GitHub Actions Bot' with no email by default
git config user.name "Budibase Staging Release Bot"
git config user.email "<>"
echo //registry.npmjs.org/:_authToken=${NPM_TOKEN} >> .npmrc
yarn release:develop
- name: Build/release Docker images
run: |
docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
yarn build
yarn build:docker:develop
env:
DOCKER_USER: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_API_KEY }}

View File

@ -1,5 +1,5 @@
{ {
"version": "0.9.78", "version": "0.9.80-alpha.7",
"npmClient": "yarn", "npmClient": "yarn",
"packages": [ "packages": [
"packages/*" "packages/*"

View File

@ -23,6 +23,7 @@
"publishdev": "lerna run publishdev", "publishdev": "lerna run publishdev",
"publishnpm": "yarn build && lerna publish --force-publish", "publishnpm": "yarn build && lerna publish --force-publish",
"release": "yarn build && lerna publish patch --yes --force-publish", "release": "yarn build && lerna publish patch --yes --force-publish",
"release:develop": "yarn build && lerna publish prerelease --yes --force-publish --dist-tag develop",
"restore": "yarn run clean && yarn run bootstrap && yarn run build", "restore": "yarn run clean && yarn run bootstrap && yarn run build",
"nuke": "yarn run nuke:packages && yarn run nuke:docker", "nuke": "yarn run nuke:packages && yarn run nuke:docker",
"nuke:packages": "yarn run restore", "nuke:packages": "yarn run restore",

View File

@ -0,0 +1 @@
module.exports = require("./src/constants")

View File

@ -1,6 +1,6 @@
{ {
"name": "@budibase/auth", "name": "@budibase/auth",
"version": "0.9.78", "version": "0.9.80-alpha.7",
"description": "Authentication middlewares for budibase builder and apps", "description": "Authentication middlewares for budibase builder and apps",
"main": "src/index.js", "main": "src/index.js",
"author": "Budibase", "author": "Budibase",
@ -10,6 +10,7 @@
"test:watch": "jest --watchAll" "test:watch": "jest --watchAll"
}, },
"dependencies": { "dependencies": {
"@techpass/passport-openidconnect": "^0.3.0",
"aws-sdk": "^2.901.0", "aws-sdk": "^2.901.0",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"ioredis": "^4.27.1", "ioredis": "^4.27.1",
@ -17,7 +18,6 @@
"koa-passport": "^4.1.4", "koa-passport": "^4.1.4",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"@techpass/passport-openidconnect": "^0.3.0",
"passport-google-auth": "^1.0.2", "passport-google-auth": "^1.0.2",
"passport-google-oauth": "^2.0.0", "passport-google-oauth": "^2.0.0",
"passport-jwt": "^4.0.0", "passport-jwt": "^4.0.0",
@ -35,8 +35,8 @@
"devDependencies": { "devDependencies": {
"ioredis-mock": "^5.5.5", "ioredis-mock": "^5.5.5",
"jest": "^26.6.3", "jest": "^26.6.3",
"pouchdb-adapter-memory": "^7.2.2",
"pouchdb": "^7.2.1", "pouchdb": "^7.2.1",
"pouchdb-adapter-memory": "^7.2.2",
"pouchdb-all-dbs": "^1.0.2" "pouchdb-all-dbs": "^1.0.2"
}, },
"gitHead": "d1836a898cab3f8ab80ee6d8f42be1a9eed7dcdc" "gitHead": "d1836a898cab3f8ab80ee6d8f42be1a9eed7dcdc"

View File

@ -9,6 +9,13 @@ exports.Cookies = {
OIDC_CONFIG: "budibase:oidc:config", OIDC_CONFIG: "budibase:oidc:config",
} }
exports.Headers = {
API_KEY: "x-budibase-api-key",
API_VER: "x-budibase-api-version",
APP_ID: "x-budibase-app-id",
TYPE: "x-budibase-type",
}
exports.GlobalRoles = { exports.GlobalRoles = {
OWNER: "owner", OWNER: "owner",
ADMIN: "admin", ADMIN: "admin",

View File

@ -1,4 +1,4 @@
const { Cookies } = require("../constants") const { Cookies, Headers } = require("../constants")
const { getCookie, clearCookie } = require("../utils") const { getCookie, clearCookie } = require("../utils")
const { getUser } = require("../cache/user") const { getUser } = require("../cache/user")
const { getSession, updateSessionTTL } = require("../security/sessions") const { getSession, updateSessionTTL } = require("../security/sessions")
@ -22,15 +22,17 @@ function buildNoAuthRegex(patterns) {
}) })
} }
function finalise(ctx, { authenticated, user, internal } = {}) { function finalise(ctx, { authenticated, user, internal, version } = {}) {
ctx.isAuthenticated = authenticated || false ctx.isAuthenticated = authenticated || false
ctx.user = user ctx.user = user
ctx.internal = internal || false ctx.internal = internal || false
ctx.version = version
} }
module.exports = (noAuthPatterns = [], opts) => { module.exports = (noAuthPatterns = [], opts) => {
const noAuthOptions = noAuthPatterns ? buildNoAuthRegex(noAuthPatterns) : [] const noAuthOptions = noAuthPatterns ? buildNoAuthRegex(noAuthPatterns) : []
return async (ctx, next) => { return async (ctx, next) => {
const version = ctx.request.headers[Headers.API_VER]
// the path is not authenticated // the path is not authenticated
const found = noAuthOptions.find(({ regex, method }) => { const found = noAuthOptions.find(({ regex, method }) => {
return ( return (
@ -71,7 +73,7 @@ module.exports = (noAuthPatterns = [], opts) => {
await updateSessionTTL(session) await updateSessionTTL(session)
} }
} }
const apiKey = ctx.request.headers["x-budibase-api-key"] const apiKey = ctx.request.headers[Headers.API_KEY]
// this is an internal request, no user made it // this is an internal request, no user made it
if (!authenticated && apiKey && apiKey === env.INTERNAL_API_KEY) { if (!authenticated && apiKey && apiKey === env.INTERNAL_API_KEY) {
authenticated = true authenticated = true
@ -82,12 +84,12 @@ module.exports = (noAuthPatterns = [], opts) => {
authenticated = false authenticated = false
} }
// isAuthenticated is a function, so use a variable to be able to check authed state // isAuthenticated is a function, so use a variable to be able to check authed state
finalise(ctx, { authenticated, user, internal }) finalise(ctx, { authenticated, user, internal, version })
return next() return next()
} catch (err) { } catch (err) {
// allow configuring for public access // allow configuring for public access
if (opts && opts.publicAllowed) { if (opts && opts.publicAllowed) {
finalise(ctx, { authenticated: false }) finalise(ctx, { authenticated: false, version })
} else { } else {
ctx.throw(err.status || 403, err) ctx.throw(err.status || 403, err)
} }

View File

@ -8,6 +8,7 @@ const jwt = require("jsonwebtoken")
const { options } = require("./middleware/passport/jwt") const { options } = require("./middleware/passport/jwt")
const { createUserEmailView } = require("./db/views") const { createUserEmailView } = require("./db/views")
const { getDB } = require("./db") const { getDB } = require("./db")
const { Headers } = require("./constants")
const APP_PREFIX = DocumentTypes.APP + SEPARATOR const APP_PREFIX = DocumentTypes.APP + SEPARATOR
@ -23,7 +24,7 @@ function confirmAppId(possibleAppId) {
* @returns {string|undefined} If an appId was found it will be returned. * @returns {string|undefined} If an appId was found it will be returned.
*/ */
exports.getAppId = ctx => { exports.getAppId = ctx => {
const options = [ctx.headers["x-budibase-app-id"], ctx.params.appId] const options = [ctx.headers[Headers.APP_ID], ctx.params.appId]
if (ctx.subdomains) { if (ctx.subdomains) {
options.push(ctx.subdomains[1]) options.push(ctx.subdomains[1])
} }
@ -97,7 +98,7 @@ exports.clearCookie = (ctx, name) => {
* @return {boolean} returns true if the call is from the client lib (a built app rather than the builder). * @return {boolean} returns true if the call is from the client lib (a built app rather than the builder).
*/ */
exports.isClient = ctx => { exports.isClient = ctx => {
return ctx.headers["x-budibase-type"] === "client" return ctx.headers[Headers.TYPE] === "client"
} }
/** /**

View File

@ -1,7 +1,7 @@
{ {
"name": "@budibase/bbui", "name": "@budibase/bbui",
"description": "A UI solution used in the different Budibase projects.", "description": "A UI solution used in the different Budibase projects.",
"version": "0.9.78", "version": "0.9.80-alpha.7",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"svelte": "src/index.js", "svelte": "src/index.js",
"module": "dist/bbui.es.js", "module": "dist/bbui.es.js",

View File

@ -1,6 +1,6 @@
{ {
"name": "@budibase/builder", "name": "@budibase/builder",
"version": "0.9.78", "version": "0.9.80-alpha.7",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"private": true, "private": true,
"scripts": { "scripts": {
@ -65,10 +65,10 @@
} }
}, },
"dependencies": { "dependencies": {
"@budibase/bbui": "^0.9.78", "@budibase/bbui": "^0.9.80-alpha.7",
"@budibase/client": "^0.9.78", "@budibase/client": "^0.9.80-alpha.7",
"@budibase/colorpicker": "1.1.2", "@budibase/colorpicker": "1.1.2",
"@budibase/string-templates": "^0.9.78", "@budibase/string-templates": "^0.9.80-alpha.7",
"@sentry/browser": "5.19.1", "@sentry/browser": "5.19.1",
"@spectrum-css/page": "^3.0.1", "@spectrum-css/page": "^3.0.1",
"@spectrum-css/vars": "^3.0.1", "@spectrum-css/vars": "^3.0.1",

View File

@ -6,8 +6,10 @@
import ErrorsBox from "components/common/ErrorsBox.svelte" import ErrorsBox from "components/common/ErrorsBox.svelte"
import { roles } from "stores/backend" import { roles } from "stores/backend"
const BASE_ROLE = { _id: "", inherits: "BASIC", permissionId: "Read/Write" }
let basePermissions = [] let basePermissions = []
let selectedRole = {} let selectedRole = BASE_ROLE
let errors = [] let errors = []
let builtInRoles = ["Admin", "Power", "Basic", "Public"] let builtInRoles = ["Admin", "Power", "Basic", "Public"]
// Don't allow editing of public role // Don't allow editing of public role
@ -15,6 +17,11 @@
$: selectedRoleId = selectedRole._id $: selectedRoleId = selectedRole._id
$: otherRoles = editableRoles.filter(role => role._id !== selectedRoleId) $: otherRoles = editableRoles.filter(role => role._id !== selectedRoleId)
$: isCreating = selectedRoleId == null || selectedRoleId === "" $: isCreating = selectedRoleId == null || selectedRoleId === ""
$: valid =
selectedRole.name &&
selectedRole.inherits &&
selectedRole.permissionId &&
!builtInRoles.includes(selectedRole.name)
const fetchBasePermissions = async () => { const fetchBasePermissions = async () => {
const permissionsResponse = await api.get("/api/permission/builtin") const permissionsResponse = await api.get("/api/permission/builtin")
@ -32,7 +39,7 @@
permissionId: role.permissionId ?? "", permissionId: role.permissionId ?? "",
} }
} else { } else {
selectedRole = { _id: "", inherits: "", permissionId: "" } selectedRole = BASE_ROLE
} }
errors = [] errors = []
} }
@ -88,6 +95,7 @@
title="Edit Roles" title="Edit Roles"
confirmText={isCreating ? "Create" : "Save"} confirmText={isCreating ? "Create" : "Save"}
onConfirm={saveRole} onConfirm={saveRole}
disabled={!valid}
> >
{#if errors.length} {#if errors.length}
<ErrorsBox {errors} /> <ErrorsBox {errors} />
@ -115,7 +123,7 @@
options={otherRoles} options={otherRoles}
getOptionValue={role => role._id} getOptionValue={role => role._id}
getOptionLabel={role => role.name} getOptionLabel={role => role.name}
placeholder="None" disabled={builtInRoles.includes(selectedRole.name)}
/> />
<Select <Select
label="Base Permissions" label="Base Permissions"
@ -123,7 +131,7 @@
options={basePermissions} options={basePermissions}
getOptionValue={x => x._id} getOptionValue={x => x._id}
getOptionLabel={x => x.name} getOptionLabel={x => x.name}
placeholder="Choose permissions" disabled={builtInRoles.includes(selectedRole.name)}
/> />
{/if} {/if}
<div slot="footer"> <div slot="footer">

View File

@ -58,5 +58,6 @@
align-items: stretch; align-items: stretch;
gap: var(--spacing-l); gap: var(--spacing-l);
background-color: var(--background); background-color: var(--background);
overflow-y: auto;
} }
</style> </style>

View File

@ -217,6 +217,10 @@
} }
originalGoogleDoc = cloneDeep(googleDoc) originalGoogleDoc = cloneDeep(googleDoc)
} else { } else {
// default activated to true for older configs
if (googleDoc.config.activated === undefined) {
googleDoc.config.activated = true
}
originalGoogleDoc = cloneDeep(googleDoc) originalGoogleDoc = cloneDeep(googleDoc)
providers.google = googleDoc providers.google = googleDoc
} }

View File

@ -19,7 +19,8 @@
import { fetchData } from "helpers" import { fetchData } from "helpers"
import { users, auth } from "stores/portal" import { users, auth } from "stores/portal"
import TagsRenderer from "./_components/TagsTableRenderer.svelte" import TagsRenderer from "./_components/RolesTagsTableRenderer.svelte"
import UpdateRolesModal from "./_components/UpdateRolesModal.svelte" import UpdateRolesModal from "./_components/UpdateRolesModal.svelte"
import ForceResetPasswordModal from "./_components/ForceResetPasswordModal.svelte" import ForceResetPasswordModal from "./_components/ForceResetPasswordModal.svelte"
@ -36,7 +37,8 @@
$: defaultRoleId = $userFetch?.data?.builder?.global ? "ADMIN" : "BASIC" $: defaultRoleId = $userFetch?.data?.builder?.global ? "ADMIN" : "BASIC"
// Merge the Apps list and the roles response to get something that makes sense for the table // Merge the Apps list and the roles response to get something that makes sense for the table
$: appList = Object.keys($apps?.data).map(id => { $: appList = Object.keys($apps?.data).map(id => {
const role = $userFetch?.data?.roles?.[id] || defaultRoleId const roleId = $userFetch?.data?.roles?.[id] || defaultRoleId
const role = $apps?.data?.[id].roles.find(role => role._id === roleId)
return { return {
...$apps?.data?.[id], ...$apps?.data?.[id],
_id: id, _id: id,

View File

@ -0,0 +1,8 @@
<script>
import TagsTableRenderer from "./TagsTableRenderer.svelte"
export let value
$: roles = value?.filter(role => role != null).map(role => role.name) ?? []
</script>
<TagsTableRenderer value={roles} />

View File

@ -4,9 +4,9 @@
const displayLimit = 5 const displayLimit = 5
$: roles = value?.filter(role => role != null) ?? [] $: values = value?.filter(value => value != null) ?? []
$: tags = roles.slice(0, displayLimit) $: tags = values.slice(0, displayLimit)
$: leftover = roles.length - tags.length $: leftover = values.length - tags.length
</script> </script>
<div class="tag-renderer"> <div class="tag-renderer">

View File

@ -10,8 +10,8 @@
const roles = app.roles const roles = app.roles
let options = roles let options = roles
.filter(role => role._id !== "PUBLIC")
.map(role => ({ value: role._id, label: role.name })) .map(role => ({ value: role._id, label: role.name }))
.filter(role => role.value !== "PUBLIC")
let selectedRole = user?.roles?.[app?._id] let selectedRole = user?.roles?.[app?._id]
async function updateUserRoles() { async function updateUserRoles() {
@ -48,5 +48,7 @@
on:change on:change
{options} {options}
label="Role" label="Role"
getOptionLabel={role => role.name}
getOptionValue={role => role._id}
/> />
</ModalContent> </ModalContent>

View File

@ -1,6 +1,6 @@
{ {
"name": "@budibase/cli", "name": "@budibase/cli",
"version": "0.9.78", "version": "0.9.80-alpha.7",
"description": "Budibase CLI, for developers, self hosting and migrations.", "description": "Budibase CLI, for developers, self hosting and migrations.",
"main": "src/index.js", "main": "src/index.js",
"bin": { "bin": {

View File

@ -1,6 +1,6 @@
{ {
"name": "@budibase/client", "name": "@budibase/client",
"version": "0.9.78", "version": "0.9.80-alpha.7",
"license": "MPL-2.0", "license": "MPL-2.0",
"module": "dist/budibase-client.js", "module": "dist/budibase-client.js",
"main": "dist/budibase-client.js", "main": "dist/budibase-client.js",
@ -18,9 +18,9 @@
"dev:builder": "rollup -cw" "dev:builder": "rollup -cw"
}, },
"dependencies": { "dependencies": {
"@budibase/bbui": "^0.9.78", "@budibase/bbui": "^0.9.80-alpha.7",
"@budibase/standard-components": "^0.9.78", "@budibase/standard-components": "^0.9.80-alpha.7",
"@budibase/string-templates": "^0.9.78", "@budibase/string-templates": "^0.9.80-alpha.7",
"regexparam": "^1.3.0", "regexparam": "^1.3.0",
"shortid": "^2.2.15", "shortid": "^2.2.15",
"svelte-spa-router": "^3.0.5" "svelte-spa-router": "^3.0.5"

View File

@ -1,7 +1,9 @@
import { notificationStore } from "../store"
import { ApiVersion } from "../constants"
/** /**
* API cache for cached request responses. * API cache for cached request responses.
*/ */
import { notificationStore } from "../store"
let cache = {} let cache = {}
/** /**
@ -22,6 +24,7 @@ const makeApiCall = async ({ method, url, body, json = true }) => {
const headers = { const headers = {
Accept: "application/json", Accept: "application/json",
"x-budibase-app-id": window["##BUDIBASE_APP_ID##"], "x-budibase-app-id": window["##BUDIBASE_APP_ID##"],
"x-budibase-api-version": ApiVersion,
...(json && { "Content-Type": "application/json" }), ...(json && { "Content-Type": "application/json" }),
...(!inBuilder && { "x-budibase-type": "client" }), ...(!inBuilder && { "x-budibase-type": "client" }),
} }

View File

@ -7,3 +7,11 @@ export const ActionTypes = {
RefreshDatasource: "RefreshDatasource", RefreshDatasource: "RefreshDatasource",
SetDataProviderQuery: "SetDataProviderQuery", SetDataProviderQuery: "SetDataProviderQuery",
} }
export const ApiVersion = "1"
/**
* API Version Changelog
* v1:
* - Coerce types for search endpoint
*/

View File

@ -6,8 +6,15 @@ const createAppStore = () => {
// Fetches the app definition including screens, layouts and theme // Fetches the app definition including screens, layouts and theme
const fetchAppDefinition = async () => { const fetchAppDefinition = async () => {
const appDefinition = await API.fetchAppPackage(get(store).appId) const appId = get(store)?.appId
store.set(appDefinition) if (!appId) {
throw "Cannot fetch app definition without app ID set"
}
const appDefinition = await API.fetchAppPackage(appId)
store.set({
...appDefinition,
appId: appDefinition?.application?.appId,
})
} }
// Sets the initial app ID // Sets the initial app ID

View File

@ -10,9 +10,14 @@ const createAuthStore = () => {
store.set(user) store.set(user)
} }
const logOut = async () => {
window.document.cookie = `budibase:auth=; budibase:currentapp=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;`
window.location = "/builder/auth/login"
}
return { return {
subscribe: store.subscribe, subscribe: store.subscribe,
actions: { fetchUser }, actions: { fetchUser, logOut },
} }
} }

View File

@ -1,10 +1,15 @@
import { get } from "svelte/store" import { get } from "svelte/store"
import { routeStore, builderStore, confirmationStore } from "../store" import {
routeStore,
builderStore,
confirmationStore,
authStore,
} from "../store"
import { saveRow, deleteRow, executeQuery, triggerAutomation } from "../api" import { saveRow, deleteRow, executeQuery, triggerAutomation } from "../api"
import { ActionTypes } from "../constants" import { ActionTypes } from "../constants"
const saveRowHandler = async (action, context) => { const saveRowHandler = async (action, context) => {
const { fields, providerId } = action.parameters const { fields, providerId, tableId } = action.parameters
if (providerId) { if (providerId) {
let draft = context[providerId] let draft = context[providerId]
if (fields) { if (fields) {
@ -12,6 +17,9 @@ const saveRowHandler = async (action, context) => {
draft[field] = value draft[field] = value
} }
} }
if (tableId) {
draft.tableId = tableId
}
await saveRow(draft) await saveRow(draft)
} }
} }
@ -74,6 +82,10 @@ const refreshDatasourceHandler = async (action, context) => {
) )
} }
const logoutHandler = async () => {
await authStore.actions.logOut()
}
const handlerMap = { const handlerMap = {
["Save Row"]: saveRowHandler, ["Save Row"]: saveRowHandler,
["Delete Row"]: deleteRowHandler, ["Delete Row"]: deleteRowHandler,
@ -82,6 +94,7 @@ const handlerMap = {
["Trigger Automation"]: triggerAutomationHandler, ["Trigger Automation"]: triggerAutomationHandler,
["Validate Form"]: validateFormHandler, ["Validate Form"]: validateFormHandler,
["Refresh Datasource"]: refreshDatasourceHandler, ["Refresh Datasource"]: refreshDatasourceHandler,
["Log Out"]: logoutHandler,
} }
const confirmTextMap = { const confirmTextMap = {

View File

@ -1,7 +1,7 @@
{ {
"name": "@budibase/server", "name": "@budibase/server",
"email": "hi@budibase.com", "email": "hi@budibase.com",
"version": "0.9.78", "version": "0.9.80-alpha.7",
"description": "Budibase Web Server", "description": "Budibase Web Server",
"main": "src/index.js", "main": "src/index.js",
"repository": { "repository": {
@ -60,9 +60,9 @@
"author": "Budibase", "author": "Budibase",
"license": "AGPL-3.0-or-later", "license": "AGPL-3.0-or-later",
"dependencies": { "dependencies": {
"@budibase/auth": "^0.9.78", "@budibase/auth": "^0.9.80-alpha.7",
"@budibase/client": "^0.9.78", "@budibase/client": "^0.9.80-alpha.7",
"@budibase/string-templates": "^0.9.78", "@budibase/string-templates": "^0.9.80-alpha.7",
"@elastic/elasticsearch": "7.10.0", "@elastic/elasticsearch": "7.10.0",
"@koa/router": "8.0.0", "@koa/router": "8.0.0",
"@sendgrid/mail": "7.1.1", "@sendgrid/mail": "7.1.1",
@ -115,7 +115,7 @@
"devDependencies": { "devDependencies": {
"@babel/core": "^7.14.3", "@babel/core": "^7.14.3",
"@babel/preset-env": "^7.14.4", "@babel/preset-env": "^7.14.4",
"@budibase/standard-components": "^0.9.78", "@budibase/standard-components": "^0.9.80-alpha.7",
"@jest/test-sequencer": "^24.8.0", "@jest/test-sequencer": "^24.8.0",
"@types/bull": "^3.15.1", "@types/bull": "^3.15.1",
"@types/jest": "^26.0.23", "@types/jest": "^26.0.23",

View File

@ -278,6 +278,7 @@ exports.search = async ctx => {
const { tableId } = ctx.params const { tableId } = ctx.params
const db = new CouchDB(appId) const db = new CouchDB(appId)
const { paginate, query, ...params } = ctx.request.body const { paginate, query, ...params } = ctx.request.body
params.version = ctx.version
params.tableId = tableId params.tableId = tableId
let response let response

View File

@ -2,16 +2,6 @@ const { SearchIndexes } = require("../../../db/utils")
const env = require("../../../environment") const env = require("../../../environment")
const fetch = require("node-fetch") const fetch = require("node-fetch")
/**
* Escapes any characters in a string which lucene searches require to be
* escaped.
* @param value The value to escape
* @returns {string}
*/
const luceneEscape = value => {
return `${value}`.replace(/[ #+\-&|!(){}\]^"~*?:\\]/g, "\\$&")
}
/** /**
* Class to build lucene query URLs. * Class to build lucene query URLs.
* Optionally takes a base lucene query object. * Optionally takes a base lucene query object.
@ -33,6 +23,12 @@ class QueryBuilder {
this.sortOrder = "ascending" this.sortOrder = "ascending"
this.sortType = "string" this.sortType = "string"
this.includeDocs = true this.includeDocs = true
this.version = null
}
setVersion(version) {
this.version = version
return this
} }
setTable(tableId) { setTable(tableId) {
@ -108,12 +104,43 @@ class QueryBuilder {
return this return this
} }
/**
* Preprocesses a value before going into a lucene search.
* Transforms strings to lowercase and wraps strings and bools in quotes.
* @param value The value to process
* @param options The preprocess options
* @returns {string|*}
*/
preprocess(value, { escape, lowercase, wrap } = {}) {
const hasVersion = !!this.version
// Determine if type needs wrapped
const originalType = typeof value
// Convert to lowercase
if (value && lowercase) {
value = value.toLowerCase ? value.toLowerCase() : value
}
// Escape characters
if (escape && originalType === "string") {
value = `${value}`.replace(/[ #+\-&|!(){}\]^"~*?:\\]/g, "\\$&")
}
// Wrap in quotes
if (hasVersion && wrap) {
value = originalType === "number" ? value : `"${value}"`
}
return value
}
buildSearchQuery() { buildSearchQuery() {
const builder = this
let query = "*:*" let query = "*:*"
const allPreProcessingOpts = { escape: true, lowercase: true, wrap: true }
function build(structure, queryFn) { function build(structure, queryFn) {
for (let [key, value] of Object.entries(structure)) { for (let [key, value] of Object.entries(structure)) {
const expression = queryFn(luceneEscape(key.replace(/ /, "_")), value) key = builder.preprocess(key.replace(/ /, "_"), {
escape: true,
})
const expression = queryFn(key, value)
if (expression == null) { if (expression == null) {
continue continue
} }
@ -124,7 +151,14 @@ class QueryBuilder {
// Construct the actual lucene search query string from JSON structure // Construct the actual lucene search query string from JSON structure
if (this.query.string) { if (this.query.string) {
build(this.query.string, (key, value) => { build(this.query.string, (key, value) => {
return value ? `${key}:${luceneEscape(value.toLowerCase())}*` : null if (!value) {
return null
}
value = builder.preprocess(value, {
escape: true,
lowercase: true,
})
return `${key}:${value}*`
}) })
} }
if (this.query.range) { if (this.query.range) {
@ -138,30 +172,37 @@ class QueryBuilder {
if (value.high == null || value.high === "") { if (value.high == null || value.high === "") {
return null return null
} }
return `${key}:[${value.low} TO ${value.high}]` const low = builder.preprocess(value.low, allPreProcessingOpts)
const high = builder.preprocess(value.high, allPreProcessingOpts)
return `${key}:[${low} TO ${high}]`
}) })
} }
if (this.query.fuzzy) { if (this.query.fuzzy) {
build(this.query.fuzzy, (key, value) => { build(this.query.fuzzy, (key, value) => {
return value ? `${key}:${luceneEscape(value.toLowerCase())}~` : null if (!value) {
return null
}
value = builder.preprocess(value, {
escape: true,
lowercase: true,
})
return `${key}:${value}~`
}) })
} }
if (this.query.equal) { if (this.query.equal) {
build(this.query.equal, (key, value) => { build(this.query.equal, (key, value) => {
const escapedValue = luceneEscape(value.toLowerCase()) if (!value) {
// have to do the or to manage straight values, or strings return null
return value }
? `(${key}:${escapedValue} OR ${key}:"${escapedValue}")` return `${key}:${builder.preprocess(value, allPreProcessingOpts)}`
: null
}) })
} }
if (this.query.notEqual) { if (this.query.notEqual) {
build(this.query.notEqual, (key, value) => { build(this.query.notEqual, (key, value) => {
const escapedValue = luceneEscape(value.toLowerCase()) if (!value) {
// have to do the or to manage straight values, or strings return null
return value }
? `(!${key}:${escapedValue} OR !${key}:"${escapedValue}")` return `!${key}:${builder.preprocess(value, allPreProcessingOpts)}`
: null
}) })
} }
if (this.query.empty) { if (this.query.empty) {
@ -250,6 +291,7 @@ const recursiveSearch = async (appId, query, params) => {
pageSize = params.limit - rows.length pageSize = params.limit - rows.length
} }
const page = await new QueryBuilder(appId, query) const page = await new QueryBuilder(appId, query)
.setVersion(params.version)
.setTable(params.tableId) .setTable(params.tableId)
.setBookmark(bookmark) .setBookmark(bookmark)
.setLimit(pageSize) .setLimit(pageSize)
@ -294,6 +336,7 @@ exports.paginatedSearch = async (appId, query, params) => {
} }
limit = Math.min(limit, 200) limit = Math.min(limit, 200)
const search = new QueryBuilder(appId, query) const search = new QueryBuilder(appId, query)
.setVersion(params.version)
.setTable(params.tableId) .setTable(params.tableId)
.setSort(params.sort) .setSort(params.sort)
.setSortOrder(params.sortOrder) .setSortOrder(params.sortOrder)

View File

@ -31,7 +31,13 @@ describe("run misc tests", () => {
describe("/version", () => { describe("/version", () => {
it("should confirm version", async () => { it("should confirm version", async () => {
const res = await request.get("/version").expect(200) const res = await request.get("/version").expect(200)
expect(res.text.split(".").length).toEqual(3) const text = res.text
if (text.includes("alpha")) {
expect(text.split(".").length).toEqual(4)
} else {
expect(text.split(".").length).toEqual(3)
}
}) })
}) })

View File

@ -12,7 +12,12 @@ module.exports = async (ctx, next) => {
// try to get the appID from the request // try to get the appID from the request
const requestAppId = getAppId(ctx) const requestAppId = getAppId(ctx)
// get app cookie if it exists // get app cookie if it exists
const appCookie = getCookie(ctx, Cookies.CurrentApp) let appCookie = null
try {
appCookie = getCookie(ctx, Cookies.CurrentApp)
} catch (err) {
clearCookie(ctx, Cookies.CurrentApp)
}
if (!appCookie && !requestAppId) { if (!appCookie && !requestAppId) {
return next() return next()
} }

View File

@ -14,7 +14,7 @@ const {
const controllers = require("./controllers") const controllers = require("./controllers")
const supertest = require("supertest") const supertest = require("supertest")
const { cleanup } = require("../../utilities/fileSystem") const { cleanup } = require("../../utilities/fileSystem")
const { Cookies } = require("@budibase/auth").constants const { Cookies, Headers } = require("@budibase/auth").constants
const { jwt } = require("@budibase/auth").auth const { jwt } = require("@budibase/auth").auth
const { StaticDatabases } = require("@budibase/auth/db") const { StaticDatabases } = require("@budibase/auth/db")
const { createASession } = require("@budibase/auth/sessions") const { createASession } = require("@budibase/auth/sessions")
@ -122,7 +122,7 @@ class TestConfiguration {
], ],
} }
if (this.appId) { if (this.appId) {
headers["x-budibase-app-id"] = this.appId headers[Headers.APP_ID] = this.appId
} }
return headers return headers
} }
@ -132,7 +132,7 @@ class TestConfiguration {
Accept: "application/json", Accept: "application/json",
} }
if (this.appId) { if (this.appId) {
headers["x-budibase-app-id"] = this.appId headers[Headers.APP_ID] = this.appId
} }
return headers return headers
} }
@ -354,7 +354,7 @@ class TestConfiguration {
`${Cookies.Auth}=${authToken}`, `${Cookies.Auth}=${authToken}`,
`${Cookies.CurrentApp}=${appToken}`, `${Cookies.CurrentApp}=${appToken}`,
], ],
"x-budibase-app-id": this.appId, [Headers.APP_ID]: this.appId,
} }
} }
} }

View File

@ -3,13 +3,14 @@ const env = require("../environment")
const { checkSlashesInUrl } = require("./index") const { checkSlashesInUrl } = require("./index")
const { getDeployedAppID } = require("@budibase/auth/db") const { getDeployedAppID } = require("@budibase/auth/db")
const { updateAppRole, getGlobalUser } = require("./global") const { updateAppRole, getGlobalUser } = require("./global")
const { Headers } = require("@budibase/auth/constants")
function request(ctx, request, noApiKey) { function request(ctx, request, noApiKey) {
if (!request.headers) { if (!request.headers) {
request.headers = {} request.headers = {}
} }
if (!noApiKey) { if (!noApiKey) {
request.headers["x-budibase-api-key"] = env.INTERNAL_API_KEY request.headers[Headers.API_KEY] = env.INTERNAL_API_KEY
} }
if (request.body && Object.keys(request.body).length > 0) { if (request.body && Object.keys(request.body).length > 0) {
request.headers["Content-Type"] = "application/json" request.headers["Content-Type"] = "application/json"

View File

@ -29,12 +29,12 @@
"keywords": [ "keywords": [
"svelte" "svelte"
], ],
"version": "0.9.78", "version": "0.9.80-alpha.7",
"license": "MIT", "license": "MIT",
"gitHead": "d1836a898cab3f8ab80ee6d8f42be1a9eed7dcdc", "gitHead": "d1836a898cab3f8ab80ee6d8f42be1a9eed7dcdc",
"dependencies": { "dependencies": {
"@budibase/bbui": "^0.9.80-alpha.7",
"@spectrum-css/card": "^3.0.3", "@spectrum-css/card": "^3.0.3",
"@budibase/bbui": "^0.9.78",
"@spectrum-css/link": "^3.1.3", "@spectrum-css/link": "^3.1.3",
"@spectrum-css/page": "^3.0.1", "@spectrum-css/page": "^3.0.1",
"@spectrum-css/typography": "^3.0.2", "@spectrum-css/typography": "^3.0.2",

View File

@ -15,10 +15,16 @@ export const buildLuceneQuery = filter => {
if (Array.isArray(filter)) { if (Array.isArray(filter)) {
filter.forEach(expression => { filter.forEach(expression => {
let { operator, field, type, value } = expression let { operator, field, type, value } = expression
// Ensure date fields are transformed into ISO strings // Parse all values into correct types
if (type === "datetime" && value) { if (type === "datetime" && value) {
value = new Date(value).toISOString() value = new Date(value).toISOString()
} }
if (type === "number") {
value = parseFloat(value)
}
if (type === "boolean") {
value = value?.toLowerCase() === "true"
}
if (operator.startsWith("range")) { if (operator.startsWith("range")) {
if (!query.range[field]) { if (!query.range[field]) {
query.range[field] = { query.range[field] = {
@ -42,10 +48,10 @@ export const buildLuceneQuery = filter => {
// Transform boolean filters to cope with null. // Transform boolean filters to cope with null.
// "equals false" needs to be "not equals true" // "equals false" needs to be "not equals true"
// "not equals false" needs to be "equals true" // "not equals false" needs to be "equals true"
if (operator === "equal" && value === "false") { if (operator === "equal" && value === false) {
query.notEqual[field] = "true" query.notEqual[field] = true
} else if (operator === "notEqual" && value === "false") { } else if (operator === "notEqual" && value === false) {
query.equal[field] = "true" query.equal[field] = true
} else { } else {
query[operator][field] = value query[operator][field] = value
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "@budibase/string-templates", "name": "@budibase/string-templates",
"version": "0.9.78", "version": "0.9.80-alpha.7",
"description": "Handlebars wrapper for Budibase templating.", "description": "Handlebars wrapper for Budibase templating.",
"main": "src/index.cjs", "main": "src/index.cjs",
"module": "dist/bundle.mjs", "module": "dist/bundle.mjs",

View File

@ -1,7 +1,7 @@
{ {
"name": "@budibase/worker", "name": "@budibase/worker",
"email": "hi@budibase.com", "email": "hi@budibase.com",
"version": "0.9.78", "version": "0.9.80-alpha.7",
"description": "Budibase background service", "description": "Budibase background service",
"main": "src/index.js", "main": "src/index.js",
"repository": { "repository": {
@ -21,9 +21,10 @@
"author": "Budibase", "author": "Budibase",
"license": "AGPL-3.0-or-later", "license": "AGPL-3.0-or-later",
"dependencies": { "dependencies": {
"@budibase/auth": "^0.9.78", "@budibase/auth": "^0.9.80-alpha.7",
"@budibase/string-templates": "^0.9.78", "@budibase/string-templates": "^0.9.80-alpha.7",
"@koa/router": "^8.0.0", "@koa/router": "^8.0.0",
"@techpass/passport-openidconnect": "^0.3.0",
"aws-sdk": "^2.811.0", "aws-sdk": "^2.811.0",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
@ -39,7 +40,6 @@
"koa-static": "^5.0.0", "koa-static": "^5.0.0",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"nodemailer": "^6.5.0", "nodemailer": "^6.5.0",
"@techpass/passport-openidconnect": "^0.3.0",
"passport-google-oauth": "^2.0.0", "passport-google-oauth": "^2.0.0",
"passport-jwt": "^4.0.0", "passport-jwt": "^4.0.0",
"passport-local": "^1.0.0", "passport-local": "^1.0.0",

View File

@ -144,7 +144,9 @@ async function oidcStrategyFactory(ctx, configId) {
const chosenConfig = config.configs.filter(c => c.uuid === configId)[0] const chosenConfig = config.configs.filter(c => c.uuid === configId)[0]
const callbackUrl = `${ctx.protocol}://${ctx.host}/api/admin/auth/oidc/callback` // require https callback in production
const protocol = process.env.NODE_ENV === "production" ? "https" : "http"
const callbackUrl = `${protocol}://${ctx.host}/api/admin/auth/oidc/callback`
return oidc.strategyFactory(chosenConfig, callbackUrl) return oidc.strategyFactory(chosenConfig, callbackUrl)
} }

View File

@ -149,16 +149,24 @@ exports.publicSettings = async function (ctx) {
config = publicConfig config = publicConfig
} }
config.config.google = !googleConfig // google button flag
? !!googleConfig if (googleConfig && googleConfig.config) {
: !googleConfig.config.activated const googleActivated =
? false googleConfig.config.activated == undefined || // activated by default for configs pre-activated flag
: true googleConfig.config.activated
config.config.oidc = !oidcConfig config.config.google = googleActivated
? !!oidcConfig } else {
: !oidcConfig.config.configs[0].activated config.config.google = false
? false }
: true
// oidc button flag
if (oidcConfig && oidcConfig.config) {
const oidcActivated = oidcConfig.config.configs[0].activated
config.config.oidc = oidcActivated
} else {
config.config.oidc = false
}
ctx.body = config ctx.body = config
} catch (err) { } catch (err) {
ctx.throw(err.status, err) ctx.throw(err.status, err)