1
0
Fork 0
mirror of synced 2024-06-03 02:55:14 +12:00
budibase/packages/server/src/tests/utilities/TestConfiguration.js

411 lines
10 KiB
JavaScript
Raw Normal View History

const { BUILTIN_ROLE_IDS } = require("@budibase/auth/roles")
const env = require("../../environment")
2021-03-04 07:41:49 +13:00
const {
basicTable,
basicRow,
basicRole,
basicAutomation,
2021-03-04 23:05:50 +13:00
basicDatasource,
basicQuery,
2021-03-09 03:49:19 +13:00
basicScreen,
basicLayout,
basicWebhook,
TENANT_ID,
2021-03-04 07:41:49 +13:00
} = require("./structures")
2021-03-04 23:05:50 +13:00
const controllers = require("./controllers")
const supertest = require("supertest")
const { cleanup } = require("../../utilities/fileSystem")
2021-07-24 02:29:14 +12:00
const { Cookies, Headers } = require("@budibase/auth").constants
2021-04-24 01:58:06 +12:00
const { jwt } = require("@budibase/auth").auth
const auth = require("@budibase/auth")
const { getGlobalDB } = require("@budibase/auth/tenancy")
2021-07-08 11:30:55 +12:00
const { createASession } = require("@budibase/auth/sessions")
const { user: userCache } = require("@budibase/auth/cache")
const CouchDB = require("../../db")
auth.init(CouchDB)
const GLOBAL_USER_ID = "us_uuid1"
const EMAIL = "babs@babs.com"
class TestConfiguration {
constructor(openServer = true) {
if (openServer) {
// use a random port because it doesn't matter
env.PORT = 0
this.server = require("../../app")
// we need the request for logging in, involves cookies, hard to fake
this.request = supertest(this.server)
}
this.appId = null
this.allApps = []
}
getRequest() {
return this.request
}
getAppId() {
return this.appId
}
async _req(config, params, controlFunc) {
const request = {}
// fake cookies, we don't need them
request.cookies = { set: () => {}, get: () => {} }
request.config = { jwtSecret: env.JWT_SECRET }
request.appId = this.appId
request.user = { appId: this.appId, tenantId: TENANT_ID }
request.query = {}
request.request = {
body: config,
}
if (params) {
request.params = params
}
await controlFunc(request)
return request.body
}
async globalUser({
id = GLOBAL_USER_ID,
builder = true,
email = EMAIL,
roles,
} = {}) {
const db = getGlobalDB(TENANT_ID)
let existing
try {
existing = await db.get(id)
} catch (err) {
existing = { email }
}
const user = {
_id: id,
...existing,
2021-07-08 11:30:55 +12:00
roles: roles || {},
tenantId: TENANT_ID,
}
await createASession(id, { sessionId: "sessionid", tenantId: TENANT_ID })
if (builder) {
user.builder = { global: true }
} else {
user.builder = { global: false }
}
2021-05-20 03:24:20 +12:00
const resp = await db.put(user)
return {
_rev: resp._rev,
...user,
}
}
async init(appName = "test_application") {
await this.globalUser()
return this.createApp(appName)
}
end() {
if (!this) {
return
}
if (this.server) {
this.server.close()
}
2021-05-17 08:25:37 +12:00
cleanup(this.allApps.map(app => app.appId))
}
defaultHeaders() {
const auth = {
userId: GLOBAL_USER_ID,
2021-07-08 11:30:55 +12:00
sessionId: "sessionid",
tenantId: TENANT_ID,
}
const app = {
roleId: BUILTIN_ROLE_IDS.ADMIN,
appId: this.appId,
}
const authToken = jwt.sign(auth, env.JWT_SECRET)
const appToken = jwt.sign(app, env.JWT_SECRET)
const headers = {
Accept: "application/json",
Cookie: [
`${Cookies.Auth}=${authToken}`,
`${Cookies.CurrentApp}=${appToken}`,
],
}
if (this.appId) {
2021-07-24 02:29:14 +12:00
headers[Headers.APP_ID] = this.appId
}
return headers
}
publicHeaders({ prodApp = true } = {}) {
const appId = prodApp ? this.prodAppId : this.appId
const headers = {
Accept: "application/json",
}
2021-10-27 04:21:26 +13:00
if (appId) {
headers[Headers.APP_ID] = appId
}
return headers
}
async roleHeaders({
email = EMAIL,
roleId = BUILTIN_ROLE_IDS.ADMIN,
builder = false,
prodApp = true,
} = {}) {
return this.login({ email, roleId, builder, prodApp })
2021-03-09 03:49:19 +13:00
}
async createApp(appName) {
// create dev app
2021-03-04 23:05:50 +13:00
this.app = await this._req({ name: appName }, null, controllers.app.create)
2021-05-17 08:25:37 +12:00
this.appId = this.app.appId
// create production app
this.prodApp = await this.deploy()
this.prodAppId = this.prodApp.appId
this.allApps.push(this.prodApp)
this.allApps.push(this.app)
return this.app
}
async deploy() {
const deployment = await this._req(null, null, controllers.deploy.deployApp)
const prodAppId = deployment.appId.replace("_dev", "")
const appPackage = await this._req(
null,
{ appId: prodAppId },
controllers.app.fetchAppPackage
)
return appPackage.application
}
async updateTable(config = null) {
config = config || basicTable()
2021-03-04 23:05:50 +13:00
this.table = await this._req(config, null, controllers.table.save)
return this.table
}
async createTable(config = null) {
if (config != null && config._id) {
delete config._id
}
return this.updateTable(config)
}
2021-03-05 03:36:59 +13:00
async getTable(tableId = null) {
tableId = tableId || this.table._id
return this._req(null, { id: tableId }, controllers.table.find)
}
async createLinkedTable(relationshipType = null, links = ["link"]) {
2021-03-05 02:07:33 +13:00
if (!this.table) {
throw "Must have created a table first."
}
const tableConfig = basicTable()
tableConfig.primaryDisplay = "name"
for (let link of links) {
tableConfig.schema[link] = {
type: "link",
fieldName: link,
tableId: this.table._id,
name: link,
}
if (relationshipType) {
tableConfig.schema[link].relationshipType = relationshipType
}
}
2021-03-05 02:07:33 +13:00
const linkedTable = await this.createTable(tableConfig)
this.linkedTable = linkedTable
return linkedTable
}
async createAttachmentTable() {
const table = basicTable()
table.schema.attachment = {
type: "attachment",
}
return this.createTable(table)
}
async createRow(config = null) {
if (!this.table) {
throw "Test requires table to be configured."
}
const tableId = (config && config.tableId) || this.table._id
config = config || basicRow(tableId)
return this._req(config, { tableId }, controllers.row.save)
}
async getRow(tableId, rowId) {
return this._req(null, { tableId, rowId }, controllers.row.find)
}
async getRows(tableId) {
if (!tableId && this.table) {
tableId = this.table._id
}
2021-06-18 03:35:58 +12:00
return this._req(null, { tableId }, controllers.row.fetch)
}
async createRole(config = null) {
config = config || basicRole()
2021-03-04 23:05:50 +13:00
return this._req(config, null, controllers.role.save)
}
async addPermission(roleId, resourceId, level = "read") {
return this._req(
null,
{
roleId,
resourceId,
level,
},
2021-03-04 23:05:50 +13:00
controllers.perms.addPermission
)
}
async createView(config) {
if (!this.table) {
throw "Test requires table to be configured."
}
const view = config || {
map: "function(doc) { emit(doc[doc.key], doc._id); } ",
tableId: this.table._id,
name: "ViewTest",
}
2021-03-04 23:05:50 +13:00
return this._req(view, null, controllers.view.save)
}
2021-03-04 07:41:49 +13:00
async createAutomation(config) {
config = config || basicAutomation()
if (config._rev) {
delete config._rev
}
this.automation = (
2021-03-04 23:05:50 +13:00
await this._req(config, null, controllers.automation.create)
2021-03-04 07:41:49 +13:00
).automation
return this.automation
}
async getAllAutomations() {
2021-03-04 23:05:50 +13:00
return this._req(null, null, controllers.automation.fetch)
2021-03-04 07:41:49 +13:00
}
2021-03-04 23:05:50 +13:00
async deleteAutomation(automation = null) {
2021-03-04 07:41:49 +13:00
automation = automation || this.automation
if (!automation) {
return
}
return this._req(
null,
{ id: automation._id, rev: automation._rev },
2021-03-04 23:05:50 +13:00
controllers.automation.destroy
2021-03-04 07:41:49 +13:00
)
}
2021-03-04 23:05:50 +13:00
async createDatasource(config = null) {
config = config || basicDatasource()
2021-10-28 01:10:46 +13:00
const response = await this._req(config, null, controllers.datasource.save)
this.datasource = response.datasource
2021-03-04 23:05:50 +13:00
return this.datasource
}
async updateDatasource(datasource) {
const response = await this._req(
datasource,
{ datasourceId: datasource._id },
controllers.datasource.update
)
this.datasource = response.datasource
return this.datasource
}
2021-03-04 23:05:50 +13:00
async createQuery(config = null) {
if (!this.datasource && !config) {
throw "No data source created for query."
}
config = config || basicQuery(this.datasource._id)
return this._req(config, null, controllers.query.save)
}
2021-03-09 03:49:19 +13:00
async createScreen(config = null) {
config = config || basicScreen()
return this._req(config, null, controllers.screen.save)
}
async createWebhook(config = null) {
if (!this.automation) {
throw "Must create an automation before creating webhook."
}
config = config || basicWebhook(this.automation._id)
return (await this._req(config, null, controllers.webhook.save)).webhook
}
async createLayout(config = null) {
config = config || basicLayout()
return await this._req(config, null, controllers.layout.save)
}
async createUser(id = null, email = EMAIL) {
const globalId = !id ? `us_${Math.random()}` : `us_${id}`
const resp = await this.globalUser({ id: globalId, email })
2021-07-08 11:30:55 +12:00
await userCache.invalidateUser(globalId)
return {
2021-05-20 03:24:20 +12:00
...resp,
globalId,
}
}
async login({ roleId, userId, builder, prodApp = false } = {}) {
const appId = prodApp ? this.prodAppId : this.appId
userId = !userId ? `us_uuid1` : userId
if (!this.request) {
throw "Server has not been opened, cannot login."
}
// make sure the user exists in the global DB
if (roleId !== BUILTIN_ROLE_IDS.PUBLIC) {
await this.globalUser({
userId,
builder,
roles: { [this.prodAppId]: roleId },
2021-07-08 11:30:55 +12:00
})
}
await createASession(userId, {
sessionId: "sessionid",
tenantId: TENANT_ID,
})
// have to fake this
const auth = {
userId,
2021-07-08 11:30:55 +12:00
sessionId: "sessionid",
tenantId: TENANT_ID,
}
const app = {
roleId: roleId,
appId,
}
const authToken = jwt.sign(auth, env.JWT_SECRET)
const appToken = jwt.sign(app, env.JWT_SECRET)
// returning necessary request headers
2021-07-08 11:30:55 +12:00
await userCache.invalidateUser(userId)
return {
Accept: "application/json",
Cookie: [
`${Cookies.Auth}=${authToken}`,
`${Cookies.CurrentApp}=${appToken}`,
],
[Headers.APP_ID]: appId,
}
}
}
module.exports = TestConfiguration