| 36 | * or an error response on failure. |
| 37 | */ |
| 38 | export async function validateEnterpriseAuditAccess(userId: string): Promise<AuthResult> { |
| 39 | const [membership] = await db |
| 40 | .select({ organizationId: member.organizationId, role: member.role }) |
| 41 | .from(member) |
| 42 | .where(eq(member.userId, userId)) |
| 43 | .limit(1) |
| 44 | |
| 45 | if (!membership) { |
| 46 | return { |
| 47 | success: false, |
| 48 | response: NextResponse.json({ error: 'Not a member of any organization' }, { status: 403 }), |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | if (membership.role !== 'admin' && membership.role !== 'owner') { |
| 53 | return { |
| 54 | success: false, |
| 55 | response: NextResponse.json( |
| 56 | { error: 'Organization admin or owner role required' }, |
| 57 | { status: 403 } |
| 58 | ), |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | const billingStatus = await getEffectiveBillingStatus(userId) |
| 63 | if (billingStatus.billingBlocked) { |
| 64 | return { |
| 65 | success: false, |
| 66 | response: NextResponse.json( |
| 67 | { error: 'Active enterprise subscription required' }, |
| 68 | { status: 403 } |
| 69 | ), |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | const [orgSub, orgMembers] = await Promise.all([ |
| 74 | db |
| 75 | .select({ id: subscription.id }) |
| 76 | .from(subscription) |
| 77 | .where( |
| 78 | and( |
| 79 | eq(subscription.referenceId, membership.organizationId), |
| 80 | eq(subscription.plan, 'enterprise'), |
| 81 | inArray(subscription.status, USABLE_SUBSCRIPTION_STATUSES) |
| 82 | ) |
| 83 | ) |
| 84 | .limit(1), |
| 85 | db |
| 86 | .select({ userId: member.userId }) |
| 87 | .from(member) |
| 88 | .where(eq(member.organizationId, membership.organizationId)), |
| 89 | ]) |
| 90 | |
| 91 | if (orgSub.length === 0) { |
| 92 | return { |
| 93 | success: false, |
| 94 | response: NextResponse.json( |
| 95 | { error: 'Active enterprise subscription required' }, |