1
0
Fork 0
mirror of synced 2024-06-01 18:20:18 +12:00
budibase/packages/auth/src/db/utils.js

262 lines
7.7 KiB
JavaScript
Raw Normal View History

2021-04-19 22:34:07 +12:00
const { newid } = require("../hashing")
2021-05-13 22:06:08 +12:00
const Replication = require("./Replication")
2021-05-15 03:31:07 +12:00
const { getCouch } = require("./index")
2021-04-19 22:34:07 +12:00
const UNICODE_MAX = "\ufff0"
const SEPARATOR = "_"
exports.ViewNames = {
USER_BY_EMAIL: "by_email",
}
2021-04-07 22:33:16 +12:00
exports.StaticDatabases = {
GLOBAL: {
name: "global-db",
2021-04-07 22:33:16 +12:00
},
2021-05-17 08:25:37 +12:00
DEPLOYMENTS: {
name: "deployments",
},
2021-04-07 22:33:16 +12:00
}
const DocumentTypes = {
USER: "us",
2021-04-19 22:34:07 +12:00
GROUP: "group",
2021-04-21 05:14:36 +12:00
CONFIG: "config",
TEMPLATE: "template",
APP: "app",
APP_DEV: "app_dev",
2021-05-17 08:25:37 +12:00
APP_METADATA: "app_metadata",
ROLE: "role",
2021-04-07 22:33:16 +12:00
}
exports.DocumentTypes = DocumentTypes
exports.APP_PREFIX = DocumentTypes.APP + SEPARATOR
exports.APP_DEV_PREFIX = DocumentTypes.APP_DEV + SEPARATOR
exports.SEPARATOR = SEPARATOR
/**
* If creating DB allDocs/query params with only a single top level ID this can be used, this
* is usually the case as most of our docs are top level e.g. tables, automations, users and so on.
* More complex cases such as link docs and rows which have multiple levels of IDs that their
* ID consists of need their own functions to build the allDocs parameters.
* @param {string} docType The type of document which input params are being built for, e.g. user,
* link, app, table and so on.
* @param {string|null} docId The ID of the document minus its type - this is only needed if looking
* for a singular document.
* @param {object} otherProps Add any other properties onto the request, e.g. include_docs.
* @returns {object} Parameters which can then be used with an allDocs request.
*/
function getDocParams(docType, docId = null, otherProps = {}) {
if (docId == null) {
docId = ""
}
return {
...otherProps,
startkey: `${docType}${SEPARATOR}${docId}`,
endkey: `${docType}${SEPARATOR}${docId}${UNICODE_MAX}`,
}
}
2021-04-19 22:34:07 +12:00
/**
* Generates a new group ID.
* @returns {string} The new group ID which the group doc can be stored under.
*/
exports.generateGroupID = () => {
return `${DocumentTypes.GROUP}${SEPARATOR}${newid()}`
}
2021-04-07 22:33:16 +12:00
/**
2021-04-20 03:16:46 +12:00
* Gets parameters for retrieving groups.
*/
exports.getGroupParams = (id = "", otherProps = {}) => {
return {
...otherProps,
startkey: `${DocumentTypes.GROUP}${SEPARATOR}${id}`,
endkey: `${DocumentTypes.GROUP}${SEPARATOR}${id}${UNICODE_MAX}`,
}
}
/**
* Generates a new global user ID.
* @returns {string} The new user ID which the user doc can be stored under.
*/
2021-05-04 22:32:22 +12:00
exports.generateGlobalUserID = id => {
2021-04-22 08:08:04 +12:00
return `${DocumentTypes.USER}${SEPARATOR}${id || newid()}`
}
2021-04-20 03:16:46 +12:00
/**
* Gets parameters for retrieving users.
2021-04-07 22:33:16 +12:00
*/
exports.getGlobalUserParams = (globalId, otherProps = {}) => {
if (!globalId) {
globalId = ""
}
2021-04-07 22:33:16 +12:00
return {
...otherProps,
startkey: `${DocumentTypes.USER}${SEPARATOR}${globalId}`,
endkey: `${DocumentTypes.USER}${SEPARATOR}${globalId}${UNICODE_MAX}`,
2021-04-07 22:33:16 +12:00
}
}
/**
* Generates a template ID.
* @param ownerId The owner/user of the template, this could be global or a group level.
*/
2021-05-04 22:32:22 +12:00
exports.generateTemplateID = ownerId => {
return `${DocumentTypes.TEMPLATE}${SEPARATOR}${ownerId}${SEPARATOR}${newid()}`
}
/**
* Gets parameters for retrieving templates. Owner ID must be specified, either global or a group level.
*/
exports.getTemplateParams = (ownerId, templateId, otherProps = {}) => {
if (!templateId) {
templateId = ""
}
2021-04-22 05:15:57 +12:00
let final
if (templateId) {
final = templateId
} else {
final = `${DocumentTypes.TEMPLATE}${SEPARATOR}${ownerId}${SEPARATOR}`
}
2021-04-07 22:33:16 +12:00
return {
...otherProps,
startkey: final,
endkey: `${final}${UNICODE_MAX}`,
2021-04-07 22:33:16 +12:00
}
}
2021-04-21 05:14:36 +12:00
/**
* Generates a new role ID.
* @returns {string} The new role ID which the role doc can be stored under.
*/
exports.generateRoleID = id => {
return `${DocumentTypes.ROLE}${SEPARATOR}${id || newid()}`
}
/**
* Gets parameters for retrieving a role, this is a utility function for the getDocParams function.
*/
exports.getRoleParams = (roleId = null, otherProps = {}) => {
return getDocParams(DocumentTypes.ROLE, roleId, otherProps)
}
/**
* Convert a development app ID to a deployed app ID.
*/
exports.getDeployedAppID = appId => {
// if dev, convert it
if (appId.startsWith(exports.APP_DEV_PREFIX)) {
const id = appId.split(exports.APP_DEV_PREFIX)[1]
return `${exports.APP_PREFIX}${id}`
}
return appId
}
2021-05-15 03:31:07 +12:00
/**
* Lots of different points in the system need to find the full list of apps, this will
* enumerate the entire CouchDB cluster and get the list of databases (every app).
* NOTE: this operation is fine in self hosting, but cannot be used when hosting many
* different users/companies apps as there is no security around it - all apps are returned.
* @return {Promise<object[]>} returns the app information document stored in each app database.
*/
exports.getAllApps = async (devApps = false) => {
const CouchDB = getCouch()
let allDbs = await CouchDB.allDbs()
2021-05-15 03:32:51 +12:00
const appDbNames = allDbs.filter(dbName =>
dbName.startsWith(exports.APP_PREFIX)
)
2021-05-17 08:29:07 +12:00
const appPromises = appDbNames.map(db => new CouchDB(db).get(DocumentTypes.APP_METADATA))
2021-05-15 03:31:07 +12:00
if (appPromises.length === 0) {
return []
} else {
const response = await Promise.allSettled(appPromises)
const apps = response
.filter(result => result.status === "fulfilled")
.map(({ value }) => value)
return apps.filter(app => {
if (devApps) {
2021-05-17 08:29:07 +12:00
return app.appId.startsWith(exports.APP_DEV_PREFIX)
2021-05-15 03:31:07 +12:00
}
2021-05-17 08:29:07 +12:00
return !app.appId.startsWith(exports.APP_DEV_PREFIX)
2021-05-15 03:31:07 +12:00
})
}
}
2021-04-21 05:14:36 +12:00
/**
* Generates a new configuration ID.
* @returns {string} The new configuration ID which the config doc can be stored under.
*/
2021-04-23 00:46:54 +12:00
const generateConfigID = ({ type, group, user }) => {
2021-04-22 22:45:22 +12:00
const scope = [type, group, user].filter(Boolean).join(SEPARATOR)
2021-04-21 05:14:36 +12:00
2021-04-22 22:45:22 +12:00
return `${DocumentTypes.CONFIG}${SEPARATOR}${scope}`
2021-04-21 05:14:36 +12:00
}
/**
* Gets parameters for retrieving configurations.
*/
2021-04-23 00:46:54 +12:00
const getConfigParams = ({ type, group, user }, otherProps = {}) => {
2021-04-22 22:45:22 +12:00
const scope = [type, group, user].filter(Boolean).join(SEPARATOR)
2021-04-21 05:14:36 +12:00
return {
...otherProps,
2021-04-22 22:45:22 +12:00
startkey: `${DocumentTypes.CONFIG}${SEPARATOR}${scope}`,
endkey: `${DocumentTypes.CONFIG}${SEPARATOR}${scope}${UNICODE_MAX}`,
2021-04-21 05:14:36 +12:00
}
}
2021-04-23 00:46:54 +12:00
/**
* Returns the most granular configuration document from the DB based on the type, group and userID passed.
2021-04-23 01:53:19 +12:00
* @param {Object} db - db instance to query
2021-04-23 00:46:54 +12:00
* @param {Object} scopes - the type, group and userID scopes of the configuration.
* @returns The most granular configuration document based on the scope.
*/
const getScopedFullConfig = async function (db, { type, user, group }) {
2021-04-23 00:46:54 +12:00
const response = await db.allDocs(
getConfigParams(
{ type, user, group },
{
include_docs: true,
}
)
)
2021-05-05 04:31:06 +12:00
function determineScore(row) {
2021-04-23 01:07:00 +12:00
const config = row.doc
2021-04-23 00:46:54 +12:00
// Config is specific to a user and a group
if (config._id.includes(generateConfigID({ type, user, group }))) {
2021-05-05 04:31:06 +12:00
return 4
2021-04-23 01:07:00 +12:00
} else if (config._id.includes(generateConfigID({ type, user }))) {
// Config is specific to a user only
2021-05-05 04:31:06 +12:00
return 3
2021-04-23 01:07:00 +12:00
} else if (config._id.includes(generateConfigID({ type, group }))) {
// Config is specific to a group only
2021-05-05 04:31:06 +12:00
return 2
2021-04-23 01:07:00 +12:00
} else if (config._id.includes(generateConfigID({ type }))) {
// Config is specific to a type only
2021-05-05 04:31:06 +12:00
return 1
2021-04-23 00:46:54 +12:00
}
2021-05-05 04:31:06 +12:00
return 0
}
2021-04-23 00:46:54 +12:00
2021-04-23 01:07:00 +12:00
// Find the config with the most granular scope based on context
2021-05-05 05:14:13 +12:00
const scopedConfig = response.rows.sort(
(a, b) => determineScore(a) - determineScore(b)
)[0]
2021-04-23 01:07:00 +12:00
return scopedConfig && scopedConfig.doc
2021-04-23 00:46:54 +12:00
}
async function getScopedConfig(db, params) {
const configDoc = await getScopedFullConfig(db, params)
return configDoc && configDoc.config ? configDoc.config : configDoc
}
2021-05-13 22:06:08 +12:00
exports.Replication = Replication
exports.getScopedConfig = getScopedConfig
2021-04-23 00:46:54 +12:00
exports.generateConfigID = generateConfigID
exports.getConfigParams = getConfigParams
exports.getScopedFullConfig = getScopedFullConfig