Merge pull request #1940 from Budibase/ak-fixes

Fixes for some recent issues
This commit is contained in:
Andrew Kingston 2021-07-07 11:44:39 +01:00 committed by GitHub
commit 6a0acffe61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 292 additions and 84 deletions

View File

@ -147,7 +147,7 @@ exports.getRole = async (appId, roleId) => {
*/ */
async function getAllUserRoles(appId, userRoleId) { async function getAllUserRoles(appId, userRoleId) {
if (!userRoleId) { if (!userRoleId) {
return [BUILTIN_IDS.PUBLIC] return [BUILTIN_IDS.BASIC]
} }
let currentRole = await exports.getRole(appId, userRoleId) let currentRole = await exports.getRole(appId, userRoleId)
let roles = currentRole ? [currentRole] : [] let roles = currentRole ? [currentRole] : []
@ -226,7 +226,7 @@ exports.getAllRoles = async appId => {
dbRole => exports.getExternalRoleID(dbRole._id) === builtinRoleId dbRole => exports.getExternalRoleID(dbRole._id) === builtinRoleId
)[0] )[0]
if (dbBuiltin == null) { if (dbBuiltin == null) {
roles.push(builtinRole) roles.push(builtinRole || builtinRoles.BASIC)
} else { } else {
// remove role and all back after combining with the builtin // remove role and all back after combining with the builtin
roles = roles.filter(role => role._id !== dbBuiltin._id) roles = roles.filter(role => role._id !== dbBuiltin._id)

View File

@ -15,8 +15,12 @@
const dispatch = createEventDispatcher() const dispatch = createEventDispatcher()
$: selected = $tab.title $: {
$: selected = dispatch("select", selected) if ($tab.title !== selected) {
selected = $tab.title
dispatch("select", selected)
}
}
let top, left, width, height let top, left, width, height
$: calculateIndicatorLength($tab) $: calculateIndicatorLength($tab)

View File

@ -0,0 +1,34 @@
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 48 48" height="48px" viewBox="0 0 48 48" width="48px" xml:space="preserve">
<g>
<g>
<path d="M9,42H3c-0.552,0-1-0.449-1-1v-3.5C2,37.224,2.224,37,2.5,37S3,37.224,3,37.5V41h6 c0.276,0,0.5,0.224,0.5,0.5S9.276,42,9,42z"/>
<path d="M45,42h-6c-0.276,0-0.5-0.224-0.5-0.5S38.724,41,39,41h6V13H3v27c0,0.276-0.224,0.5-0.5,0.5S2,40.276,2,40 V12h44v29C46,41.551,45.552,42,45,42z"/>
<g>
<path d="M45.5,13h-43C2.224,13,2,12.776,2,12.5v-5C2,6.673,2.673,6,3.5,6h41C45.327,6,46,6.673,46,7.5v5 C46,12.776,45.776,13,45.5,13z M3,12h42V7.5C45,7.224,44.775,7,44.5,7h-41C3.225,7,3,7.224,3,7.5V12z"/>
</g>
<g>
<g>
<path d="M16.5,11c-0.827,0-1.5-0.673-1.5-1.5S15.673,8,16.5,8S18,8.673,18,9.5S17.327,11,16.5,11z M16.5,9 C16.225,9,16,9.224,16,9.5s0.225,0.5,0.5,0.5S17,9.776,17,9.5S16.775,9,16.5,9z"/>
</g>
<g>
<path d="M11.5,11c-0.827,0-1.5-0.673-1.5-1.5S10.673,8,11.5,8S13,8.673,13,9.5S12.327,11,11.5,11z M11.5,9 C11.225,9,11,9.224,11,9.5s0.225,0.5,0.5,0.5S12,9.776,12,9.5S11.775,9,11.5,9z"/>
</g>
<g>
<path d="M6.5,11C5.673,11,5,10.327,5,9.5S5.673,8,6.5,8S8,8.673,8,9.5S7.327,11,6.5,11z M6.5,9 C6.225,9,6,9.224,6,9.5S6.225,10,6.5,10S7,9.776,7,9.5S6.775,9,6.5,9z"/>
</g>
</g>
</g>
<g>
<g>
<path d="M35.696,44H12.304c-0.728,0-1.313-0.284-1.605-0.779c-0.289-0.489-0.259-1.126,0.084-1.749L22.58,19.996 c0.709-1.285,2.132-1.285,2.839,0l11.799,21.477v0c0.343,0.623,0.373,1.26,0.084,1.749C37.01,43.716,36.424,44,35.696,44z M24,20 c-0.176,0-0.379,0.179-0.544,0.478L11.659,41.954c-0.168,0.306-0.205,0.582-0.101,0.758C11.667,42.895,11.938,43,12.304,43 h23.393c0.365,0,0.637-0.105,0.745-0.288c0.104-0.177,0.067-0.453-0.101-0.758v0L24.543,20.478C24.379,20.179,24.176,20,24,20z"/>
</g>
<g>
<path d="M24,36L24,36c-0.225,0-0.421-0.15-0.481-0.366C23.456,35.412,22,30.169,22,28c0-1.103,0.897-2,2-2 s2,0.897,2,2c0,2.232-1.457,7.417-1.519,7.636C24.42,35.851,24.224,36,24,36z M24,27c-0.552,0-1,0.449-1,1 c0,1.266,0.569,3.793,1.002,5.531C24.435,31.806,25,29.301,25,28C25,27.449,24.552,27,24,27z"/>
</g>
<g>
<path d="M24,41c-1.103,0-2-0.897-2-2s0.897-2,2-2s2,0.897,2,2S25.103,41,24,41z M24,38c-0.552,0-1,0.449-1,1 s0.448,1,1,1s1-0.449,1-1S24.552,38,24,38z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@ -122,6 +122,9 @@ export const getFrontendStore = () => {
save: async screen => { save: async screen => {
const creatingNewScreen = screen._id === undefined const creatingNewScreen = screen._id === undefined
const response = await api.post(`/api/screens`, screen) const response = await api.post(`/api/screens`, screen)
if (response.status !== 200) {
return
}
screen = await response.json() screen = await response.json()
await store.actions.routing.fetch() await store.actions.routing.fetch()

View File

@ -10,8 +10,10 @@
let selectedRole = {} let selectedRole = {}
let errors = [] let errors = []
let builtInRoles = ["Admin", "Power", "Basic", "Public"] let builtInRoles = ["Admin", "Power", "Basic", "Public"]
// Don't allow editing of public role
$: editableRoles = $roles.filter(role => role._id !== "PUBLIC")
$: selectedRoleId = selectedRole._id $: selectedRoleId = selectedRole._id
$: otherRoles = $roles.filter(role => role._id !== selectedRoleId) $: otherRoles = editableRoles.filter(role => role._id !== selectedRoleId)
$: isCreating = selectedRoleId == null || selectedRoleId === "" $: isCreating = selectedRoleId == null || selectedRoleId === ""
const fetchBasePermissions = async () => { const fetchBasePermissions = async () => {
@ -96,7 +98,7 @@
label="Role" label="Role"
value={selectedRoleId} value={selectedRoleId}
on:change={changeRole} on:change={changeRole}
options={$roles} options={editableRoles}
placeholder="Create new role" placeholder="Create new role"
getOptionValue={role => role._id} getOptionValue={role => role._id}
getOptionLabel={role => role.name} getOptionLabel={role => role.name}

View File

@ -5,12 +5,16 @@
import { Screen } from "builderStore/store/screenTemplates/utils/Screen" import { Screen } from "builderStore/store/screenTemplates/utils/Screen"
import { FrontendTypes } from "constants" import { FrontendTypes } from "constants"
import ConfirmDialog from "components/common/ConfirmDialog.svelte" import ConfirmDialog from "components/common/ConfirmDialog.svelte"
import { ProgressCircle, Layout, Heading, Body } from "@budibase/bbui"
import ErrorSVG from "assets/error.svg?raw"
let iframe let iframe
let layout let layout
let screen let screen
let confirmDeleteDialog let confirmDeleteDialog
let idToDelete let idToDelete
let loading = true
let error
// Create screen slot placeholder for use when a page is selected rather // Create screen slot placeholder for use when a page is selected rather
// than a screen // than a screen
@ -68,11 +72,21 @@
onMount(() => { onMount(() => {
// Initialise the app when mounted // Initialise the app when mounted
iframe.contentWindow.addEventListener( iframe.contentWindow.addEventListener(
"bb-ready", "ready",
() => refreshContent(strippedJson), () => refreshContent(strippedJson),
{ once: true } { once: true }
) )
// Catch any app errors
iframe.contentWindow.addEventListener(
"error",
event => {
loading = false
error = event.detail || "An unknown error occurred"
},
{ once: true }
)
// Add listener for events sent by cliebt library in preview // Add listener for events sent by cliebt library in preview
iframe.contentWindow.addEventListener("bb-event", event => { iframe.contentWindow.addEventListener("bb-event", event => {
const { type, data } = event.detail const { type, data } = event.detail
@ -83,8 +97,10 @@
} else if (type === "delete-component" && data.id) { } else if (type === "delete-component" && data.id) {
idToDelete = data.id idToDelete = data.id
confirmDeleteDialog.show() confirmDeleteDialog.show()
} else if (type === "preview-loaded") {
loading = false
} else { } else {
console.log(data) console.warning(`Client sent unknown event type: ${type}`)
} }
}) })
}) })
@ -99,11 +115,25 @@
</script> </script>
<div class="component-container"> <div class="component-container">
{#if loading}
<div class="center">
<ProgressCircle />
</div>
{:else if error}
<div class="center error">
<Layout justifyItems="center" gap="S">
{@html ErrorSVG}
<Heading size="L">App preview failed to load</Heading>
<Body size="S">{error}</Body>
</Layout>
</div>
{/if}
<iframe <iframe
style="height: 100%; width: 100%" style="height: 100%; width: 100%"
title="componentPreview" title="componentPreview"
bind:this={iframe} bind:this={iframe}
srcdoc={template} srcdoc={template}
class:hidden={loading || error}
/> />
</div> </div>
<ConfirmDialog <ConfirmDialog
@ -131,4 +161,32 @@
width: 100%; width: 100%;
background-color: transparent; background-color: transparent;
} }
.center {
position: absolute;
width: 100%;
height: 100%;
display: grid;
place-items: center;
z-index: 1;
}
.hidden {
opacity: 0;
}
.error :global(svg) {
fill: var(--spectrum-global-color-gray-500);
width: 80px;
height: 80px;
}
.error :global(h1),
.error :global(p) {
color: var(--spectrum-global-color-gray-800);
}
.error :global(p) {
font-style: italic;
margin-top: -0.5em;
}
.error :global(h1) {
font-weight: 400;
margin: 0;
}
</style> </style>

View File

@ -25,7 +25,9 @@ export default `
flex-direction: column; flex-direction: column;
justify-content: flex-start; justify-content: flex-start;
align-items: stretch; align-items: stretch;
box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.1); }
html.loaded {
box-shadow: 0 2px 8px -2px rgba(0, 0, 0, 0.1);
} }
body { body {
flex: 1 1 auto; flex: 1 1 auto;
@ -58,13 +60,20 @@ export default `
window["##BUDIBASE_PREVIEW_TYPE##"] = previewType window["##BUDIBASE_PREVIEW_TYPE##"] = previewType
// Initialise app // Initialise app
if (window.loadBudibase) { try {
loadBudibase() if (window.loadBudibase) {
window.loadBudibase()
document.documentElement.classList.add("loaded")
} else {
throw "The client library couldn't be loaded"
}
} catch (error) {
window.dispatchEvent(new CustomEvent("error", { detail: error }))
} }
} }
window.addEventListener("message", receiveMessage) window.addEventListener("message", receiveMessage)
window.dispatchEvent(new Event("bb-ready")) window.dispatchEvent(new Event("ready"))
</script> </script>
</head> </head>
<body/> <body/>

View File

@ -21,7 +21,7 @@
export let value = [] export let value = []
export let componentInstance export let componentInstance
let drawer let drawer
let tempValue = value let tempValue = value || []
$: numFilters = Array.isArray(tempValue) $: numFilters = Array.isArray(tempValue)
? tempValue.length ? tempValue.length
@ -31,15 +31,6 @@
$: schemaFields = Object.values(schema || {}) $: schemaFields = Object.values(schema || {})
$: internalTable = dataSource?.type === "table" $: internalTable = dataSource?.type === "table"
// Reset value if value is wrong type for the datasource.
// Lucene editor needs an array, and simple editor needs an object.
$: {
if (!Array.isArray(value)) {
tempValue = []
dispatch("change", [])
}
}
const saveFilter = async () => { const saveFilter = async () => {
dispatch("change", tempValue) dispatch("change", tempValue)
notifications.success("Filters saved.") notifications.success("Filters saved.")

View File

@ -28,12 +28,7 @@
onMount(async () => { onMount(async () => {
await organisation.init() await organisation.init()
await apps.load() await apps.load()
// Skip the portal if you only have one app loaded = true
if (!$auth.isBuilder && $apps.filter(publishedAppsOnly).length === 1) {
window.location = `/${publishedApps[0].prodId}`
} else {
loaded = true
}
}) })
const publishedAppsOnly = app => app.status === AppStatus.DEPLOYED const publishedAppsOnly = app => app.status === AppStatus.DEPLOYED

View File

@ -9,8 +9,6 @@
$redirect("../") $redirect("../")
} }
} }
$: console.log($page)
</script> </script>
{#if $auth.isAdmin} {#if $auth.isAdmin}

View File

@ -33,7 +33,7 @@
role: {}, role: {},
} }
$: defaultRoleId = $userFetch?.data?.builder?.global ? "ADMIN" : "" $: 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 role = $userFetch?.data?.roles?.[id] || defaultRoleId

