forked from Cap-go/capgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorganization.ts
More file actions
686 lines (587 loc) · 23.4 KB
/
organization.ts
File metadata and controls
686 lines (587 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
import type { ComputedRef, Ref } from 'vue'
import type { ArrayElement, Concrete, Merge } from '~/services/types'
import type { Database } from '~/types/supabase.types'
import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import { createSignedImageUrl, getImmediateImageUrl, resolveImagePath } from '~/services/storage'
import { stripeEnabled, useSupabase } from '~/services/supabase'
import { createDeferredPromise } from '../utils/promise'
import { useDashboardAppsStore } from './dashboardApps'
import { useDisplayStore } from './display'
import { useMainStore } from './main'
// Password policy configuration interface
export interface PasswordPolicyConfig {
enabled: boolean
min_length: number
require_uppercase: boolean
require_number: boolean
require_special: boolean
}
// Extended organization type with password policy and 2FA fields (from get_orgs_v7)
// Note: Using get_orgs_v7 return type with explicit JSON parsing for password_policy_config
type RawOrganization = ArrayElement<Database['public']['Functions']['get_orgs_v7']['Returns']>
export type Organization = Omit<RawOrganization, 'password_policy_config' | 'stats_refresh_requested_at' | 'stats_updated_at'> & {
logo_storage_path?: string | null
logo_is_loading?: boolean
password_policy_config: PasswordPolicyConfig | null
stats_refresh_requested_at: string | null
stats_updated_at: string | null
}
export type OrganizationRole
= Database['public']['Enums']['user_min_right']
| 'owner'
| 'org_member'
| 'org_billing_admin'
| 'org_admin'
| 'org_super_admin'
export type ExtendedOrganizationMember = Concrete<Merge<ArrayElement<Database['public']['Functions']['get_org_members']['Returns']>, { id: number | string }>>
export type ExtendedOrganizationMembers = ExtendedOrganizationMember[]
type SignedMemberImageCallback = (signedImages: Map<string, string>) => void
type LegacyMinRight = Database['public']['Enums']['user_min_right'] | 'owner'
// Mapping des rôles RBAC d'organisation vers leurs clés de traduction i18n
export const RBAC_ORG_ROLE_I18N_KEYS: Record<string, string> = {
org_super_admin: 'role-org-super-admin',
org_admin: 'role-org-admin',
org_billing_admin: 'role-org-billing-admin',
org_member: 'role-org-member',
app_admin: 'role-app-admin',
app_developer: 'role-app-developer',
app_uploader: 'role-app-uploader',
app_reader: 'role-app-reader',
}
/**
* Obtient la clé i18n pour un rôle RBAC d'organisation
* @param role Le nom technique du rôle
* @returns La clé de traduction i18n, ou undefined si non mappé
*/
export function getRbacRoleI18nKey(role: string): string | undefined {
return RBAC_ORG_ROLE_I18N_KEYS[role]
}
const LEGACY_ROLE_RANK: Record<string, number> = {
read: 1,
upload: 2,
write: 3,
admin: 4,
super_admin: 5,
}
const LEGACY_ROLE_ALIASES: Record<string, string> = {
owner: 'super_admin',
org_super_admin: 'super_admin',
org_admin: 'admin',
org_billing_admin: 'read',
org_member: 'read',
app_admin: 'admin',
app_developer: 'write',
app_uploader: 'upload',
app_reader: 'read',
}
const LEGACY_TO_RBAC_ORG: Record<string, string> = {
super_admin: 'org_super_admin',
admin: 'org_admin',
write: 'org_member',
upload: 'org_member',
read: 'org_member',
}
const LEGACY_TO_RBAC_APP: Record<string, string> = {
super_admin: 'app_admin',
admin: 'app_admin',
write: 'app_developer',
upload: 'app_uploader',
read: 'app_reader',
}
function normalizeLegacyRole(role?: string | null) {
if (!role)
return null
const trimmed = role.startsWith('invite_') ? role.slice('invite_'.length) : role
return LEGACY_ROLE_ALIASES[trimmed] ?? trimmed
}
function legacyRoleRank(role?: string | null) {
const normalized = normalizeLegacyRole(role)
if (!normalized)
return null
return LEGACY_ROLE_RANK[normalized] ?? null
}
export function roleHasLegacyMinRight(role: string | null | undefined, minRight: LegacyMinRight) {
const roleRank = legacyRoleRank(role)
const requiredRank = legacyRoleRank(minRight)
if (roleRank === null || requiredRank === null)
return false
return roleRank >= requiredRank
}
export function isAdminRole(role: string | null | undefined) {
return roleHasLegacyMinRight(role, 'admin')
}
export function isSuperAdminRole(role: string | null | undefined) {
return roleHasLegacyMinRight(role, 'super_admin')
}
function normalizeRbacRole(role: string, scope: 'org' | 'app') {
const legacy = normalizeLegacyRole(role)
if (!legacy)
return role
if (scope === 'org')
return LEGACY_TO_RBAC_ORG[legacy] ?? role
return LEGACY_TO_RBAC_APP[legacy] ?? role
}
function matchesRbacRole(role: string, requiredRole: string) {
if (role === requiredRole)
return true
if (requiredRole.startsWith('org_'))
return normalizeRbacRole(role, 'org') === requiredRole
if (requiredRole.startsWith('app_'))
return normalizeRbacRole(role, 'app') === requiredRole
return normalizeLegacyRole(role) === normalizeLegacyRole(requiredRole)
}
function isSelectableOrganization(role: string) {
return !role.includes('invite')
}
const supabase = useSupabase()
export const useOrganizationStore = defineStore('organization', () => {
const main = useMainStore()
const _organizations: Ref<Map<string, Organization>> = ref(new Map())
const _organizationsByAppId: Ref<Map<string, Organization>> = ref(new Map())
const _initialLoadPromise = ref(createDeferredPromise<boolean>())
const _initialized = ref(false)
const organizations: ComputedRef<Organization[]> = computed(
() => {
return Array.from(
_organizations.value,
([_key, value]) => value,
)
},
)
const hasOrganizations = computed(() => organizations.value.some(org => isSelectableOrganization(org.role)))
const getCurrentRole = async (appOwner: string, appId?: string, channelId?: number): Promise<OrganizationRole> => {
if (_organizations.value.size === 0) {
// eslint-disable-next-line ts/no-use-before-define
await fetchOrganizations()
}
for (const org of _organizations.value.values()) {
if (org.created_by === appOwner)
return org.role as OrganizationRole
}
throw new Error(`Cannot find role for (${appOwner}, ${appId}, ${channelId}))`)
}
// WARNING: currentOrganization does not guarantee correctness when used in an app-based URL
// For example if you try to use this value when fetching app channels it COULD BE incorrect
// When trying to fetch an organization in an app based component the following should be used
//
// const organization = ref(null as null | Organization)
// watchEffect(async () => {
// await organizationStore.awaitInitialLoad()
// organization.value = organizationStore.getOrgByAppId(appId.value) ?? null
// }
//
const currentOrganization = ref<Organization | undefined>(undefined)
const currentOrganizationFailed = ref(false)
const currentRole = ref<OrganizationRole | null>(null)
const STORAGE_KEY = 'capgo_current_org_id'
let organizationLogoLoadRun = 0
const getMemberImageKey = (member: { uid?: string | null, id?: number | string | null, email?: string | null }) => {
return String(member.uid ?? member.id ?? member.email ?? '')
}
const loadSignedMemberImages = async (
sources: Array<{ key: string, imageUrl?: string | null }>,
onSignedImages: SignedMemberImageCallback,
) => {
const signedImageEntries = await Promise.all(sources.map(async (source) => {
if (!source.key || !source.imageUrl || getImmediateImageUrl(source.imageUrl))
return null
try {
const signedImageUrl = await createSignedImageUrl(source.imageUrl)
return signedImageUrl ? [source.key, signedImageUrl] as const : null
}
catch (error) {
console.warn('Cannot load signed member image', { memberKey: source.key, error })
return null
}
}))
const signedImages = new Map<string, string>()
for (const entry of signedImageEntries) {
if (entry)
signedImages.set(entry[0], entry[1])
}
if (signedImages.size > 0)
onSignedImages(signedImages)
}
const updateOrganizationLogoState = (orgId: string, patch: Partial<Organization>, run: number) => {
if (run !== organizationLogoLoadRun)
return
const organization = _organizations.value.get(orgId)
if (!organization)
return
const hasChanges = Object.entries(patch).some(([key, value]) => organization[key as keyof Organization] !== value)
if (!hasChanges)
return
const nextOrganization = {
...organization,
...patch,
}
const nextOrganizations = new Map(_organizations.value)
nextOrganizations.set(orgId, nextOrganization)
_organizations.value = nextOrganizations
if (currentOrganization.value?.gid === orgId)
currentOrganization.value = nextOrganization
}
const loadOrganizationLogo = async (org: Organization & { id: number }, run: number) => {
const logoSource = org.logo_storage_path ?? org.logo
const { normalized, shouldSign } = resolveImagePath(logoSource)
if (!normalized || !shouldSign) {
updateOrganizationLogoState(org.gid, { logo_is_loading: false }, run)
return
}
try {
const signedLogo = await createSignedImageUrl(normalized)
updateOrganizationLogoState(org.gid, {
logo: signedLogo || org.logo,
logo_storage_path: normalized,
logo_is_loading: false,
}, run)
}
catch (error) {
console.warn('Cannot load signed organization logo', { orgId: org.gid, error })
updateOrganizationLogoState(org.gid, { logo_is_loading: false }, run)
}
}
const loadOrganizationLogos = (sourceOrganizations: Array<Organization & { id: number }>, run: number) => {
for (const org of sourceOrganizations) {
loadOrganizationLogo(org, run).catch((error) => {
console.warn('Cannot load signed organization logo', { orgId: org.gid, error })
updateOrganizationLogoState(org.gid, { logo_is_loading: false }, run)
})
}
}
watch([currentOrganization, stripeEnabled], async ([currentOrganizationRaw, stripeEnabledValue], [previousOrganization]) => {
if (!currentOrganizationRaw) {
currentRole.value = null
localStorage.removeItem(STORAGE_KEY)
return
}
localStorage.setItem(STORAGE_KEY, currentOrganizationRaw.gid)
currentRole.value = await getCurrentRole(currentOrganizationRaw.created_by)
// Don't mark as failed if user lacks 2FA or password access - the data is redacted and unreliable
const lacks2FAAccess = currentOrganizationRaw.enforcing_2fa === true && currentOrganizationRaw['2fa_has_access'] === false
const lacksPasswordAccess = currentOrganizationRaw.password_policy_config?.enabled && currentOrganizationRaw.password_has_access === false
if (lacks2FAAccess || lacksPasswordAccess || !stripeEnabledValue) {
currentOrganizationFailed.value = false
}
else {
currentOrganizationFailed.value = !(!!currentOrganizationRaw.paying || (currentOrganizationRaw.trial_left ?? 0) > 0 || !!currentOrganizationRaw.can_use_more)
}
// Clear caches when org changes to prevent showing stale data from other orgs
if (previousOrganization?.gid !== currentOrganizationRaw.gid) {
const displayStore = useDisplayStore()
displayStore.clearCachesForOrg(currentOrganizationRaw.gid)
// Reset and refetch dashboard apps for the new org
const dashboardAppsStore = useDashboardAppsStore()
dashboardAppsStore.reset()
// Fetch apps for the new org - don't await to avoid blocking other operations
dashboardAppsStore.fetchApps(true)
}
// Always fetch last 30 days of data and filter client-side for billing period
// End date should be tomorrow at midnight to include all of today's data
const last30DaysEnd = new Date()
last30DaysEnd.setHours(0, 0, 0, 0)
last30DaysEnd.setDate(last30DaysEnd.getDate() + 1) // Tomorrow midnight
const last30DaysStart = new Date()
last30DaysStart.setHours(0, 0, 0, 0)
last30DaysStart.setDate(last30DaysStart.getDate() - 29) // 30 days including today
try {
await main.updateDashboard(currentOrganizationRaw.gid, last30DaysStart.toISOString(), last30DaysEnd.toISOString())
}
catch (error) {
// Silently catch dashboard errors - they're logged elsewhere and shouldn't block UI
console.error('Failed to update dashboard:', error)
}
})
watch(_organizations, async (organizationsMap) => {
// Only run once - if we already have the app-to-org mapping, skip
if (_organizationsByAppId.value.size > 0)
return
const organizations = Array.from(organizationsMap.values())
const selectableOrganizations = organizations.filter(org => isSelectableOrganization(org.role))
const orgIds = selectableOrganizations.map(org => org.gid)
if (orgIds.length === 0) {
_initialLoadPromise.value.resolve(true)
return
}
const { error, data: allAppsByOwner } = await supabase
.from('apps')
.select('app_id, owner_org')
.in('owner_org', orgIds)
if (error) {
console.error('Cannot get app apps for org store', error)
return
}
const organizationsByAppId = new Map<string, Organization>()
for (const app of allAppsByOwner) {
// For each app find the org_id that owns said app
// This is needed for the "banner"
const org = selectableOrganizations.find(org => org.gid === app.owner_org)
if (!org) {
console.error(`Cannot find organization for app`, app)
_initialLoadPromise.value.reject(`Cannot find organization for app ${app}`)
return
}
organizationsByAppId.set(app.app_id, org)
}
_organizationsByAppId.value = organizationsByAppId
_initialLoadPromise.value.resolve(true)
})
const getOrgByAppId = (appId: string) => {
return _organizationsByAppId.value.get(appId)
}
const awaitInitialLoad = () => {
return _initialLoadPromise.value.promise
}
const getCurrentRoleForApp = (appId: string) => {
if (_organizationsByAppId.value.size < 1)
throw new Error('Organizations by app_id map is empty')
const org = getOrgByAppId(appId)
if (!org)
throw new Error(`Cannot find app ${appId} in the app_id -> org map`)
return org.role as OrganizationRole
}
const setCurrentOrganization = (id: string) => {
currentOrganization.value = organizations.value.find(org => org.gid === id)
}
const setCurrentOrganizationToMain = () => {
const organization = organizations.value.find(org => org.role === 'owner')
if (!organization)
throw new Error('User has no main organization')
setCurrentOrganization(organization.gid)
}
const setCurrentOrganizationToFirst = () => {
if (organizations.value.length === 0)
return
const organization = organizations.value[0]
setCurrentOrganization(organization.gid)
}
const getMembers = async (onSignedImages?: SignedMemberImageCallback): Promise<ExtendedOrganizationMembers> => {
const currentOrgId = currentOrganization.value?.gid
if (!currentOrgId)
return []
const { data, error } = await supabase
.rpc('get_org_members', {
guild_id: currentOrgId,
})
if (error || data === null) {
console.log('Cannot get org members!', error)
return []
}
const memberImageSources = data.map(item => ({
key: getMemberImageKey(item),
imageUrl: item.image_url,
}))
const mappedMembers = data.map((item, id) => ({
id,
...item,
image_url: getImmediateImageUrl(item.image_url) || '',
}))
if (onSignedImages) {
loadSignedMemberImages(memberImageSources, onSignedImages).catch((error) => {
console.warn('Cannot load signed member images', error)
})
}
return mappedMembers
}
const fetchOrganizations = async () => {
const main = useMainStore()
const userId = main.user?.id ?? main.auth?.id
if (!userId)
return
if (!_initialized.value) {
const listener = supabase.auth.onAuthStateChange((event: any) => {
if (event === 'SIGNED_OUT') {
listener.data.subscription.unsubscribe()
// Remove all from orgs
_organizations.value = new Map()
_organizationsByAppId.value = new Map()
_initialLoadPromise.value = createDeferredPromise<boolean>()
currentOrganization.value = undefined
currentRole.value = null
}
})
_initialized.value = true
}
// We have RLS that ensure that we only select rows where we are member or owner
// Using get_orgs_v7 which includes 2FA and password policy fields
const { data, error } = await supabase
.rpc('get_orgs_v7')
if (error) {
console.error('Cannot get orgs!', error)
throw error
}
const logoLoadRun = ++organizationLogoLoadRun
const mappedData = data.map((item, id) => {
const { normalized: logoStoragePath, shouldSign: shouldSignLogo } = resolveImagePath(item.logo)
return {
id,
...item,
logo: getImmediateImageUrl(item.logo) || null,
logo_storage_path: logoStoragePath || null,
logo_is_loading: shouldSignLogo,
password_policy_config: item.password_policy_config as PasswordPolicyConfig | null,
} as Organization & { id: number }
})
_organizations.value = new Map(mappedData.map(item => [item.gid, item as Organization]))
loadOrganizationLogos(mappedData, logoLoadRun)
const selectableOrganizations = mappedData
.filter(org => isSelectableOrganization(org.role))
.sort((a, b) => b.app_count - a.app_count)
const organization = selectableOrganizations[0]
if (!organization) {
// Keep invitation-only organizations available so invite deep links
// can still open the accept-invite dialog before the user joins.
currentOrganization.value = undefined
currentRole.value = null
currentOrganizationFailed.value = false
_organizationsByAppId.value = new Map()
_initialLoadPromise.value.resolve(true)
return
}
// Try to restore from localStorage first
let targetOrgId = currentOrganization.value?.gid
if (!targetOrgId) {
const storedOrgId = localStorage.getItem(STORAGE_KEY)
if (storedOrgId) {
const storedOrg = mappedData.find(org => org.gid === storedOrgId && isSelectableOrganization(org.role))
if (storedOrg) {
targetOrgId = storedOrg.gid
}
}
}
targetOrgId ||= organization.gid
currentOrganization.value = mappedData.find(org => org.gid === targetOrgId) as Organization | undefined
// Don't mark as failed if user lacks 2FA or password access - the data is redacted and unreliable
const lacks2FAAccess = currentOrganization.value?.enforcing_2fa === true && currentOrganization.value?.['2fa_has_access'] === false
const lacksPasswordAccess = currentOrganization.value?.password_policy_config?.enabled && currentOrganization.value?.password_has_access === false
if (lacks2FAAccess || lacksPasswordAccess) {
currentOrganizationFailed.value = false
}
else {
currentOrganizationFailed.value = !(!!currentOrganization.value?.paying || (currentOrganization.value?.trial_left ?? 0) > 0 || !!currentOrganization.value?.can_use_more)
}
}
const refreshOrganizationLogos = async () => {
if (_organizations.value.size === 0)
return
const nextOrganizations = new Map(_organizations.value)
let updated = false
for (const [orgId, org] of nextOrganizations.entries()) {
const logoSource = org.logo_storage_path ?? org.logo
if (!logoSource)
continue
const logoStoragePath = resolveImagePath(logoSource).normalized
const refreshedLogo = await createSignedImageUrl(logoStoragePath || org.logo, { forceRefresh: true })
if (!refreshedLogo || refreshedLogo === org.logo)
continue
nextOrganizations.set(orgId, {
...org,
logo: refreshedLogo,
logo_storage_path: logoStoragePath || null,
logo_is_loading: false,
})
updated = true
}
if (!updated)
return
_organizations.value = nextOrganizations
if (currentOrganization.value) {
const refreshedCurrentOrganization = nextOrganizations.get(currentOrganization.value.gid)
if (refreshedCurrentOrganization) {
currentOrganization.value.logo = refreshedCurrentOrganization.logo
currentOrganization.value.logo_storage_path = refreshedCurrentOrganization.logo_storage_path
}
}
}
const dedupFetchOrganizations = async () => {
if (_organizations.value.size === 0)
await fetchOrganizations()
}
const getAllOrgs = () => {
return _organizations.value
}
const hasPermissionsInRole = (
minRight: LegacyMinRight,
requiredRoles: string[] = [],
orgId?: string,
appId?: string,
) => {
const orgFromApp = appId ? getOrgByAppId(appId) : undefined
const org = orgId ? _organizations.value.get(orgId) : (orgFromApp ?? currentOrganization.value)
const role = org?.role ?? currentRole.value
if (!role)
return false
if (org?.use_new_rbac && requiredRoles.length > 0) {
if (requiredRoles.some(required => matchesRbacRole(role, required)))
return true
}
return roleHasLegacyMinRight(role, minRight)
}
// Check password policy compliance for all org members (for super_admin preview)
const checkPasswordPolicyImpact = async (orgId: string) => {
const { data, error } = await supabase.rpc('check_org_members_password_policy', {
org_id: orgId,
})
if (error) {
console.error('Failed to check password policy impact:', error)
return null
}
return {
totalUsers: data.length,
compliantUsers: data.filter(u => u.password_policy_compliant),
nonCompliantUsers: data.filter(u => !u.password_policy_compliant),
}
}
const canDeleteOrganization = (orgId?: string) => {
return hasPermissionsInRole('super_admin', ['org_super_admin'], orgId)
}
const deleteOrganization = async (orgId: string) => {
// Validate input
if (!orgId || typeof orgId !== 'string' || orgId.trim() === '') {
return { data: null, error: new Error('Invalid organization ID') }
}
// Check if current user has permission to delete this organization
const currentUserId = main.user?.id
if (!currentUserId) {
return { data: null, error: new Error('User not authenticated') }
}
// Verify user has super_admin or owner role for this organization
const currentOrg = _organizations.value.get(orgId)
console.log('Delete org check:', { orgId, currentOrg, role: currentOrg?.role, userId: currentUserId })
if (!currentOrg || !canDeleteOrganization(orgId)) {
console.error('Permission denied:', { role: currentOrg?.role, required: ['super_admin', 'owner', 'org_super_admin'] })
return { data: null, error: new Error('Insufficient permissions') }
}
const { data, error } = await supabase.from('orgs')
.delete()
.eq('id', orgId)
if (error) {
console.error('Organization deletion failed:', error.message)
return { data, error }
}
return { data, error: null }
}
return {
organizations,
currentOrganization,
currentOrganizationFailed,
currentRole,
setCurrentOrganization,
setCurrentOrganizationToMain,
setCurrentOrganizationToFirst,
getMembers,
getCurrentRoleForApp,
getAllOrgs,
hasPermissionsInRole,
fetchOrganizations,
refreshOrganizationLogos,
dedupFetchOrganizations,
getOrgByAppId,
awaitInitialLoad,
deleteOrganization,
canDeleteOrganization,
checkPasswordPolicyImpact,
hasOrganizations,
}
})