Skip to content

Commit

Permalink
Merge pull request #12152 from Budibase/fix/revert-per-user-per-creator
Browse files Browse the repository at this point in the history
[Fix] [Revert] per user per creator
  • Loading branch information
jvcalderon authored Oct 23, 2023
2 parents 97fc794 + bc4dd8e commit 6c4befb
Show file tree
Hide file tree
Showing 17 changed files with 53 additions and 235 deletions.
4 changes: 2 additions & 2 deletions packages/backend-core/src/cache/writethrough.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ export class Writethrough {
this.writeRateMs = writeRateMs
}

async put(doc: any, writeRateMs: number = this.writeRateMs) {
return put(this.db, doc, writeRateMs)
async put(doc: any) {
return put(this.db, doc, this.writeRateMs)
}

async get(id: string) {
Expand Down
108 changes: 46 additions & 62 deletions packages/backend-core/src/users/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,12 @@ import {
import {
getAccountHolderFromUserIds,
isAdmin,
isCreator,
validateUniqueUser,
} from "./utils"
import { searchExistingEmails } from "./lookup"
import { hash } from "../utils"

type QuotaUpdateFn = (
change: number,
creatorsChange: number,
cb?: () => Promise<any>
) => Promise<any>
type QuotaUpdateFn = (change: number, cb?: () => Promise<any>) => Promise<any>
type GroupUpdateFn = (groupId: string, userIds: string[]) => Promise<any>
type FeatureFn = () => Promise<Boolean>
type GroupGetFn = (ids: string[]) => Promise<UserGroup[]>
Expand Down Expand Up @@ -250,8 +245,7 @@ export class UserDB {
}

const change = dbUser ? 0 : 1 // no change if there is existing user
const creatorsChange = isCreator(dbUser) !== isCreator(user) ? 1 : 0
return UserDB.quotas.addUsers(change, creatorsChange, async () => {
return UserDB.quotas.addUsers(change, async () => {
await validateUniqueUser(email, tenantId)

let builtUser = await UserDB.buildUser(user, opts, tenantId, dbUser)
Expand Down Expand Up @@ -313,7 +307,6 @@ export class UserDB {

let usersToSave: any[] = []
let newUsers: any[] = []
let newCreators: any[] = []

const emails = newUsersRequested.map((user: User) => user.email)
const existingEmails = await searchExistingEmails(emails)
Expand All @@ -334,66 +327,59 @@ export class UserDB {
}
newUser.userGroups = groups
newUsers.push(newUser)
if (isCreator(newUser)) {
newCreators.push(newUser)
}
}

const account = await accountSdk.getAccountByTenantId(tenantId)
return UserDB.quotas.addUsers(
newUsers.length,
newCreators.length,
async () => {
// create the promises array that will be called by bulkDocs
newUsers.forEach((user: any) => {
usersToSave.push(
UserDB.buildUser(
user,
{
hashPassword: true,
requirePassword: user.requirePassword,
},
tenantId,
undefined, // no dbUser
account
)
return UserDB.quotas.addUsers(newUsers.length, async () => {
// create the promises array that will be called by bulkDocs
newUsers.forEach((user: any) => {
usersToSave.push(
UserDB.buildUser(
user,
{
hashPassword: true,
requirePassword: user.requirePassword,
},
tenantId,
undefined, // no dbUser
account
)
})
)
})

const usersToBulkSave = await Promise.all(usersToSave)
await usersCore.bulkUpdateGlobalUsers(usersToBulkSave)
const usersToBulkSave = await Promise.all(usersToSave)
await usersCore.bulkUpdateGlobalUsers(usersToBulkSave)

// Post-processing of bulk added users, e.g. events and cache operations
for (const user of usersToBulkSave) {
// TODO: Refactor to bulk insert users into the info db
// instead of relying on looping tenant creation
await platform.users.addUser(tenantId, user._id, user.email)
await eventHelpers.handleSaveEvents(user, undefined)
}

const saved = usersToBulkSave.map(user => {
return {
_id: user._id,
email: user.email,
}
})
// Post-processing of bulk added users, e.g. events and cache operations
for (const user of usersToBulkSave) {
// TODO: Refactor to bulk insert users into the info db
// instead of relying on looping tenant creation
await platform.users.addUser(tenantId, user._id, user.email)
await eventHelpers.handleSaveEvents(user, undefined)
}

// now update the groups
if (Array.isArray(saved) && groups) {
const groupPromises = []
const createdUserIds = saved.map(user => user._id)
for (let groupId of groups) {
groupPromises.push(UserDB.groups.addUsers(groupId, createdUserIds))
}
await Promise.all(groupPromises)
const saved = usersToBulkSave.map(user => {
return {
_id: user._id,
email: user.email,
}
})

return {
successful: saved,
unsuccessful,
// now update the groups
if (Array.isArray(saved) && groups) {
const groupPromises = []
const createdUserIds = saved.map(user => user._id)
for (let groupId of groups) {
groupPromises.push(UserDB.groups.addUsers(groupId, createdUserIds))
}
await Promise.all(groupPromises)
}
)

return {
successful: saved,
unsuccessful,
}
})
}

static async bulkDelete(userIds: string[]): Promise<BulkUserDeleted> {
Expand Down Expand Up @@ -433,12 +419,11 @@ export class UserDB {
_deleted: true,
}))
const dbResponse = await usersCore.bulkUpdateGlobalUsers(toDelete)
const creatorsToDelete = usersToDelete.filter(isCreator)

await UserDB.quotas.removeUsers(toDelete.length)
for (let user of usersToDelete) {
await bulkDeleteProcessing(user)
}
await UserDB.quotas.removeUsers(toDelete.length, creatorsToDelete.length)

// Build Response
// index users by id
Expand Down Expand Up @@ -487,8 +472,7 @@ export class UserDB {

await db.remove(userId, dbUser._rev)

const creatorsToDelete = isCreator(dbUser) ? 1 : 0
await UserDB.quotas.removeUsers(1, creatorsToDelete)
await UserDB.quotas.removeUsers(1)
await eventHelpers.handleDeleteEvents(dbUser)
await cache.user.invalidateUser(userId)
await sessions.invalidateSessions(userId, { reason: "deletion" })
Expand Down
18 changes: 2 additions & 16 deletions packages/backend-core/src/users/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,15 @@ import {
} from "../db"
import {
BulkDocsResponse,
ContextUser,
SearchQuery,
SearchQueryOperators,
SearchUsersRequest,
User,
ContextUser,
DatabaseQueryOpts,
} from "@budibase/types"
import { getGlobalDB } from "../context"
import * as context from "../context"
import { isCreator } from "./utils"
import { getGlobalDB } from "../context"

type GetOpts = { cleanup?: boolean }

Expand Down Expand Up @@ -287,19 +286,6 @@ export async function getUserCount() {
return response.total_rows
}

export async function getCreatorCount() {
let creators = 0
async function iterate(startPage?: string) {
const page = await paginatedUsers({ bookmark: startPage })
creators += page.data.filter(isCreator).length
if (page.hasNextPage) {
await iterate(page.nextPage)
}
}
await iterate()
return creators
}

// used to remove the builder/admin permissions, for processing the
// user as an app user (they may have some specific role/group
export function removePortalUserPermissions(user: User | ContextUser) {
Expand Down
1 change: 0 additions & 1 deletion packages/backend-core/src/users/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { getAccountByTenantId } from "../accounts"
// extract from shared-core to make easily accessible from backend-core
export const isBuilder = sdk.users.isBuilder
export const isAdmin = sdk.users.isAdmin
export const isCreator = sdk.users.isCreator
export const isGlobalBuilder = sdk.users.isGlobalBuilder
export const isAdminOrBuilder = sdk.users.isAdminOrBuilder
export const hasAdminPermissions = sdk.users.hasAdminPermissions
Expand Down
54 changes: 0 additions & 54 deletions packages/backend-core/tests/core/users/users.spec.js

This file was deleted.

13 changes: 0 additions & 13 deletions packages/backend-core/tests/core/utilities/structures/licenses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,6 @@ export function quotas(): Quotas {
value: 1,
triggers: [],
},
creators: {
name: "Creators",
value: 1,
triggers: [],
},
userGroups: {
name: "User Groups",
value: 1,
Expand Down Expand Up @@ -123,10 +118,6 @@ export function customer(): Customer {
export function subscription(): Subscription {
return {
amount: 10000,
amounts: {
user: 10000,
creator: 0,
},
cancelAt: undefined,
currency: "usd",
currentPeriodEnd: 0,
Expand All @@ -135,10 +126,6 @@ export function subscription(): Subscription {
duration: PriceDuration.MONTHLY,
pastDueAt: undefined,
quantity: 0,
quantities: {
user: 0,
creator: 0,
},
status: "active",
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MonthlyQuotaName, QuotaUsage } from "@budibase/types"

export const usage = (users: number = 0, creators: number = 0): QuotaUsage => {
export const usage = (): QuotaUsage => {
return {
_id: "usage_quota",
quotaReset: new Date().toISOString(),
Expand Down Expand Up @@ -58,8 +58,7 @@ export const usage = (users: number = 0, creators: number = 0): QuotaUsage => {
usageQuota: {
apps: 0,
plugins: 0,
users,
creators,
users: 0,
userGroups: 0,
rows: 0,
triggers: {},
Expand Down
2 changes: 1 addition & 1 deletion packages/pro
Submodule pro updated from 56d968 to f7e7cf
2 changes: 0 additions & 2 deletions packages/server/src/migrations/functions/syncQuotas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import * as syncApps from "./usageQuotas/syncApps"
import * as syncRows from "./usageQuotas/syncRows"
import * as syncPlugins from "./usageQuotas/syncPlugins"
import * as syncUsers from "./usageQuotas/syncUsers"
import * as syncCreators from "./usageQuotas/syncCreators"

/**
* Synchronise quotas to the state of the db.
Expand All @@ -14,6 +13,5 @@ export const run = async () => {
await syncRows.run()
await syncPlugins.run()
await syncUsers.run()
await syncCreators.run()
})
}

This file was deleted.

This file was deleted.

Loading

0 comments on commit 6c4befb

Please sign in to comment.