View File

@ -9,7 +9,7 @@
const dispatch = createEventDispatcher() const dispatch = createEventDispatcher()
const roles = app.roles const roles = app.roles
let options = roles.map(role => role._id) let options = roles.map(role => role._id).filter(id => id !== "PUBLIC")
let selectedRole = user?.roles?.[app?._id] let selectedRole = user?.roles?.[app?._id]
async function updateUserRoles() { async function updateUserRoles() {

View File

@ -43,10 +43,9 @@ const makeApiCall = async ({ method, url, body, json = true }) => {
case 400: case 400:
return handleError(`${url}: Bad Request`) return handleError(`${url}: Bad Request`)
case 403: case 403:
// reload the page incase the token has expired notificationStore.danger(
if (!url.includes("self")) { "Your session has expired, or you don't have permission to access that data"
location.reload() )
}
return handleError(`${url}: Forbidden`) return handleError(`${url}: Forbidden`)
default: default:
if (response.status >= 200 && response.status < 400) { if (response.status >= 200 && response.status < 400) {

View File

@ -24,7 +24,12 @@ export const logIn = async ({ email, password }) => {
export const fetchSelf = async () => { export const fetchSelf = async () => {
const user = await API.get({ url: "/api/self" }) const user = await API.get({ url: "/api/self" })
if (user?._id) { if (user?._id) {
return (await enrichRows([user], TableNames.USERS))[0] if (user.roleId === "PUBLIC") {
// Don't try to enrich a public user as it will 403
return user
} else {
return (await enrichRows([user], TableNames.USERS))[0]
}
} else { } else {
return null return null
} }

View File

@ -18,6 +18,8 @@
import SettingsBar from "./preview/SettingsBar.svelte" import SettingsBar from "./preview/SettingsBar.svelte"
import SelectionIndicator from "./preview/SelectionIndicator.svelte" import SelectionIndicator from "./preview/SelectionIndicator.svelte"
import HoverIndicator from "./preview/HoverIndicator.svelte" import HoverIndicator from "./preview/HoverIndicator.svelte"
import { Layout, Heading, Body } from "@budibase/bbui"
import ErrorSVG from "../../../builder/assets/error.svg"
// Provide contexts // Provide contexts
setContext("sdk", SDK) setContext("sdk", SDK)
@ -25,12 +27,16 @@
setContext("context", createContextStore()) setContext("context", createContextStore())
let dataLoaded = false let dataLoaded = false
let permissionError = false
// Load app config // Load app config
onMount(async () => { onMount(async () => {
await initialise() await initialise()
await authStore.actions.fetchUser() await authStore.actions.fetchUser()
dataLoaded = true dataLoaded = true
if ($builderStore.inBuilder) {
builderStore.actions.notifyLoaded()
}
}) })
// Register this as a refreshable datasource so that user changes cause // Register this as a refreshable datasource so that user changes cause
@ -43,12 +49,21 @@
}, },
] ]
// Redirect to home layout if no matching route // Handle no matching route - this is likely a permission error
$: { $: {
if (dataLoaded && $routeStore.routerLoaded && !$routeStore.activeRoute) { if (dataLoaded && $routeStore.routerLoaded && !$routeStore.activeRoute) {
if ($authStore) { if ($authStore) {
routeStore.actions.navigate("/") // There is a logged in user, so handle them
if ($screenStore.screens.length) {
// Screens exist so navigate back to the home screen
const firstRoute = $screenStore.screens[0].routing?.route ?? "/"
routeStore.actions.navigate(firstRoute)
} else {
// No screens likely means the user has no permissions to view this app
permissionError = true
}
} else { } else {
// The user is not logged in, redirect them to login
const returnUrl = `${window.location.pathname}${window.location.hash}` const returnUrl = `${window.location.pathname}${window.location.hash}`
const encodedUrl = encodeURIComponent(returnUrl) const encodedUrl = encodeURIComponent(returnUrl)
window.location = `/builder/auth/login?returnUrl=${encodedUrl}` window.location = `/builder/auth/login?returnUrl=${encodedUrl}`
@ -57,36 +72,46 @@
} }
</script> </script>
{#if dataLoaded && $screenStore.activeLayout} {#if dataLoaded}
<div <div
id="spectrum-root" id="spectrum-root"
lang="en" lang="en"
dir="ltr" dir="ltr"
class="spectrum spectrum--medium spectrum--light" class="spectrum spectrum--medium spectrum--light"
> >
<Provider key="user" data={$authStore} {actions}> {#if permissionError}
<div id="app-root"> <div class="error">
{#key $screenStore.activeLayout._id} <Layout justifyItems="center" gap="S">
<Component instance={$screenStore.activeLayout.props} /> {@html ErrorSVG}
{/key} <Heading size="L">You don't have permission to use this app</Heading>
<Body size="S">Ask your administrator to grant you access</Body>
</Layout>
</div> </div>
<NotificationDisplay /> {:else if $screenStore.activeLayout}
<ConfirmationDisplay /> <Provider key="user" data={$authStore} {actions}>
<!-- Key block needs to be outside the if statement or it breaks --> <div id="app-root">
{#key $builderStore.selectedComponentId} {#key $screenStore.activeLayout._id}
<Component instance={$screenStore.activeLayout.props} />
{/key}
</div>
<NotificationDisplay />
<ConfirmationDisplay />
<!-- Key block needs to be outside the if statement or it breaks -->
{#key $builderStore.selectedComponentId}
{#if $builderStore.inBuilder}
<SettingsBar />
{/if}
{/key}
<!--
We don't want to key these by componentID as they control their own
re-mounting to avoid flashes.
-->
{#if $builderStore.inBuilder} {#if $builderStore.inBuilder}
<SettingsBar /> <SelectionIndicator />
<HoverIndicator />
{/if} {/if}
{/key} </Provider>
<!-- {/if}
We don't want to key these by componentID as they control their own
re-mounting to avoid flashes.
-->
{#if $builderStore.inBuilder}
<SelectionIndicator />
<HoverIndicator />
{/if}
</Provider>
</div> </div>
{/if} {/if}
@ -102,4 +127,31 @@
#app-root { #app-root {
position: relative; position: relative;
} }
.error {
position: absolute;
width: 100%;
height: 100%;
display: grid;
place-items: center;
z-index: 1;
text-align: center;
padding: 20px;
}
.error :global(svg) {
fill: var(--spectrum-global-color-gray-500);
width: 80px;
height: 80px;
}
.error :global(h1),
.error :global(p) {
color: var(--spectrum-global-color-gray-800);
}
.error :global(p) {
font-style: italic;
margin-top: -0.5em;
}
.error :global(h1) {
font-weight: 400;
}
</style> </style>

View File

@ -1,7 +1,7 @@
import { writable, derived } from "svelte/store" import { writable, derived } from "svelte/store"
import Manifest from "@budibase/standard-components/manifest.json" import Manifest from "@budibase/standard-components/manifest.json"
const dispatchEvent = (type, data) => { const dispatchEvent = (type, data = {}) => {
window.dispatchEvent( window.dispatchEvent(
new CustomEvent("bb-event", { new CustomEvent("bb-event", {
detail: { type, data }, detail: { type, data },
@ -64,6 +64,9 @@ const createBuilderStore = () => {
deleteComponent: id => { deleteComponent: id => {
dispatchEvent("delete-component", { id }) dispatchEvent("delete-component", { id })
}, },
notifyLoaded: () => {
dispatchEvent("preview-loaded")
},
} }
return { return {
...writableStore, ...writableStore,

View File

@ -11,17 +11,20 @@ const createScreenStore = () => {
const store = derived( const store = derived(
[config, routeStore, builderStore], [config, routeStore, builderStore],
([$config, $routeStore, $builderStore]) => { ([$config, $routeStore, $builderStore]) => {
let activeLayout let activeLayout, activeScreen
let activeScreen let layouts, screens
if ($builderStore.inBuilder) { if ($builderStore.inBuilder) {
// Use builder defined definitions if inside the builder preview // Use builder defined definitions if inside the builder preview
activeLayout = $builderStore.layout activeLayout = $builderStore.layout
activeScreen = $builderStore.screen activeScreen = $builderStore.screen
layouts = [activeLayout]
screens = [activeScreen]
} else { } else {
activeLayout = { props: { _component: "screenslot" } } activeLayout = { props: { _component: "screenslot" } }
// Find the correct screen by matching the current route // Find the correct screen by matching the current route
const { screens, layouts } = $config screens = $config.screens
layouts = $config.layouts
if ($routeStore.activeRoute) { if ($routeStore.activeRoute) {
activeScreen = screens.find( activeScreen = screens.find(
screen => screen._id === $routeStore.activeRoute.screenId screen => screen._id === $routeStore.activeRoute.screenId
@ -33,7 +36,7 @@ const createScreenStore = () => {
) )
} }
} }
return { activeLayout, activeScreen } return { layouts, screens, activeLayout, activeScreen }
} }
) )

View File

@ -34,13 +34,55 @@
*:after { *:after {
box-sizing: border-box; box-sizing: border-box;
} }
#error {
position: absolute;
top: 0;
left: 0;
height: 100vh;
width: 100vw;
display: none;
font-family: "Source Sans Pro", sans-serif;
flex-direction: column;
justify-content: center;
align-items: center;
background: #222;
text-align: center;
padding: 2rem;
gap: 2rem;
}
#error h1,
#error h2 {
margin: 0;
}
#error h1 {
color: #ccc;
font-size: 3rem;
font-weight: 600;
}
#error h2 {
color: #888;
font-weight: 400;
}
</style> </style>
</svelte:head> </svelte:head>
<body id="app"> <body id="app">
<div id="error">
<h1>There was an error loading your app</h1>
<h2>
The Budibase client library could not be loaded. Try republishing your
app.
</h2>
</div>
<script type="application/javascript" src={clientLibPath}> <script type="application/javascript" src={clientLibPath}>
</script> </script>
<script type="application/javascript"> <script type="application/javascript">
loadBudibase() if (window.loadBudibase) {
window.loadBudibase()
} else {
console.error("Failed to load the Budibase client")
document.getElementById("error").style.display = "flex"
}
</script> </script>
</body> </body>

View File

@ -9,9 +9,13 @@ jest.mock("../../../utilities/redis", () => ({
updateLock: jest.fn(), updateLock: jest.fn(),
setDebounce: jest.fn(), setDebounce: jest.fn(),
checkDebounce: jest.fn(), checkDebounce: jest.fn(),
shutdown: jest.fn(),
})) }))
const { clearAllApps, checkBuilderEndpoint } = require("./utilities/TestFunctions") const {
clearAllApps,
checkBuilderEndpoint,
} = require("./utilities/TestFunctions")
const setup = require("./utilities") const setup = require("./utilities")
const { AppStatus } = require("../../../db/utils") const { AppStatus } = require("../../../db/utils")
@ -32,7 +36,7 @@ describe("/applications", () => {
.post("/api/applications") .post("/api/applications")
.send({ name: "My App" }) .send({ name: "My App" })
.set(config.defaultHeaders()) .set(config.defaultHeaders())
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(res.body._id).toBeDefined() expect(res.body._id).toBeDefined()
}) })
@ -42,7 +46,7 @@ describe("/applications", () => {
config, config,
method: "POST", method: "POST",
url: `/api/applications`, url: `/api/applications`,
body: { name: "My App" } body: { name: "My App" },
}) })
}) })
}) })
@ -55,7 +59,7 @@ describe("/applications", () => {
const res = await request const res = await request
.get(`/api/applications?status=${AppStatus.DEV}`) .get(`/api/applications?status=${AppStatus.DEV}`)
.set(config.defaultHeaders()) .set(config.defaultHeaders())
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
// two created apps + the inited app // two created apps + the inited app
@ -68,7 +72,7 @@ describe("/applications", () => {
const res = await request const res = await request
.get(`/api/applications/${config.getAppId()}/definition`) .get(`/api/applications/${config.getAppId()}/definition`)
.set(config.defaultHeaders()) .set(config.defaultHeaders())
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
// should have empty packages // should have empty packages
expect(res.body.screens.length).toEqual(1) expect(res.body.screens.length).toEqual(1)
@ -81,7 +85,7 @@ describe("/applications", () => {
const res = await request const res = await request
.get(`/api/applications/${config.getAppId()}/appPackage`) .get(`/api/applications/${config.getAppId()}/appPackage`)
.set(config.defaultHeaders()) .set(config.defaultHeaders())
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(res.body.application).toBeDefined() expect(res.body.application).toBeDefined()
expect(res.body.screens.length).toEqual(1) expect(res.body.screens.length).toEqual(1)
@ -94,10 +98,10 @@ describe("/applications", () => {
const res = await request const res = await request
.put(`/api/applications/${config.getAppId()}`) .put(`/api/applications/${config.getAppId()}`)
.send({ .send({
name: "TEST_APP" name: "TEST_APP",
}) })
.set(config.defaultHeaders()) .set(config.defaultHeaders())
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(res.body.rev).toBeDefined() expect(res.body.rev).toBeDefined()
}) })
@ -113,14 +117,14 @@ describe("/applications", () => {
name: "UPDATED_NAME", name: "UPDATED_NAME",
}) })
.set(headers) .set(headers)
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(res.body.rev).toBeDefined() expect(res.body.rev).toBeDefined()
// retrieve the app to check it // retrieve the app to check it
const getRes = await request const getRes = await request
.get(`/api/applications/${config.getAppId()}/appPackage`) .get(`/api/applications/${config.getAppId()}/appPackage`)
.set(headers) .set(headers)
.expect('Content-Type', /json/) .expect("Content-Type", /json/)
.expect(200) .expect(200)
expect(getRes.body.application.updatedAt).toBeDefined() expect(getRes.body.application.updatedAt).toBeDefined()
}) })

View File

@ -45,10 +45,10 @@ module.exports = async (ctx, next) => {
updateCookie = true updateCookie = true
appId = requestAppId appId = requestAppId
// retrieving global user gets the right role // retrieving global user gets the right role
roleId = globalUser.roleId || BUILTIN_ROLE_IDS.PUBLIC roleId = globalUser.roleId || BUILTIN_ROLE_IDS.BASIC
} else if (appCookie != null) { } else if (appCookie != null) {
appId = appCookie.appId appId = appCookie.appId
roleId = appCookie.roleId || BUILTIN_ROLE_IDS.PUBLIC roleId = appCookie.roleId || BUILTIN_ROLE_IDS.BASIC
} }
// nothing more to do // nothing more to do
if (!appId) { if (!appId) {

View File

@ -238,7 +238,10 @@ exports.readFileSync = (filepath, options = "utf8") => {
*/ */
exports.cleanup = appIds => { exports.cleanup = appIds => {
for (let appId of appIds) { for (let appId of appIds) {
fs.rmdirSync(join(budibaseTempDir(), appId), { recursive: true }) const path = join(budibaseTempDir(), appId)
if (fs.existsSync(path)) {
fs.rmdirSync(path, { recursive: true })
}
} }
} }

View File

@ -19,7 +19,7 @@ exports.updateAppRole = (appId, user) => {
if (!user.roleId && user.builder && user.builder.global) { if (!user.roleId && user.builder && user.builder.global) {
user.roleId = BUILTIN_ROLE_IDS.ADMIN user.roleId = BUILTIN_ROLE_IDS.ADMIN
} else if (!user.roleId) { } else if (!user.roleId) {
user.roleId = BUILTIN_ROLE_IDS.PUBLIC user.roleId = BUILTIN_ROLE_IDS.BASIC
} }
delete user.roles delete user.roles
return user return user

View File

@ -73,13 +73,13 @@
{ {
"label": "Column", "label": "Column",
"value": "column", "value": "column",
"barIcon": "ViewRow", "barIcon": "ViewColumn",
"barTitle": "Column layout" "barTitle": "Column layout"
}, },
{ {
"label": "Row", "label": "Row",
"value": "row", "value": "row",
"barIcon": "ViewColumn", "barIcon": "ViewRow",
"barTitle": "Row layout" "barTitle": "Row layout"
} }
], ],

View File

@ -13,9 +13,12 @@ export const buildLuceneQuery = filter => {
notEmpty: {}, notEmpty: {},
} }
if (Array.isArray(filter)) { if (Array.isArray(filter)) {
// Build up proper range filters
filter.forEach(expression => { filter.forEach(expression => {
const { operator, field, type, value } = expression let { operator, field, type, value } = expression
// Ensure date fields are transformed into ISO strings
if (type === "datetime" && value) {
value = new Date(value).toISOString()
}
if (operator.startsWith("range")) { if (operator.startsWith("range")) {
if (!query.range[field]) { if (!query.range[field]) {
query.range[field] = { query.range[field] = {