1
0
Fork 0
mirror of synced 2024-06-28 11:00:55 +12:00
budibase/packages/worker/src/api/controllers/global/users.ts

429 lines
11 KiB
TypeScript
Raw Normal View History

2023-02-23 23:38:03 +13:00
import {
checkInviteCode,
getInviteCodes,
updateInviteCode,
} from "../../../utilities/redis"
// import sdk from "../../../sdk"
import * as userSdk from "../../../sdk/users"
import env from "../../../environment"
import {
AcceptUserInviteRequest,
AcceptUserInviteResponse,
BulkUserRequest,
BulkUserResponse,
CloudAccount,
2022-11-12 04:43:41 +13:00
CreateAdminUserRequest,
CreateAdminUserResponse,
Ctx,
InviteUserRequest,
InviteUsersRequest,
MigrationType,
SaveUserResponse,
2022-10-04 02:02:58 +13:00
SearchUsersRequest,
User,
UserCtx,
} from "@budibase/types"
import {
accounts,
cache,
errors,
events,
migrations,
tenancy,
platform,
} from "@budibase/backend-core"
import { checkAnyUserExists } from "../../../utilities/users"
2023-03-01 06:05:11 +13:00
import { isEmailConfigured } from "../../../utilities/email"
2022-07-26 23:17:01 +12:00
const MAX_USERS_UPLOAD_LIMIT = 1000
export const save = async (ctx: UserCtx<User, SaveUserResponse>) => {
try {
const currentUserId = ctx.user._id
const requestUser = ctx.request.body
const user = await userSdk.save(requestUser, { currentUserId })
ctx.body = {
_id: user._id!,
_rev: user._rev!,
email: user.email,
}
} catch (err: any) {
ctx.throw(err.status || 400, err)
}
}
const bulkDelete = async (userIds: string[], currentUserId: string) => {
if (userIds?.indexOf(currentUserId) !== -1) {
throw new Error("Unable to delete self.")
}
return await userSdk.bulkDelete(userIds)
}
2022-07-26 23:17:01 +12:00
const bulkCreate = async (users: User[], groupIds: string[]) => {
if (!env.SELF_HOSTED && users.length > MAX_USERS_UPLOAD_LIMIT) {
throw new Error(
2022-07-26 23:17:01 +12:00
"Max limit for upload is 1000 users. Please reduce file size and try again."
)
}
return await userSdk.bulkCreate(users, groupIds)
}
2022-07-26 23:17:01 +12:00
export const bulkUpdate = async (ctx: any) => {
const currentUserId = ctx.user._id
const input = ctx.request.body as BulkUserRequest
let created, deleted
2022-07-18 23:33:56 +12:00
try {
if (input.create) {
created = await bulkCreate(input.create.users, input.create.groups)
}
if (input.delete) {
deleted = await bulkDelete(input.delete.userIds, currentUserId)
}
} catch (err: any) {
2022-09-24 09:21:51 +12:00
ctx.throw(err.status || 400, err?.message || err)
}
ctx.body = { created, deleted } as BulkUserResponse
}
const parseBooleanParam = (param: any) => {
return !(param && param === "false")
}
export const adminUser = async (
ctx: Ctx<CreateAdminUserRequest, CreateAdminUserResponse>
) => {
const { email, password, tenantId } = ctx.request.body
if (await platform.tenants.exists(tenantId)) {
ctx.throw(403, "Organisation already exists.")
}
if (env.MULTI_TENANCY) {
// store the new tenant record in the platform db
await platform.tenants.addTenant(tenantId)
await migrations.backPopulateMigrations({
type: MigrationType.GLOBAL,
tenantId,
})
}
await tenancy.doInTenant(tenantId, async () => {
// account portal sends a pre-hashed password - honour param to prevent double hashing
const hashPassword = parseBooleanParam(ctx.request.query.hashPassword)
// account portal sends no password for SSO users
const requirePassword = parseBooleanParam(ctx.request.query.requirePassword)
const userExists = await checkAnyUserExists()
if (userExists) {
ctx.throw(
403,
"You cannot initialise once an global user has been created."
)
}
const user: User = {
email: email,
password: password,
createdAt: Date.now(),
roles: {},
builder: {
global: true,
},
admin: {
global: true,
},
tenantId,
}
try {
// always bust checklist beforehand, if an error occurs but can proceed, don't get
// stuck in a cycle
await cache.bustCache(cache.CacheKey.CHECKLIST)
const finalUser = await userSdk.save(user, {
hashPassword,
requirePassword,
})
2021-09-24 10:25:25 +12:00
// events
let account: CloudAccount | undefined
if (!env.SELF_HOSTED && !env.DISABLE_ACCOUNT_PORTAL) {
account = await accounts.getAccountByTenantId(tenantId)
}
await events.identification.identifyTenantGroup(tenantId, account)
ctx.body = {
_id: finalUser._id!,
_rev: finalUser._rev!,
email: finalUser.email,
}
} catch (err: any) {
ctx.throw(err.status || 400, err)
}
})
}
export const countByApp = async (ctx: any) => {
const appId = ctx.params.appId
try {
ctx.body = await userSdk.countUsersByApp(appId)
} catch (err: any) {
ctx.throw(err.status || 400, err)
}
}
export const destroy = async (ctx: any) => {
2022-04-08 12:28:22 +12:00
const id = ctx.params.id
if (id === ctx.user._id) {
ctx.throw(400, "Unable to delete self.")
}
2022-07-20 01:20:57 +12:00
await userSdk.destroy(id, ctx.user)
2022-07-20 01:20:57 +12:00
2021-04-19 22:34:07 +12:00
ctx.body = {
2022-04-08 12:28:22 +12:00
message: `User ${id} deleted.`,
}
2021-04-19 22:34:07 +12:00
}
2023-02-28 22:37:03 +13:00
export const getAppUsers = async (ctx: any) => {
const body = ctx.request.body as SearchUsersRequest
const users = await userSdk.getUsersByAppAccess(body?.appId)
ctx.body = { data: users }
}
export const search = async (ctx: any) => {
2022-10-04 02:02:58 +13:00
const body = ctx.request.body as SearchUsersRequest
2023-02-28 22:37:03 +13:00
if (body.paginated === false) {
await getAppUsers(ctx)
} else {
const paginated = await userSdk.paginatedUsers(body)
// user hashed password shouldn't ever be returned
for (let user of paginated.data) {
if (user) {
delete user.password
}
2021-04-19 22:34:07 +12:00
}
2023-02-28 22:37:03 +13:00
ctx.body = paginated
2021-04-19 22:34:07 +12:00
}
}
// called internally by app server user fetch
export const fetch = async (ctx: any) => {
const all = await userSdk.allUsers()
2021-04-19 22:34:07 +12:00
// user hashed password shouldn't ever be returned
for (let user of all) {
2021-04-19 22:34:07 +12:00
if (user) {
delete user.password
}
}
2022-03-26 05:08:12 +13:00
ctx.body = all
2021-04-19 22:34:07 +12:00
}
// called internally by app server user find
export const find = async (ctx: any) => {
ctx.body = await userSdk.getUser(ctx.params.id)
2021-04-19 22:34:07 +12:00
}
export const tenantUserLookup = async (ctx: any) => {
const id = ctx.params.id
const user = await userSdk.getPlatformUser(id)
if (user) {
ctx.body = user
} else {
2021-09-18 00:41:22 +12:00
ctx.throw(400, "No tenant user found.")
}
}
2023-02-23 23:38:03 +13:00
/*
Encapsulate the app user onboarding flows here.
*/
export const onboardUsers = async (ctx: any) => {
const request = ctx.request.body as InviteUsersRequest | BulkUserRequest
const isBulkCreate = "create" in request
const emailConfigured = await isEmailConfigured()
let onboardingResponse
if (isBulkCreate) {
// @ts-ignore
const { users, groups, roles } = request.create
const assignUsers = users.map((user: User) => (user.roles = roles))
onboardingResponse = await userSdk.bulkCreate(assignUsers, groups)
2023-02-23 23:38:03 +13:00
ctx.body = onboardingResponse
} else if (emailConfigured) {
2023-02-28 22:37:03 +13:00
onboardingResponse = await invite(ctx)
2023-02-23 23:38:03 +13:00
} else if (!emailConfigured) {
const inviteRequest = ctx.request.body as InviteUsersRequest
2023-02-28 22:37:03 +13:00
let createdPasswords: any = {}
2023-02-23 23:38:03 +13:00
const users: User[] = inviteRequest.map(invite => {
let password = Math.random().toString(36).substring(2, 22)
2023-02-28 22:37:03 +13:00
// Temp password to be passed to the user.
createdPasswords[invite.email] = password
2023-02-23 23:38:03 +13:00
return {
email: invite.email,
password,
forceResetPassword: true,
roles: invite.userInfo.apps,
admin: { global: false },
builder: { global: false },
tenantId: tenancy.getTenantId(),
}
})
let bulkCreateReponse = await userSdk.bulkCreate(users, [])
2023-02-28 22:37:03 +13:00
// Apply temporary credentials
let createWithCredentials = {
2023-02-23 23:38:03 +13:00
...bulkCreateReponse,
2023-02-28 22:37:03 +13:00
successful: bulkCreateReponse?.successful.map(user => {
return {
...user,
password: createdPasswords[user.email],
}
}),
2023-02-23 23:38:03 +13:00
created: true,
}
2023-02-28 22:37:03 +13:00
ctx.body = createWithCredentials
2023-02-23 23:38:03 +13:00
} else {
ctx.throw(400, "User onboarding failed")
}
}
export const invite = async (ctx: any) => {
2023-02-28 22:37:03 +13:00
const request = ctx.request.body as InviteUsersRequest
const response = await userSdk.invite(request)
// explicitly throw for single user invite
if (response.unsuccessful.length) {
const reason = response.unsuccessful[0].reason
if (reason === "Unavailable") {
ctx.throw(400, reason)
} else {
ctx.throw(500, reason)
}
}
2021-05-06 02:17:15 +12:00
ctx.body = {
2021-05-06 02:19:44 +12:00
message: "Invitation has been sent.",
2023-02-23 23:38:03 +13:00
successful: response.successful,
unsuccessful: response.unsuccessful,
2021-05-06 02:17:15 +12:00
}
}
2022-07-05 20:21:59 +12:00
export const inviteMultiple = async (ctx: any) => {
const request = ctx.request.body as InviteUsersRequest
ctx.body = await userSdk.invite(request)
2022-07-05 20:21:59 +12:00
}
2023-01-28 02:44:57 +13:00
export const checkInvite = async (ctx: any) => {
const { code } = ctx.params
let invite
try {
invite = await checkInviteCode(code, false)
} catch (e) {
ctx.throw(400, "There was a problem with the invite")
}
ctx.body = {
email: invite.email,
}
}
2023-02-23 23:38:03 +13:00
export const getUserInvites = async (ctx: any) => {
let invites
try {
// Restricted to the currently authenticated tenant
invites = await getInviteCodes([ctx.user.tenantId])
} catch (e) {
ctx.throw(400, "There was a problem fetching invites")
}
ctx.body = invites
}
export const updateInvite = async (ctx: any) => {
const { code } = ctx.params
let updateBody = { ...ctx.request.body }
delete updateBody.email
let invite
try {
invite = await checkInviteCode(code, false)
if (!invite) {
throw new Error("The invite could not be retrieved")
}
} catch (e) {
ctx.throw(400, "There was a problem with the invite")
}
let updated = {
...invite,
}
if (!updateBody?.apps || !Object.keys(updateBody?.apps).length) {
updated.info.apps = []
} else {
updated.info = {
...invite.info,
apps: {
...invite.info.apps,
...updateBody.apps,
},
}
}
await updateInviteCode(code, updated)
ctx.body = { ...invite }
}
export const inviteAccept = async (
ctx: Ctx<AcceptUserInviteRequest, AcceptUserInviteResponse>
) => {
const { inviteCode, password, firstName, lastName } = ctx.request.body
2021-05-06 02:17:15 +12:00
try {
// info is an extension of the user object that was stored by global
const { email, info }: any = await checkInviteCode(inviteCode)
const user = await tenancy.doInTenant(info.tenantId, async () => {
2023-02-23 23:38:03 +13:00
let request = {
firstName,
lastName,
password,
email,
2023-02-23 23:38:03 +13:00
roles: info.apps,
tenantId: info.tenantId,
2023-02-23 23:38:03 +13:00
}
delete info.apps
request = {
...request,
...info,
2023-02-23 23:38:03 +13:00
}
const saved = await userSdk.save(request)
const db = tenancy.getGlobalDB()
2022-05-25 07:01:13 +12:00
const user = await db.get(saved._id)
2022-05-24 09:14:44 +12:00
await events.user.inviteAccepted(user)
2022-05-25 07:01:13 +12:00
return saved
2022-04-08 12:28:22 +12:00
})
ctx.body = {
_id: user._id,
_rev: user._rev,
email: user.email,
}
} catch (err: any) {
if (err.code === errors.codes.USAGE_LIMIT_EXCEEDED) {
// explicitly re-throw limit exceeded errors
ctx.throw(400, err)
}
2021-05-06 02:17:15 +12:00
ctx.throw(400, "Unable to create new user, invitation invalid.")
}
}