| 1 | import { type Database, schema } from '@ghost/db'; |
| 2 | import { eq } |
| 3 | |
| 4 | import { organizationMembership } |
| 5 | import { administers, organizationRoleOf |
| 6 | import { |
| 7 | OrganizationForbiddenError, |
| 8 | OrganizationNotFoundError, |
| 9 | } from './organization.errors.js'; |
| 10 | |
| 11 | type Visibility |
| 12 | |
| 13 | /** The requester's standing in the organization behind `slug`, with its policies. Outsiders get a 404, the way repositories answer. */ |
| 14 | export async function membershipIn |
| 15 | db: Pick |
| 16 | slug: string, |
| 17 | userId: string, |
| 18 | ) { |
| 19 | const [membership] |
| 20 | .select({ |
| 21 | organizationId: schema.organization |
| 22 | memberRole: schema.member |
| 23 | settings: schema.organizationSettings |
| 24 | }) |
| 25 | .from(schema.organization |
| 26 | .leftJoin( |
| 27 | schema.member, |
| 28 | organizationMembership(schema.organization |
| 29 | ) |
| 30 | .leftJoin( |
| 31 | schema.organizationSettings, |
| 32 | eq(schema.organizationSettings |
| 33 | ) |
| 34 | .where(eq(schema |
| 35 | |
| 36 | if (!membership?.memberRole |
| 37 | return { ...membership |
| 38 | } |
| 39 | |
| 40 | /** The organization behind `slug`, if `userId` administers it; members below admin get a 403. */ |
| 41 | export async function administeredOrganization |
| 42 | db: Pick |
| 43 | slug: string, |
| 44 | userId: string, |
| 45 | ) { |
| 46 | const { organizationId, |
| 47 | db, |
| 48 | slug, |
| 49 | userId, |
| 50 | ); |
| 51 | if (!administers(role |
| 52 | throw new OrganizationForbiddenError() |
| 53 | } |
| 54 | return { organizationId, |
| 55 | } |
| 56 | |
| 57 | /** Where `userId` may create a repository of `visibility` in the organization: always for its admins, and for members as far as its policy allows. */ |
| 58 | export async function organizationToCreateIn |
| 59 | db: Pick |
| 60 | slug: string, |
| 61 | userId: string, |
| 62 | visibility: Visibility |
| 63 | ) { |
| 64 | const { organizationId, |
| 65 | db, |
| 66 | slug, |
| 67 | userId, |
| 68 | ); |
| 69 | const allowed = |
| 70 | administers(role) || |
| 71 | (role === 'member |
| 72 | (visibility === 'public |
| 73 | ? settings?.membersCanCreatePublicRepositories |
| 74 | : settings?.membersCanCreatePrivateRepositories)) |
| 75 | if (!allowed) |
| 76 | return { organizationId, |
| 77 | } |