1
0
Fork 0
mirror of synced 2024-06-30 20:10:54 +12:00

Updating user search endpoint to allow searching by app ID with a new view, as well as updating user page to have a search input again.

This commit is contained in:
mike12345567 2022-07-06 16:09:05 +01:00
parent 18d259b1ba
commit c62805853a
7 changed files with 126 additions and 27 deletions

View file

@ -12,6 +12,7 @@ export enum AutomationViewModes {
export enum ViewNames { export enum ViewNames {
USER_BY_EMAIL = "by_email", USER_BY_EMAIL = "by_email",
USER_BY_APP = "by_app",
BY_API_KEY = "by_api_key", BY_API_KEY = "by_api_key",
USER_BY_BUILDERS = "by_builders", USER_BY_BUILDERS = "by_builders",
LINK = "by_link", LINK = "by_link",

View file

@ -8,7 +8,7 @@ import { doWithDB, allDbs } from "./index"
import { getCouchInfo } from "./pouch" import { getCouchInfo } from "./pouch"
import { getAppMetadata } from "../cache/appMetadata" import { getAppMetadata } from "../cache/appMetadata"
import { checkSlashesInUrl } from "../helpers" import { checkSlashesInUrl } from "../helpers"
import { isDevApp, isDevAppID } from "./conversions" import { isDevApp, isDevAppID, getProdAppID } from "./conversions"
import { APP_PREFIX } from "./constants" import { APP_PREFIX } from "./constants"
import * as events from "../events" import * as events from "../events"
@ -107,6 +107,15 @@ export function getGlobalUserParams(globalId: any, otherProps: any = {}) {
} }
} }
export function getUsersByAppParams(appId: any, otherProps: any = {}) {
const prodAppId = getProdAppID(appId)
return {
...otherProps,
startkey: prodAppId,
endkey: `${prodAppId}${UNICODE_MAX}`,
}
}
/** /**
* Generates a template ID. * Generates a template ID.
* @param ownerId The owner/user of the template, this could be global or a workspace level. * @param ownerId The owner/user of the template, this could be global or a workspace level.
@ -464,15 +473,29 @@ export const getPlatformUrl = async (opts = { tenantAware: true }) => {
export function pagination( export function pagination(
data: any[], data: any[],
pageSize: number, pageSize: number,
{ paginate, property } = { paginate: true, property: "_id" } {
paginate,
property,
getKey,
}: {
paginate: boolean
property: string
getKey?: (doc: any) => string | undefined
} = {
paginate: true,
property: "_id",
}
) { ) {
if (!paginate) { if (!paginate) {
return { data, hasNextPage: false } return { data, hasNextPage: false }
} }
const hasNextPage = data.length > pageSize const hasNextPage = data.length > pageSize
let nextPage = undefined let nextPage = undefined
if (!getKey) {
getKey = (doc: any) => (property ? doc?.[property] : doc?._id)
}
if (hasNextPage) { if (hasNextPage) {
nextPage = property ? data[pageSize]?.[property] : data[pageSize]?._id nextPage = getKey(data[pageSize])
} }
return { return {
data: data.slice(0, pageSize), data: data.slice(0, pageSize),

View file

@ -1,4 +1,4 @@
const { DocumentTypes, ViewNames } = require("./utils") const { DocumentTypes, ViewNames, SEPARATOR } = require("./constants")
const { getGlobalDB } = require("../tenancy") const { getGlobalDB } = require("../tenancy")
function DesignDoc() { function DesignDoc() {
@ -34,6 +34,33 @@ exports.createUserEmailView = async () => {
await db.put(designDoc) await db.put(designDoc)
} }
exports.createUserAppView = async () => {
const db = getGlobalDB()
let designDoc
try {
designDoc = await db.get("_design/database")
} catch (err) {
// no design doc, make one
designDoc = DesignDoc()
}
const view = {
// if using variables in a map function need to inject them before use
map: `function(doc) {
if (doc._id.startsWith("${DocumentTypes.USER}${SEPARATOR}") && doc.roles) {
for (let prodAppId of Object.keys(doc.roles)) {
let emitted = prodAppId + "${SEPARATOR}" + doc._id
emit(emitted, null)
}
}
}`,
}
designDoc.views = {
...designDoc.views,
[ViewNames.USER_BY_APP]: view,
}
await db.put(designDoc)
}
exports.createApiKeyView = async () => { exports.createApiKeyView = async () => {
const db = getGlobalDB() const db = getGlobalDB()
let designDoc let designDoc
@ -84,6 +111,7 @@ exports.queryGlobalView = async (viewName, params, db = null) => {
[ViewNames.USER_BY_EMAIL]: exports.createUserEmailView, [ViewNames.USER_BY_EMAIL]: exports.createUserEmailView,
[ViewNames.BY_API_KEY]: exports.createApiKeyView, [ViewNames.BY_API_KEY]: exports.createApiKeyView,
[ViewNames.USER_BY_BUILDERS]: exports.createUserBuildersView, [ViewNames.USER_BY_BUILDERS]: exports.createUserBuildersView,
[ViewNames.USER_BY_APP]: exports.createUserAppView,
} }
// can pass DB in if working with something specific // can pass DB in if working with something specific
if (!db) { if (!db) {

View file

@ -1,6 +1,6 @@
const { ViewNames } = require("./db/utils") const { ViewNames, getUsersByAppParams, getProdAppID } = require("./db/utils")
const { queryGlobalView } = require("./db/views") const { queryGlobalView } = require("./db/views")
const { UNICODE_MAX } = require("./db/constants") const { UNICODE_MAX, SEPARATOR } = require("./db/constants")
/** /**
* Given an email address this will use a view to search through * Given an email address this will use a view to search through
@ -13,12 +13,32 @@ exports.getGlobalUserByEmail = async email => {
throw "Must supply an email address to view" throw "Must supply an email address to view"
} }
const response = await queryGlobalView(ViewNames.USER_BY_EMAIL, { return await queryGlobalView(ViewNames.USER_BY_EMAIL, {
key: email.toLowerCase(), key: email.toLowerCase(),
include_docs: true, include_docs: true,
}) })
}
return response exports.searchGlobalUsersByApp = async (appId, opts) => {
if (typeof appId !== "string") {
throw new Error("Must provide a string based app ID")
}
const params = getUsersByAppParams(appId, {
include_docs: true,
})
params.startkey = opts && opts.startkey ? opts.startkey : params.startkey
let response = await queryGlobalView(ViewNames.USER_BY_APP, params)
if (!response) {
response = []
}
return Array.isArray(response) ? response : [response]
}
exports.getGlobalUserByAppPage = (appId, user) => {
if (!user) {
return
}
return `${getProdAppID(appId)}${SEPARATOR}${user._id}`
} }
/** /**

View file

@ -11,6 +11,8 @@
Icon, Icon,
notifications, notifications,
Pagination, Pagination,
Search,
Label,
} from "@budibase/bbui" } from "@budibase/bbui"
import AddUserModal from "./_components/AddUserModal.svelte" import AddUserModal from "./_components/AddUserModal.svelte"
import { users, groups } from "stores/portal" import { users, groups } from "stores/portal"
@ -70,10 +72,10 @@
importUsersModal importUsersModal
let pageInfo = createPaginationStore() let pageInfo = createPaginationStore()
let prevSearch = undefined, let prevEmail = undefined,
search = undefined searchEmail = undefined
$: page = $pageInfo.page $: page = $pageInfo.page
$: fetchUsers(page, search) $: fetchUsers(page, searchEmail)
$: { $: {
enrichedUsers = $users.data?.map(user => { enrichedUsers = $users.data?.map(user => {
@ -160,19 +162,19 @@
} }
}) })
async function fetchUsers(page, search) { async function fetchUsers(page, email) {
if ($pageInfo.loading) { if ($pageInfo.loading) {
return return
} }
// need to remove the page if they've started searching // need to remove the page if they've started searching
if (search && !prevSearch) { if (email && !prevEmail) {
pageInfo.reset() pageInfo.reset()
page = undefined page = undefined
} }
prevSearch = search prevEmail = email
try { try {
pageInfo.loading() pageInfo.loading()
await users.search({ page, search }) await users.search({ page, email })
pageInfo.fetched($users.hasNextPage, $users.nextPage) pageInfo.fetched($users.hasNextPage, $users.nextPage)
} catch (error) { } catch (error) {
notifications.error("Error getting user list") notifications.error("Error getting user list")
@ -207,6 +209,10 @@
<Button on:click={importUsersModal.show} icon="Import" primary <Button on:click={importUsersModal.show} icon="Import" primary
>Import Users</Button >Import Users</Button
> >
<div class="field">
<Label size="L">Search email</Label>
<Search bind:value={searchEmail} placeholder="" />
</div>
</ButtonGroup> </ButtonGroup>
<Table <Table
on:click={({ detail }) => $goto(`./${detail._id}`)} on:click={({ detail }) => $goto(`./${detail._id}`)}
@ -273,6 +279,18 @@
</Modal> </Modal>
<style> <style>
.field {
display: flex;
align-items: center;
flex-direction: row;
grid-gap: var(--spacing-m);
margin-left: auto;
}
.field > :global(*) + :global(*) {
margin-left: var(--spacing-m);
}
.access-description { .access-description {
display: flex; display: flex;
margin-top: var(--spacing-xl); margin-top: var(--spacing-xl);

View file

@ -13,13 +13,16 @@ export const buildUserEndpoints = API => ({
* @param {string} page The page to retrieve * @param {string} page The page to retrieve
* @param {string} search The starts with string to search username/email by. * @param {string} search The starts with string to search username/email by.
*/ */
searchUsers: async ({ page, search } = {}) => { searchUsers: async ({ page, email, appId } = {}) => {
const opts = {} const opts = {}
if (page) { if (page) {
opts.page = page opts.page = page
} }
if (search) { if (email) {
opts.search = search opts.email = email
}
if (appId) {
opts.appId = appId
} }
return await API.post({ return await API.post({
url: `/api/global/users/search`, url: `/api/global/users/search`,

View file

@ -31,8 +31,9 @@ export const allUsers = async () => {
export const paginatedUsers = async ({ export const paginatedUsers = async ({
page, page,
search, email,
}: { page?: string; search?: string } = {}) => { appId,
}: { page?: string; email?: string; appId?: string } = {}) => {
const db = tenancy.getGlobalDB() const db = tenancy.getGlobalDB()
// get one extra document, to have the next page // get one extra document, to have the next page
const opts: any = { const opts: any = {
@ -44,19 +45,24 @@ export const paginatedUsers = async ({
opts.startkey = page opts.startkey = page
} }
// property specifies what to use for the page/anchor // property specifies what to use for the page/anchor
let userList, property let userList,
// no search, query allDocs property = "_id",
if (!search) { getKey
if (appId) {
userList = await usersCore.searchGlobalUsersByApp(appId, opts)
getKey = (doc: any) => usersCore.getGlobalUserByAppPage(appId, doc)
} else if (email) {
userList = await usersCore.searchGlobalUsersByEmail(email, opts)
property = "email"
} else {
// no search, query allDocs
const response = await db.allDocs(dbUtils.getGlobalUserParams(null, opts)) const response = await db.allDocs(dbUtils.getGlobalUserParams(null, opts))
userList = response.rows.map((row: any) => row.doc) userList = response.rows.map((row: any) => row.doc)
property = "_id"
} else {
userList = await usersCore.searchGlobalUsersByEmail(search, opts)
property = "email"
} }
return dbUtils.pagination(userList, PAGE_LIMIT, { return dbUtils.pagination(userList, PAGE_LIMIT, {
paginate: true, paginate: true,
property, property,
getKey,
}) })
} }