Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): enforce roles and pro defaults in organization mutations

Richie McIlroyb50ec9489f71
diff --git a/apps/web/actions/organization/check-domain.ts b/apps/web/actions/organization/check-domain.ts
index c7041c643..81b7087c5 100644
--- a/apps/web/actions/organization/check-domain.ts
+++ b/apps/web/actions/organization/check-domain.ts
@@ -5,6 +5,7 @@ import { getCurrentUser } from "@cap/database/auth/session";
import { organizations } from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
+import { requireOrganizationSettingsManager } from "./authorization";
import { checkDomainStatus } from "./domain-utils";
export async function checkOrganizationDomain(
@@ -21,9 +22,9 @@ export async function checkOrganizationDomain(
.from(organizations)
.where(eq(organizations.id, organizationId));
- if (!organization || organization.ownerId !== user.id) {
- throw new Error("Only the owner can check domain status");
- }
+ if (!organization) throw new Error("Organization not found");
+
+ await requireOrganizationSettingsManager(user.id, organizationId);
if (!organization.customDomain) {
throw new Error("No custom domain set");
diff --git a/apps/web/actions/organization/create-space.ts b/apps/web/actions/organization/create-space.ts
index 132bb383f..032e9e4c4 100644
--- a/apps/web/actions/organization/create-space.ts
+++ b/apps/web/actions/organization/create-space.ts
@@ -76,7 +76,6 @@ export async function createSpace(
};
}
- // Check for duplicate space name in the same organization
const existingSpace = await db()
.select({ id: spaces.id })
.from(spaces)
@@ -95,7 +94,6 @@ export async function createSpace(
};
}
- // Generate the space ID early so we can use it in the file path
const spaceId = Space.SpaceId.make(nanoId());
let iconUrl: ImageUpload.ImageUrlOrKey | null = null;
const hashedPassword =
@@ -104,7 +102,6 @@ export async function createSpace(
: null;
await db().transaction(async (tx) => {
- // Create the space first
await tx.insert(spaces).values({
id: spaceId,
name,
@@ -115,8 +112,6 @@ export async function createSpace(
password: hashedPassword,
});
- // --- Member Management Logic ---
- // Collect member user IDs from formData
const memberUserIds: string[] = [];
for (const entry of formData.getAll("members[]")) {
if (typeof entry === "string" && entry.length > 0) {
@@ -124,16 +119,13 @@ export async function createSpace(
}
}
- // Always add the creator as Admin (if not already in the list)
if (!memberUserIds.includes(user.id)) {
memberUserIds.push(user.id);
}
- // Create space members
if (memberUserIds.length > 0) {
const spaceMembersToInsert = memberUserIds.map((userId) => {
- // Creator is always Admin, others are member
- const role: SpaceMemberRole = userId === user.id ? "Admin" : "member";
+ const role: SpaceMemberRole = userId === user.id ? "admin" : "member";
return {
id: SpaceMemberId.make(nanoId()),
spaceId,
diff --git a/apps/web/actions/organization/delete-space.ts b/apps/web/actions/organization/delete-space.ts
index 4d2c5ef3b..24239eefd 100644
--- a/apps/web/actions/organization/delete-space.ts
+++ b/apps/web/actions/organization/delete-space.ts
@@ -14,6 +14,7 @@ import { eq } from "drizzle-orm";
import { Effect, Option } from "effect";
import { revalidatePath } from "next/cache";
import { runPromise } from "@/lib/server";
+import { requireSpaceManager } from "./space-authorization";
interface DeleteSpaceResponse {
success: boolean;
@@ -33,7 +34,6 @@ export async function deleteSpace(
};
}
- // Check if the space exists and belongs to the user's organization
const space = await db()
.select()
.from(spaces)
@@ -47,28 +47,23 @@ export async function deleteSpace(
};
}
- // Check if user has permission to delete the space
- // Only the space creator or organization owner should be able to delete spaces
const spaceData = space[0];
- if (!spaceData || spaceData.createdById !== user.id) {
+ const access = await requireSpaceManager(user.id, spaceId).catch(
+ () => null,
+ );
+ if (!spaceData || !access) {
return {
success: false,
error: "You don't have permission to delete this space",
};
}
- // Delete in order to maintain referential integrity:
-
- // 1. First delete all space videos
await db().delete(spaceVideos).where(eq(spaceVideos.spaceId, spaceId));
- // 2. Delete all space members
await db().delete(spaceMembers).where(eq(spaceMembers.spaceId, spaceId));
- // 3. Delete all space folders
await db().delete(folders).where(eq(folders.spaceId, spaceId));
- // 4. Delete space icons from S3
try {
await Effect.gen(function* () {
const [bucket] = yield* S3Buckets.getBucketAccess(Option.none());
@@ -89,11 +84,8 @@ export async function deleteSpace(
);
}
}).pipe(runPromise);
-
- // List all objects with the space prefix
} catch (error) {
console.error("Error deleting space icons from S3:", error);
- // Continue with space deletion even if S3 deletion fails
}
await db().delete(spaces).where(eq(spaces.id, spaceId));
diff --git a/apps/web/actions/organization/remove-domain.ts b/apps/web/actions/organization/remove-domain.ts
index 1f4cdd97a..5d1c051bc 100644
--- a/apps/web/actions/organization/remove-domain.ts
+++ b/apps/web/actions/organization/remove-domain.ts
@@ -6,6 +6,7 @@ import { organizations } from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import { requireOrganizationSettingsManager } from "./authorization";
export async function removeOrganizationDomain(
organizationId: Organisation.OrganisationId,
@@ -21,9 +22,9 @@ export async function removeOrganizationDomain(
.from(organizations)
.where(eq(organizations.id, organizationId));
- if (!organization || organization.ownerId !== user.id) {
- throw new Error("Only the owner can remove the custom domain");
- }
+ if (!organization) throw new Error("Organization not found");
+
+ await requireOrganizationSettingsManager(user.id, organizationId);
try {
if (organization.customDomain) {
diff --git a/apps/web/actions/organization/remove-invite.ts b/apps/web/actions/organization/remove-invite.ts
index 81db8dfd6..1eb795f5c 100644
--- a/apps/web/actions/organization/remove-invite.ts
+++ b/apps/web/actions/organization/remove-invite.ts
@@ -6,6 +6,7 @@ import { organizationInvites, organizations } from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import { requireOrganizationSettingsManager } from "./authorization";
export async function removeOrganizationInvite(
inviteId: string,
@@ -27,9 +28,7 @@ export async function removeOrganizationInvite(
throw new Error("Organization not found");
}
- if (organization[0]?.ownerId !== user.id) {
- throw new Error("Only the owner can remove organization invites");
- }
+ await requireOrganizationSettingsManager(user.id, organizationId);
const [result] = await db()
.delete(organizationInvites)
diff --git a/apps/web/actions/organization/remove-member.ts b/apps/web/actions/organization/remove-member.ts
index a01e4af29..1299c3af1 100644
--- a/apps/web/actions/organization/remove-member.ts
+++ b/apps/web/actions/organization/remove-member.ts
@@ -2,16 +2,20 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
-import { organizationMembers, organizations } from "@cap/database/schema";
+import {
+ organizationMembers,
+ spaceMembers,
+ spaces,
+} from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
-import { and, eq } from "drizzle-orm";
+import { and, eq, inArray } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import {
+ canRemoveOrganizationMember,
+ getEffectiveOrganizationRole,
+} from "@/lib/permissions/roles";
+import { requireOrganizationSettingsManager } from "./authorization";
-/**
- * Remove a member from an organization. Only the owner can perform this action.
- * @param memberId The organizationMembers.id to remove
- * @param organizationId The organization to remove from
- */
export async function removeOrganizationMember(
memberId: string,
organizationId: Organisation.OrganisationId,
@@ -19,22 +23,17 @@ export async function removeOrganizationMember(
const user = await getCurrentUser();
if (!user) throw new Error("Unauthorized");
- const organization = await db()
- .select()
- .from(organizations)
- .where(eq(organizations.id, organizationId))
- .limit(1);
-
- if (!organization || organization.length === 0) {
- throw new Error("Organization not found");
- }
- if (organization[0]?.ownerId !== user.id) {
- throw new Error("Only the owner can remove organization members");
- }
+ const actor = await requireOrganizationSettingsManager(
+ user.id,
+ organizationId,
+ );
- // Prevent owner from removing themselves
- const member = await db()
- .select()
+ const [member] = await db()
+ .select({
+ id: organizationMembers.id,
+ userId: organizationMembers.userId,
+ role: organizationMembers.role,
+ })
.from(organizationMembers)
.where(
and(
@@ -43,25 +42,60 @@ export async function removeOrganizationMember(
),
)
.limit(1);
- if (!member || member.length === 0) {
+
+ if (!member) {
throw new Error("Member not found");
}
- if (member[0]?.userId === user.id) {
- // Defensive: this should never happen due to the above check, but TS wants safety
- throw new Error("Owner cannot remove themselves");
+
+ const targetRole = getEffectiveOrganizationRole({
+ userId: member.userId,
+ ownerId: actor.ownerId,
+ memberRole: member.role,
+ });
+
+ if (
+ !canRemoveOrganizationMember({
+ actorRole: actor.role,
+ actorUserId: user.id,
+ targetUserId: member.userId,
+ ownerId: actor.ownerId,
+ targetRole,
+ })
+ ) {
+ throw new Error("You do not have permission to remove this member");
}
- const [result] = await db()
- .delete(organizationMembers)
- .where(
- and(
- eq(organizationMembers.id, memberId),
- eq(organizationMembers.organizationId, organizationId),
- ),
- );
+ await db().transaction(async (tx) => {
+ const organizationSpaces = await tx
+ .select({ id: spaces.id })
+ .from(spaces)
+ .where(eq(spaces.organizationId, organizationId));
+ const spaceIds = organizationSpaces.map((space) => space.id);
+
+ if (spaceIds.length > 0) {
+ await tx
+ .delete(spaceMembers)
+ .where(
+ and(
+ eq(spaceMembers.userId, member.userId),
+ inArray(spaceMembers.spaceId, spaceIds),
+ ),
+ );
+ }
+
+ const [result] = await tx
+ .delete(organizationMembers)
+ .where(
+ and(
+ eq(organizationMembers.id, memberId),
+ eq(organizationMembers.organizationId, organizationId),
+ ),
+ );
- if (result.affectedRows === 0) throw new Error("Member not found");
+ if (result.affectedRows === 0) throw new Error("Member not found");
+ });
revalidatePath("/dashboard/settings/organization");
+ revalidatePath("/dashboard");
return { success: true };
}
diff --git a/apps/web/actions/organization/send-invites.ts b/apps/web/actions/organization/send-invites.ts
index 6ec05bb77..800369c0a 100644
--- a/apps/web/actions/organization/send-invites.ts
+++ b/apps/web/actions/organization/send-invites.ts
@@ -15,10 +15,21 @@ import { serverEnv } from "@cap/env";
import type { Organisation } from "@cap/web-domain";
import { and, eq, inArray } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import {
+ type AssignableOrganizationRole,
+ normalizeAssignableOrganizationRole,
+} from "@/lib/permissions/roles";
+import { requireOrganizationSettingsManager } from "./authorization";
+
+type OrganizationInviteInput = {
+ email: string;
+ role?: string | null;
+};
export async function sendOrganizationInvites(
- invitedEmails: string[],
+ inviteInputs: string[] | OrganizationInviteInput[],
organizationId: Organisation.OrganisationId,
+ roleInput = "member",
) {
const user = await getCurrentUser();
@@ -26,6 +37,11 @@ export async function sendOrganizationInvites(
throw new Error("Unauthorized");
}
+ const role = normalizeAssignableOrganizationRole(roleInput);
+ if (!role) {
+ throw new Error("Invalid organization role");
+ }
+
const [organization] = await db()
.select()
.from(organizations)
@@ -35,23 +51,39 @@ export async function sendOrganizationInvites(
throw new Error("Organization not found");
}
- if (organization.ownerId !== user.id) {
- throw new Error("Only the organization owner can send invites");
- }
+ await requireOrganizationSettingsManager(user.id, organizationId);
const MAX_INVITES = 50;
- if (invitedEmails.length > MAX_INVITES) {
+ if (inviteInputs.length > MAX_INVITES) {
throw new Error(`Cannot send more than ${MAX_INVITES} invites at once`);
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
- const validEmails = Array.from(
- new Set(
- invitedEmails
- .map((email) => email.trim().toLowerCase())
- .filter((email) => emailRegex.test(email)),
- ),
- );
+ const inviteMap = new Map<string, AssignableOrganizationRole>();
+
+ for (const inviteInput of inviteInputs) {
+ const email =
+ typeof inviteInput === "string" ? inviteInput : inviteInput.email;
+ const normalizedEmail = email.trim().toLowerCase();
+ if (!emailRegex.test(normalizedEmail)) continue;
+
+ const inviteRole =
+ typeof inviteInput === "string" || !inviteInput.role
+ ? role
+ : normalizeAssignableOrganizationRole(inviteInput.role);
+
+ if (!inviteRole) {
+ throw new Error("Invalid organization role");
+ }
+
+ inviteMap.set(normalizedEmail, inviteRole);
+ }
+
+ const validInvites = Array.from(inviteMap, ([email, inviteRole]) => ({
+ email,
+ role: inviteRole,
+ }));
+ const validEmails = validInvites.map((invite) => invite.email);
if (validEmails.length === 0) {
return { success: true, failedEmails: [] as string[] };
@@ -88,14 +120,16 @@ export async function sendOrganizationInvites(
existingMembers.map((m) => m.email.toLowerCase()),
);
- const emailsToInvite = validEmails.filter(
- (email) =>
- !existingInviteEmails.has(email) && !existingMemberEmails.has(email),
+ const invitesToSend = validInvites.filter(
+ (invite) =>
+ !existingInviteEmails.has(invite.email) &&
+ !existingMemberEmails.has(invite.email),
);
- const records = emailsToInvite.map((email) => ({
+ const records = invitesToSend.map((invite) => ({
id: nanoId(),
- email,
+ email: invite.email,
+ role: invite.role,
}));
if (records.length > 0) {
@@ -105,7 +139,7 @@ export async function sendOrganizationInvites(
organizationId: organizationId,
invitedEmail: r.email,
invitedByUserId: user.id,
- role: "member" as const,
+ role: r.role,
})),
);
}
diff --git a/apps/web/actions/organization/settings.ts b/apps/web/actions/organization/settings.ts
index 212b712fb..6e3b8901a 100644
--- a/apps/web/actions/organization/settings.ts
+++ b/apps/web/actions/organization/settings.ts
@@ -3,17 +3,46 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { organizations } from "@cap/database/schema";
+import { userIsPro } from "@cap/utils";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import { requireOrganizationSettingsManager } from "./authorization";
-export async function updateOrganizationSettings(settings: {
+type OrganizationSettingsInput = {
disableSummary?: boolean;
disableCaptions?: boolean;
disableChapters?: boolean;
disableReactions?: boolean;
disableTranscript?: boolean;
disableComments?: boolean;
-}) {
+ hideShareableLinkCapLogo?: boolean;
+ shareableLinkUseOrganizationIcon?: boolean;
+};
+
+const proOrganizationSettingKeys = [
+ "disableSummary",
+ "disableChapters",
+ "disableTranscript",
+ "hideShareableLinkCapLogo",
+ "shareableLinkUseOrganizationIcon",
+] as const satisfies readonly (keyof OrganizationSettingsInput)[];
+
+const preserveProSettings = (
+ submittedSettings: OrganizationSettingsInput,
+ existingSettings: OrganizationSettingsInput | null | undefined,
+) => ({
+ ...submittedSettings,
+ ...Object.fromEntries(
+ proOrganizationSettingKeys.map((key) => [
+ key,
+ existingSettings?.[key] ?? false,
+ ]),
+ ),
+});
+
+export async function updateOrganizationSettings(
+ settings: OrganizationSettingsInput,
+) {
const user = await getCurrentUser();
if (!user) {
@@ -24,6 +53,10 @@ export async function updateOrganizationSettings(settings: {
throw new Error("Settings are required");
}
+ if (!user.activeOrganizationId) {
+ throw new Error("Organization not found");
+ }
+
const [organization] = await db()
.select()
.from(organizations)
@@ -33,12 +66,20 @@ export async function updateOrganizationSettings(settings: {
throw new Error("Organization not found");
}
+ await requireOrganizationSettingsManager(user.id, user.activeOrganizationId);
+
+ const nextSettings = userIsPro(user)
+ ? settings
+ : preserveProSettings(settings, organization.settings);
+
await db()
.update(organizations)
- .set({ settings })
+ .set({ settings: nextSettings })
.where(eq(organizations.id, user.activeOrganizationId));
revalidatePath("/dashboard/caps");
+ revalidatePath("/dashboard/settings/organization");
+ revalidatePath("/dashboard/settings/organization/preferences");
return { success: true };
}
diff --git a/apps/web/actions/organization/storage.ts b/apps/web/actions/organization/storage.ts
index b1da6ac6a..a39448033 100644
--- a/apps/web/actions/organization/storage.ts
+++ b/apps/web/actions/organization/storage.ts
@@ -26,6 +26,7 @@ import { type Organisation, S3Bucket, Storage } from "@cap/web-domain";
import { and, desc, eq, isNull } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { runPromise } from "@/lib/server";
+import { requireOrganizationSettingsManager } from "./authorization";
const googleDriveProvider = "googleDrive";
const settingsPath = "/dashboard/settings/organization/integrations";
@@ -85,7 +86,7 @@ export type OrganizationGoogleDriveFolder = {
const googleDriveFolderMimeType = "application/vnd.google-apps.folder";
const driveApiBase = "https://www.googleapis.com/drive/v3";
-const requireOrganizationOwner = async (
+const requireOrganizationStorageManager = async (
organizationId: Organisation.OrganisationId,
) => {
const user = await getCurrentUser();
@@ -107,17 +108,15 @@ const requireOrganizationOwner = async (
.limit(1);
if (!organization) throw new Error("Organization not found");
- if (organization.ownerId !== user.id) {
- throw new Error("Only the owner can manage organization storage");
- }
+ await requireOrganizationSettingsManager(user.id, organizationId);
return { user, organization };
};
-const requireOrganizationOwnerPro = async (
+const requireOrganizationStorageManagerPro = async (
organizationId: Organisation.OrganisationId,
) => {
- const result = await requireOrganizationOwner(organizationId);
+ const result = await requireOrganizationStorageManager(organizationId);
if (!userIsPro(result.user)) throw new Error(proRequiredMessage);
return result;
};
@@ -344,7 +343,8 @@ const createGoogleDriveState = (
export async function getOrganizationStorageSettings(
organizationId: Organisation.OrganisationId,
): Promise<OrganizationStorageSettings> {
- const { organization } = await requireOrganizationOwner(organizationId);
+ const { organization } =
+ await requireOrganizationStorageManager(organizationId);
const [bucket, drive, activeDrive] = await Promise.all([
getOrganizationBucket(organizationId),
getOrganizationDrive(organizationId),
@@ -381,7 +381,9 @@ export async function getOrganizationStorageSettings(
}
export async function saveOrganizationS3Config(input: S3ConfigInput) {
- const { user } = await requireOrganizationOwnerPro(input.organizationId);
+ const { user } = await requireOrganizationStorageManagerPro(
+ input.organizationId,
+ );
const credentials = await getS3InputCredentials(input);
const encryptedConfig = {
provider: input.provider,
@@ -413,7 +415,7 @@ export async function saveOrganizationS3Config(input: S3ConfigInput) {
export async function removeOrganizationS3Config(
organizationId: Organisation.OrganisationId,
) {
- await requireOrganizationOwnerPro(organizationId);
+ await requireOrganizationStorageManagerPro(organizationId);
await db()
.update(s3Buckets)
.set({ active: false })
@@ -423,7 +425,7 @@ export async function removeOrganizationS3Config(
}
export async function testOrganizationS3Config(input: S3ConfigInput) {
- await requireOrganizationOwnerPro(input.organizationId);
+ await requireOrganizationStorageManagerPro(input.organizationId);
const credentials = await getS3InputCredentials(input);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
@@ -455,7 +457,7 @@ export async function setOrganizationStorageProvider({
organizationId: Organisation.OrganisationId;
provider: OrganizationStorageProvider;
}) {
- await requireOrganizationOwnerPro(organizationId);
+ await requireOrganizationStorageManagerPro(organizationId);
if (provider === "s3") {
const bucket = await getOrganizationBucket(organizationId);
@@ -495,7 +497,7 @@ export async function setOrganizationStorageProvider({
export async function connectOrganizationGoogleDrive(
organizationId: Organisation.OrganisationId,
) {
- const { user } = await requireOrganizationOwnerPro(organizationId);
+ const { user } = await requireOrganizationStorageManagerPro(organizationId);
const state = createGoogleDriveState(user.id, organizationId);
return { url: getGoogleDriveAuthUrl({ state }) };
}
@@ -503,7 +505,7 @@ export async function connectOrganizationGoogleDrive(
export async function disconnectOrganizationGoogleDrive(
organizationId: Organisation.OrganisationId,
) {
- await requireOrganizationOwnerPro(organizationId);
+ await requireOrganizationStorageManagerPro(organizationId);
await db()
.update(storageIntegrations)
.set({
@@ -529,7 +531,7 @@ export async function disconnectOrganizationGoogleDrive(
export async function getOrganizationGoogleDrivePickerToken(
organizationId: Organisation.OrganisationId,
) {
- await requireOrganizationOwnerPro(organizationId);
+ await requireOrganizationStorageManagerPro(organizationId);
const drive = await getOrganizationDrive(organizationId);
if (!drive || drive.status !== "active") {
throw new Error("Google Drive is not connected");
@@ -556,7 +558,7 @@ export async function listOrganizationGoogleDriveFolders({
organizationId: Organisation.OrganisationId;
parentId?: string;
}) {
- await requireOrganizationOwnerPro(organizationId);
+ await requireOrganizationStorageManagerPro(organizationId);
const drive = await getOrganizationDrive(organizationId);
if (!drive || drive.status !== "active") {
throw new Error("Google Drive is not connected");
@@ -618,7 +620,7 @@ export async function setOrganizationGoogleDriveLocation({
driveId?: string | null;
driveName?: string | null;
}) {
- const { user } = await requireOrganizationOwnerPro(organizationId);
+ const { user } = await requireOrganizationStorageManagerPro(organizationId);
const drive = await getOrganizationDrive(organizationId);
if (!drive || drive.status !== "active") {
throw new Error("Google Drive is not connected");
diff --git a/apps/web/actions/organization/update-details.ts b/apps/web/actions/organization/update-details.ts
index 0156e2654..f156ca215 100644
--- a/apps/web/actions/organization/update-details.ts
+++ b/apps/web/actions/organization/update-details.ts
@@ -6,6 +6,7 @@ import { organizations } from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import { requireOrganizationSettingsManager } from "./authorization";
export async function updateOrganizationDetails({
organizationName,
@@ -31,9 +32,7 @@ export async function updateOrganizationDetails({
throw new Error("Organization not found");
}
- if (organization[0]?.ownerId !== user.id) {
- throw new Error("Only the owner can update organization details");
- }
+ await requireOrganizationSettingsManager(user.id, organizationId);
if (organizationName) {
await db()
diff --git a/apps/web/actions/organization/update-domain.ts b/apps/web/actions/organization/update-domain.ts
index d51adb7ce..7ca542c9c 100644
--- a/apps/web/actions/organization/update-domain.ts
+++ b/apps/web/actions/organization/update-domain.ts
@@ -7,6 +7,7 @@ import { userIsPro } from "@cap/utils";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
+import { requireOrganizationSettingsManager } from "./authorization";
import { addDomain, checkDomainStatus } from "./domain-utils";
export async function updateDomain(
@@ -28,9 +29,9 @@ export async function updateDomain(
.from(organizations)
.where(eq(organizations.id, organizationId));
- if (!organization || organization.ownerId !== user.id) {
- throw new Error("Only the owner can update the custom domain");
- }
+ if (!organization) throw new Error("Organization not found");
+
+ await requireOrganizationSettingsManager(user.id, organizationId);
// Check if domain is already being used by another organization
const existingDomain = await db()
diff --git a/apps/web/actions/organization/update-space.ts b/apps/web/actions/organization/update-space.ts
index 7af003907..9dd84e615 100644
--- a/apps/web/actions/organization/update-space.ts
+++ b/apps/web/actions/organization/update-space.ts
@@ -13,10 +13,12 @@ import {
type SpaceMemberRole,
type User,
} from "@cap/web-domain";
-import { and, eq } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import { Effect, Option } from "effect";
import { revalidatePath } from "next/cache";
+import { normalizeSpaceRole } from "@/lib/permissions/roles";
import { runPromise } from "@/lib/server";
+import { requireSpaceManager } from "./space-authorization";
import {
getSpaceSettingsFromFormData,
preserveProSpaceSettings,
@@ -52,14 +54,8 @@ export async function updateSpace(formData: FormData) {
return { success: false, error: "Space not found" };
}
- const isCreator = space.createdById === user.id;
- const [membership] = await db()
- .select({ role: spaceMembers.role })
- .from(spaceMembers)
- .where(and(eq(spaceMembers.spaceId, id), eq(spaceMembers.userId, user.id)))
- .limit(1);
-
- if (!isCreator && membership?.role !== "Admin") {
+ const access = await requireSpaceManager(user.id, id).catch(() => null);
+ if (!access) {
return { success: false, error: "Unauthorized" };
}
@@ -92,6 +88,16 @@ export async function updateSpace(formData: FormData) {
await db().update(spaces).set(spaceUpdate).where(eq(spaces.id, id));
const memberIds = Array.from(new Set([...members, space.createdById]));
+ const existingMembers = await db()
+ .select({ userId: spaceMembers.userId, role: spaceMembers.role })
+ .from(spaceMembers)
+ .where(eq(spaceMembers.spaceId, id));
+ const existingRoleByUserId = new Map(
+ existingMembers.map((member) => [
+ member.userId,
+ normalizeSpaceRole(member.role) ?? "member",
+ ]),
+ );
await db().delete(spaceMembers).where(eq(spaceMembers.spaceId, id));
await db()
@@ -99,7 +105,9 @@ export async function updateSpace(formData: FormData) {
.values(
memberIds.map((userId) => {
const role: SpaceMemberRole =
- userId === space.createdById ? "Admin" : "member";
+ userId === space.createdById
+ ? "admin"
+ : (existingRoleByUserId.get(userId) ?? "member");
return {
id: SpaceMemberId.make(nanoId()),
spaceId: id,
diff --git a/apps/web/actions/organization/upload-space-icon.ts b/apps/web/actions/organization/upload-space-icon.ts
index 30a431c8e..a72d8263c 100644
--- a/apps/web/actions/organization/upload-space-icon.ts
+++ b/apps/web/actions/organization/upload-space-icon.ts
@@ -10,6 +10,7 @@ import { Option } from "effect";
import { revalidatePath } from "next/cache";
import { sanitizeFile } from "@/lib/sanitizeFile";
import { runPromise } from "@/lib/server";
+import { requireSpaceManager } from "./space-authorization";
export async function uploadSpaceIcon(
formData: FormData,
@@ -21,7 +22,6 @@ export async function uploadSpaceIcon(
throw new Error("Unauthorized");
}
- // Fetch the space and check permissions
const spaceArr = await db()
.select()
.from(spaces)
@@ -36,9 +36,7 @@ export async function uploadSpaceIcon(
throw new Error("Space not found");
}
- if (space.organizationId !== user.activeOrganizationId) {
- throw new Error("You do not have permission to update this space");
- }
+ await requireSpaceManager(user.id, spaceId);
const file = formData.get("icon") as File;
if (!file) {
@@ -51,7 +49,6 @@ export async function uploadSpaceIcon(
throw new Error("File size must be less than 1MB");
}
- // Prepare new file key
const fileExtension = file.name.split(".").pop();
const fileKey = ImageUpload.ImageKey.make(
`organizations/${
@@ -64,9 +61,7 @@ export async function uploadSpaceIcon(
);
try {
- // Remove previous icon if exists
if (space.iconUrl) {
- // Extract the S3 key (it might already be a key or could be a legacy URL)
const key = space.iconUrl.startsWith("organizations/")
? space.iconUrl
: space.iconUrl.match(/organizations\/.+/)?.[0];
@@ -74,7 +69,6 @@ export async function uploadSpaceIcon(
try {
await bucket.deleteObject(key).pipe(runPromise);
} catch (e) {
- // Log and continue
console.warn("Failed to delete old space icon from S3", e);
}
}