Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: allow moving owned Caps from the share page in any member organization

Richie McIlroy4473419e6cb7
diff --git a/apps/web/__tests__/unit/move-items-dialog.test.ts b/apps/web/__tests__/unit/move-items-dialog.test.ts
index 75ce7b805..b4dea12e2 100644
--- a/apps/web/__tests__/unit/move-items-dialog.test.ts
+++ b/apps/web/__tests__/unit/move-items-dialog.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { Folder, Video } from "@cap/web-domain";
+import { Folder, Organisation, Video } from "@cap/web-domain";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
@@ -74,6 +74,7 @@ async function render(
videoIds: [videoId],
currentFolderId: null,
},
+ organizationId?: Organisation.OrganisationId,
) {
await act(async () => {
root.render(
@@ -85,6 +86,7 @@ async function render(
onOpenChange: mocks.close,
location: { type: "personal" },
rootLabel: "My Caps",
+ organizationId,
item,
}),
),
@@ -140,6 +142,20 @@ describe("moving Caps from My Caps to a team location", () => {
});
});
+ it("uses the Cap's organization when it differs from the active one", async () => {
+ const organizationId = Organisation.OrganisationId.make("cap-org");
+ await render(undefined, organizationId);
+ expect(mocks.destinations).toHaveBeenCalledWith(organizationId);
+ await chooseTeam();
+ await act(async () => button("Share & move").click());
+ expect(mocks.place).toHaveBeenCalledWith({
+ videoIds: [videoId],
+ folderId: null,
+ location: { type: "organization" },
+ organizationId,
+ });
+ });
+
it("keeps folder moves within their original location", async () => {
await render({ type: "folder", folderId, currentParentId: null });
expect(document.querySelector("select")).toBeNull();
diff --git a/apps/web/__tests__/unit/move-owned-videos.test.ts b/apps/web/__tests__/unit/move-owned-videos.test.ts
index 1aac00a52..ffc09227f 100644
--- a/apps/web/__tests__/unit/move-owned-videos.test.ts
+++ b/apps/web/__tests__/unit/move-owned-videos.test.ts
@@ -1,4 +1,4 @@
-import { Folder, Space, Video } from "@cap/web-domain";
+import { Folder, Organisation, Space, Video } from "@cap/web-domain";
import { getTableName, type SQL } from "drizzle-orm";
import { MySqlDialect, type MySqlTable } from "drizzle-orm/mysql-core";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -317,6 +317,59 @@ describe("placing owned Caps in team folders", () => {
expect(filters[1]?.params).toEqual(["org", "owner", "org", spaceId]);
});
+ it("scopes every check and write to a requested organization the owner belongs to", async () => {
+ const organizationId = Organisation.OrganisationId.make("cap-org");
+ results = [[{ id: ids[0] }], [{ id: folderId }], []];
+ await placeOwnedVideos({
+ videoIds: [ids[0]],
+ folderId,
+ location: { type: "organization" },
+ organizationId,
+ });
+ expect(mocks.organization).toHaveBeenCalledWith("owner", organizationId);
+ expect(filters[0]?.params).toEqual([ids[0], "owner", organizationId]);
+ expect(filters[1]?.params).toEqual([
+ folderId,
+ organizationId,
+ organizationId,
+ ]);
+ expect(writes[0]?.values).toEqual([
+ expect.objectContaining({ videoId: ids[0], organizationId }),
+ ]);
+ });
+
+ it("rejects a requested organization the owner no longer belongs to", async () => {
+ mocks.organization.mockRejectedValue(new Error("Forbidden"));
+ const organizationId = Organisation.OrganisationId.make("cap-org");
+ await expect(getOwnedVideoMoveDestinations(organizationId)).rejects.toThrow(
+ "Forbidden",
+ );
+ await expect(
+ placeOwnedVideos({
+ videoIds: [ids[0]],
+ folderId: null,
+ location: { type: "personal" },
+ organizationId,
+ }),
+ ).rejects.toThrow("Forbidden");
+ expect(mocks.organization).toHaveBeenCalledWith("owner", organizationId);
+ expect(mocks.select).not.toHaveBeenCalled();
+ expect(mocks.transaction).not.toHaveBeenCalled();
+ });
+
+ it("lists destinations in a requested organization", async () => {
+ const organizationId = Organisation.OrganisationId.make("cap-org");
+ results = [[], []];
+ await getOwnedVideoMoveDestinations(organizationId);
+ expect(mocks.organization).toHaveBeenCalledWith("owner", organizationId);
+ expect(filters[0]?.params).toEqual([organizationId, "owner", "owner"]);
+ expect(filters[1]?.params).toEqual([
+ organizationId,
+ "owner",
+ organizationId,
+ ]);
+ });
+
it("keeps personal moves private and checks personal folder ownership", async () => {
results = [[{ id: ids[0] }], [{ id: folderId }]];
await placeOwnedVideos({
diff --git a/apps/web/actions/folders/move-items.ts b/apps/web/actions/folders/move-items.ts
index bf940130d..80162d233 100644
--- a/apps/web/actions/folders/move-items.ts
+++ b/apps/web/actions/folders/move-items.ts
@@ -11,7 +11,7 @@ import {
spaceVideos,
videos,
} from "@cap/database/schema";
-import type { Folder, Video } from "@cap/web-domain";
+import type { Folder, Organisation, Video } from "@cap/web-domain";
import { and, asc, eq, inArray, isNull, or } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import {
@@ -73,22 +73,21 @@ async function requireMoveAccess(
function getFolderScope(
user: NonNullable<Awaited<ReturnType<typeof getCurrentUser>>>,
location: MoveLocation,
+ organizationId: Organisation.OrganisationId = user.activeOrganizationId,
) {
if (location.type === "personal") {
return and(
- eq(folders.organizationId, user.activeOrganizationId),
+ eq(folders.organizationId, organizationId),
eq(folders.createdById, user.id),
isNull(folders.spaceId),
);
}
return and(
- eq(folders.organizationId, user.activeOrganizationId),
+ eq(folders.organizationId, organizationId),
eq(
folders.spaceId,
- location.type === "organization"
- ? user.activeOrganizationId
- : location.spaceId,
+ location.type === "organization" ? organizationId : location.spaceId,
),
);
}
@@ -127,15 +126,13 @@ export async function getMoveFolderDestinations(
.orderBy(asc(folders.name));
}
-export async function getOwnedVideoMoveDestinations(): Promise<
- MoveDestinationGroup[]
-> {
+export async function getOwnedVideoMoveDestinations(
+ requestedOrganizationId?: Organisation.OrganisationId,
+): Promise<MoveDestinationGroup[]> {
const user = await getCurrentUser();
- if (!user?.activeOrganizationId) throw new Error("Unauthorized");
- const access = await requireOrganizationAccess(
- user.id,
- user.activeOrganizationId,
- );
+ const organizationId = requestedOrganizationId ?? user?.activeOrganizationId;
+ if (!user || !organizationId) throw new Error("Unauthorized");
+ const access = await requireOrganizationAccess(user.id, organizationId);
const availableSpaces = await db()
.select({ id: spaces.id, name: spaces.name })
.from(spaces)
@@ -148,7 +145,7 @@ export async function getOwnedVideoMoveDestinations(): Promise<
)
.where(
and(
- eq(spaces.organizationId, user.activeOrganizationId),
+ eq(spaces.organizationId, organizationId),
canManageOrganizationSettings(access.role)
? undefined
: or(
@@ -168,11 +165,11 @@ export async function getOwnedVideoMoveDestinations(): Promise<
.from(folders)
.where(
and(
- eq(folders.organizationId, user.activeOrganizationId),
+ eq(folders.organizationId, organizationId),
or(
and(eq(folders.createdById, user.id), isNull(folders.spaceId)),
inArray(folders.spaceId, [
- user.activeOrganizationId,
+ organizationId,
...availableSpaces.map((space) => space.id),
]),
),
@@ -189,7 +186,7 @@ export async function getOwnedVideoMoveDestinations(): Promise<
location: { type: "organization" },
name: "All team members",
folders: organizationFolders.filter(
- (folder) => folder.spaceId === user.activeOrganizationId,
+ (folder) => folder.spaceId === organizationId,
),
},
...availableSpaces.map(
@@ -208,24 +205,27 @@ export async function placeOwnedVideos({
videoIds,
folderId,
location,
+ organizationId: requestedOrganizationId,
}: {
videoIds: Video.VideoId[];
folderId: Folder.FolderId | null;
location: MoveLocation;
+ organizationId?: Organisation.OrganisationId;
}) {
const user = await getCurrentUser();
- if (!user?.activeOrganizationId) throw new Error("Unauthorized");
+ const organizationId = requestedOrganizationId ?? user?.activeOrganizationId;
+ if (!user || !organizationId) throw new Error("Unauthorized");
requireValidLocation(location);
const ids = normalizeVideoIds(videoIds).sort();
const organizationAccess = await requireOrganizationAccess(
user.id,
- user.activeOrganizationId,
+ organizationId,
);
if (location.type === "space") {
const access = await getSpaceAccess(user.id, location.spaceId);
if (
!access ||
- access.organizationId !== user.activeOrganizationId ||
+ access.organizationId !== organizationId ||
!access.organizationRole ||
(!access.canManage && !access.spaceRole)
) {
@@ -250,7 +250,7 @@ export async function placeOwnedVideos({
.where(
and(
eq(spaces.id, location.spaceId),
- eq(spaces.organizationId, user.activeOrganizationId),
+ eq(spaces.organizationId, organizationId),
),
)
.limit(1)
@@ -274,7 +274,7 @@ export async function placeOwnedVideos({
and(
inArray(videos.id, ids),
eq(videos.ownerId, user.id),
- eq(videos.orgId, user.activeOrganizationId),
+ eq(videos.orgId, organizationId),
),
)
.orderBy(asc(videos.id))
@@ -285,7 +285,12 @@ export async function placeOwnedVideos({
const [folder] = await tx
.select({ id: folders.id })
.from(folders)
- .where(and(eq(folders.id, folderId), getFolderScope(user, location)))
+ .where(
+ and(
+ eq(folders.id, folderId),
+ getFolderScope(user, location, organizationId),
+ ),
+ )
.limit(1)
.for("update");
if (!folder) throw new Error("Destination folder not found");
@@ -299,7 +304,7 @@ export async function placeOwnedVideos({
.where(
and(
inArray(sharedVideos.videoId, ids),
- eq(sharedVideos.organizationId, user.activeOrganizationId),
+ eq(sharedVideos.organizationId, organizationId),
),
);
const shared = new Set(existing.map((row) => row.videoId));
@@ -310,7 +315,7 @@ export async function placeOwnedVideos({
id: nanoId(),
videoId,
folderId,
- organizationId: user.activeOrganizationId,
+ organizationId,
sharedByUserId: user.id,
})),
);
@@ -320,7 +325,7 @@ export async function placeOwnedVideos({
.where(
and(
inArray(sharedVideos.videoId, ids),
- eq(sharedVideos.organizationId, user.activeOrganizationId),
+ eq(sharedVideos.organizationId, organizationId),
),
);
} else {
diff --git a/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx
index 666f37da4..a66ec3c9a 100644
--- a/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx
@@ -99,7 +99,7 @@ export function MoveItemsDialog({
],
queryFn: async (): Promise<MoveDestinationGroup[]> =>
ownedVideos
- ? getOwnedVideoMoveDestinations()
+ ? getOwnedVideoMoveDestinations(organizationId)
: [
{
location,
@@ -137,13 +137,15 @@ export function MoveItemsDialog({
const moveMutation = useMutation({
mutationFn: async () => {
if (item.type === "videos") {
- const move = ownedVideos ? placeOwnedVideos : moveVideos;
if (!selectedGroup) throw new Error("Select a destination");
- await move({
+ const placement = {
videoIds: item.videoIds,
folderId: selectedFolderId,
location: selectedGroup.location,
- });
+ };
+ await (ownedVideos
+ ? placeOwnedVideos({ ...placement, organizationId })
+ : moveVideos(placement));
return;
}
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 1a7148e43..d9e6ab944 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -729,8 +729,8 @@ async function AuthorizedContent({
const viewsPromise = getVideoAnalytics(videoId).then((v) => v.count);
- const canManageSharePageBrandingPromise = (async () => {
- if (!userId) return false;
+ const videoOrganizationRolePromise = (async () => {
+ if (!userId) return null;
const [organizationAccess] = await db()
.select({
@@ -753,15 +753,13 @@ async function AuthorizedContent({
)
.limit(1);
- if (!organizationAccess) return false;
+ if (!organizationAccess) return null;
- return canManageOrganizationSettings(
- getEffectiveOrganizationRole({
- userId,
- ownerId: organizationAccess.ownerId,
- memberRole: organizationAccess.memberRole,
- }),
- );
+ return getEffectiveOrganizationRole({
+ userId,
+ ownerId: organizationAccess.ownerId,
+ memberRole: organizationAccess.memberRole,
+ });
})();
const isVideoDownloadReady =
@@ -816,7 +814,7 @@ async function AuthorizedContent({
membersList,
userOrganizations,
{ customDomain, domainVerified },
- canManageSharePageBranding,
+ videoOrganizationRole,
canDownloadVideo,
videoHasEdits,
ownerIsOverShareLimit,
@@ -831,7 +829,7 @@ async function AuthorizedContent({
membersListPromise,
userOrganizationsPromise,
customDomainPromise,
- canManageSharePageBrandingPromise,
+ videoOrganizationRolePromise,
canDownloadVideoPromise,
videoHasEditsPromise,
overShareLimitPromise,
@@ -945,8 +943,7 @@ async function AuthorizedContent({
header={
<ShareHeader
canMoveToFolder={
- user?.id === video.owner.id &&
- user?.activeOrganizationId === video.orgId
+ user?.id === video.owner.id && videoOrganizationRole !== null
}
data={{
...videoWithOrganizationInfo,
@@ -965,7 +962,9 @@ async function AuthorizedContent({
userOrganizations={userOrganizations}
spacesData={spacesData}
branding={getSharePageBranding(videoWithOrganizationInfo)}
- canManageSharePageBranding={canManageSharePageBranding}
+ canManageSharePageBranding={canManageOrganizationSettings(
+ videoOrganizationRole,
+ )}
canDownload={canDownloadVideo}
hasEdits={videoHasEdits}
// Caught separately from the copy the sidebar consumes: the