budibase/packages/server/src/utilities/users.ts

46 lines
1.3 KiB
TypeScript
Raw Normal View History

import { InternalTables } from "../db/utils"
import { getGlobalUser } from "./global"
import { context, roles } from "@budibase/backend-core"
2023-11-08 11:03:22 +01:00
import { ContextUserMetadata, UserCtx, UserMetadata } from "@budibase/types"
2023-11-08 11:03:22 +01:00
export async function getFullUser(
userId: string
): Promise<ContextUserMetadata> {
const global = await getGlobalUser(userId)
2023-11-08 11:03:22 +01:00
let metadata: UserMetadata | undefined = undefined
2022-10-11 13:42:35 +02:00
// always prefer the user metadata _id and _rev
delete global._id
delete global._rev
try {
// this will throw an error if the db doesn't exist, or there is no appId
const db = context.getAppDB()
2023-11-08 11:03:22 +01:00
metadata = await db.get<UserMetadata>(userId)
delete metadata.csrfToken
} catch (err) {
2022-10-11 13:42:35 +02:00
// it is fine if there is no user metadata yet
}
return {
...metadata,
...global,
roleId: global.roleId || roles.BUILTIN_ROLE_IDS.PUBLIC,
2021-05-19 17:24:20 +02:00
tableId: InternalTables.USER_METADATA,
// make sure the ID is always a local ID, not a global one
_id: userId,
}
}
export function publicApiUserFix(ctx: UserCtx) {
if (!ctx.request.body) {
return ctx
}
if (!ctx.request.body._id && ctx.params.userId) {
ctx.request.body._id = ctx.params.userId
}
if (!ctx.request.body.roles) {
ctx.request.body.roles = {}
}
return ctx
}