Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

CSV admin fix

Richie McIlroy743dee629bfa
diff --git a/apps/web/__tests__/unit/loom-import.test.ts b/apps/web/__tests__/unit/loom-import.test.ts
index 73d2e7c6c..29d74232f 100644
--- a/apps/web/__tests__/unit/loom-import.test.ts
+++ b/apps/web/__tests__/unit/loom-import.test.ts
@@ -8,6 +8,7 @@ const revalidatePathMock = vi.fn();
const storageGetWritableAccessForUserMock = vi.hoisted(() => vi.fn());
const checkRateLimitMock = vi.hoisted(() => vi.fn());
const headersMock = vi.hoisted(() => vi.fn());
+const getOrganizationAccessMock = vi.hoisted(() => vi.fn());
const mockDb = {
select: vi.fn(() => mockDb),
@@ -41,8 +42,10 @@ vi.mock("@cap/database/schema", () => ({
sourceId: "sourceId",
},
organizationMembers: {
+ id: "memberId",
userId: "memberUserId",
organizationId: "memberOrganizationId",
+ role: "memberRole",
},
organizations: {
id: "organizationId",
@@ -147,6 +150,7 @@ vi.mock("@/lib/server", async () => {
});
vi.mock("@/actions/organization/authorization", () => ({
+ getOrganizationAccess: getOrganizationAccessMock,
requireOrganizationAccess: vi.fn(),
}));
@@ -184,6 +188,12 @@ describe("importFromLoom", () => {
whereMock.mockResolvedValue([]);
startMock.mockResolvedValue(undefined);
checkRateLimitMock.mockResolvedValue({ rateLimited: false });
+ getOrganizationAccessMock.mockResolvedValue({
+ id: "org-1",
+ ownerId: "user-123",
+ memberId: null,
+ role: "owner",
+ });
headersMock.mockResolvedValue(
new Headers({
host: "cap.test",
@@ -312,8 +322,13 @@ describe("importFromLoom", () => {
expect(revalidatePathMock).toHaveBeenCalledWith("/dashboard/caps");
});
- it("rejects a CSV import when the current user is not the organization owner", async () => {
- whereMock.mockReturnValueOnce(withLimit([{ ownerId: "owner-456" }]));
+ it("rejects a CSV import when the current user is not an organization admin or owner", async () => {
+ getOrganizationAccessMock.mockResolvedValueOnce({
+ id: "org-1",
+ ownerId: "owner-456",
+ memberId: "member-row",
+ role: "member",
+ });
const fetchMock = vi.mocked(fetch);
const { importFromLoomCsv } = await import("@/actions/loom");
@@ -335,16 +350,15 @@ describe("importFromLoom", () => {
failedCount: 0,
results: [],
error:
- "Only the organization owner can import Loom videos from a CSV. Ask the owner to do it.",
+ "Only organization admins and owners can import Loom videos from a CSV.",
});
+ expect(getOrganizationAccessMock).toHaveBeenCalledWith("user-123", "org-1");
expect(fetchMock).not.toHaveBeenCalled();
expect(valuesMock).not.toHaveBeenCalled();
});
it("rejects CSV rows for emails outside the organization", async () => {
- whereMock
- .mockReturnValueOnce(withLimit([{ ownerId: "user-123" }]))
- .mockReturnValueOnce(withLimit([]));
+ whereMock.mockReturnValueOnce(withLimit([]));
const fetchMock = vi.mocked(fetch);
const { importFromLoomCsv } = await import("@/actions/loom");
@@ -380,11 +394,9 @@ describe("importFromLoom", () => {
});
it("rejects CSV imports when the current user is rate limited", async () => {
- whereMock
- .mockReturnValueOnce(withLimit([{ ownerId: "user-123" }]))
- .mockReturnValueOnce(
- withLimit([{ userId: "member-123", email: "[email protected]" }]),
- );
+ whereMock.mockReturnValueOnce(
+ withLimit([{ userId: "member-123", email: "[email protected]" }]),
+ );
checkRateLimitMock.mockResolvedValueOnce({ rateLimited: true });
const fetchMock = vi.mocked(fetch);
@@ -428,8 +440,6 @@ describe("importFromLoom", () => {
});
it("limits CSV imports to 500 rows", async () => {
- whereMock.mockReturnValueOnce(withLimit([{ ownerId: "user-123" }]));
-
const fetchMock = vi.mocked(fetch);
const { importFromLoomCsv } = await import("@/actions/loom");
@@ -455,9 +465,14 @@ describe("importFromLoom", () => {
expect(valuesMock).not.toHaveBeenCalled();
});
- it("starts CSV Loom imports for matched organization members", async () => {
+ it("starts CSV Loom imports for matched organization members when the current user is an organization admin", async () => {
+ getOrganizationAccessMock.mockResolvedValueOnce({
+ id: "org-1",
+ ownerId: "owner-456",
+ memberId: "member-row",
+ role: "admin",
+ });
whereMock
- .mockReturnValueOnce(withLimit([{ ownerId: "user-123" }]))
.mockReturnValueOnce(
withLimit([{ userId: "member-123", email: "[email protected]" }]),
)
@@ -547,7 +562,6 @@ describe("importFromLoom", () => {
it("creates missing spaces and adds CSV Loom imports to them", async () => {
whereMock
- .mockReturnValueOnce(withLimit([{ ownerId: "user-123" }]))
.mockReturnValueOnce(
withLimit([{ userId: "member-123", email: "[email protected]" }]),
)
diff --git a/apps/web/actions/loom.ts b/apps/web/actions/loom.ts
index 1627bd5dd..77cd68a1f 100644
--- a/apps/web/actions/loom.ts
+++ b/apps/web/actions/loom.ts
@@ -7,7 +7,6 @@ import { nanoId } from "@cap/database/helpers";
import {
importedVideos,
organizationMembers,
- organizations,
spaceMembers,
spaces,
spaceVideos,
@@ -26,12 +25,16 @@ import {
Video,
} from "@cap/web-domain";
import { checkRateLimit } from "@vercel/firewall";
-import { and, eq, isNull } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { Option } from "effect";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { start } from "workflow/api";
-import { requireOrganizationAccess } from "@/actions/organization/authorization";
+import {
+ getOrganizationAccess,
+ requireOrganizationAccess,
+} from "@/actions/organization/authorization";
+import { canManageOrganizationSettings } from "@/lib/permissions/roles";
import { runPromise } from "@/lib/server";
import { importLoomVideoWorkflow } from "@/workflows/import-loom-video";
@@ -82,6 +85,8 @@ const LOOM_IMPORT_RATE_LIMIT_ID = "rl_loom_import_per_user";
const LOOM_IMPORT_RATE_LIMIT_ERROR =
"Too many Loom imports started. Please wait a few minutes, then try again.";
const LOOM_CSV_LIMIT_ERROR = `CSV imports are limited to ${MAX_LOOM_CSV_ROWS} rows at a time. Contact support to raise this limit.`;
+const LOOM_CSV_PERMISSION_ERROR =
+ "Only organization admins and owners can import Loom videos from a CSV.";
async function createLoomImportRateLimitCheck(userId: User.UserId) {
if (NODE_ENV !== "production") return async () => false;
@@ -497,21 +502,6 @@ async function getOrganizationMemberByEmail(
return member ?? null;
}
-async function isOrganizationOwner(
- userId: User.UserId,
- orgId: Organisation.OrganisationId,
-) {
- const [organization] = await db()
- .select({
- ownerId: organizations.ownerId,
- })
- .from(organizations)
- .where(and(eq(organizations.id, orgId), isNull(organizations.tombstoneAt)))
- .limit(1);
-
- return organization?.ownerId === userId;
-}
-
type ImportSpaceCacheValue = {
id: Space.SpaceIdOrOrganisationId;
name: string;
@@ -635,14 +625,14 @@ export async function importFromLoomCsv({
};
}
- if (!(await isOrganizationOwner(user.id, orgId))) {
+ const access = await getOrganizationAccess(user.id, orgId);
+ if (!canManageOrganizationSettings(access?.role)) {
return {
success: false,
importedCount: 0,
failedCount: 0,
results: [],
- error:
- "Only the organization owner can import Loom videos from a CSV. Ask the owner to do it.",
+ error: LOOM_CSV_PERMISSION_ERROR,
};
}
diff --git a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx
index c3d6b9d18..a7ed0ffbd 100644
--- a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx
+++ b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx
@@ -46,6 +46,10 @@ import {
} from "@/actions/loom";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
import { UpgradeModal } from "@/components/UpgradeModal";
+import {
+ canManageOrganizationSettings,
+ getEffectiveOrganizationRole,
+} from "@/lib/permissions/roles";
type Mode = "single" | "csv";
@@ -78,6 +82,8 @@ const LOOM_CSV_BATCH_SIZE = 10;
const LOOM_CSV_BATCH_DELAY_MS = 1500;
const LOOM_CSV_LIMIT_MESSAGE =
"CSV imports are limited to 500 videos at a time. Contact support to raise this limit.";
+const LOOM_CSV_PERMISSION_MESSAGE =
+ "Only organization admins and owners can import Loom videos from a CSV.";
function delay(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
@@ -230,10 +236,18 @@ export const ImportLoomPage = () => {
const { user, activeOrganization } = useDashboardContext();
const router = useRouter();
- const isOrganizationOwner =
- !!user && user.id === activeOrganization?.organization.ownerId;
+ const currentMember = activeOrganization?.members.find(
+ (member) => member.userId === user?.id,
+ );
+ const currentRole = getEffectiveOrganizationRole({
+ userId: user?.id,
+ ownerId: activeOrganization?.organization.ownerId,
+ memberRole: currentMember?.role,
+ });
+ const canUseCsvImport = canManageOrganizationSettings(currentRole);
const [mode, setMode] = useState<Mode>("single");
+ const activeMode = canUseCsvImport ? mode : "single";
const [upgradeModalOpen, setUpgradeModalOpen] = useState(!user?.isPro);
const [loomUrl, setLoomUrl] = useState("");
@@ -296,6 +310,7 @@ export const ImportLoomPage = () => {
const previewRows = mappedRows.slice(0, 5);
const csvLimitExceeded = readyRows.length > MAX_LOOM_CSV_IMPORT_ROWS;
const canImport =
+ canUseCsvImport &&
!!activeOrganization &&
!selectedColumnsConflict &&
readyRows.length > 0 &&
@@ -367,6 +382,11 @@ export const ImportLoomPage = () => {
const loadCsvFile = async (file: File) => {
if (!user) return;
+ if (!canUseCsvImport) {
+ toast.error(LOOM_CSV_PERMISSION_MESSAGE);
+ return;
+ }
+
if (!user.isPro) {
setUpgradeModalOpen(true);
return;
@@ -513,7 +533,7 @@ export const ImportLoomPage = () => {
Import from Loom
</h1>
<p className="mt-1 max-w-xl text-sm text-gray-10">
- {isOrganizationOwner
+ {canUseCsvImport
? "Bring a single Loom video into Cap, or bulk import recordings for organization members from a CSV."
: "Paste a Loom share link to bring it into Cap."}
</p>
@@ -522,20 +542,20 @@ export const ImportLoomPage = () => {
</div>
<div className="flex flex-col gap-6 w-full max-w-4xl">
- {isOrganizationOwner && (
+ {canUseCsvImport && (
<div
role="tablist"
aria-label="Loom import mode"
className="flex gap-1 p-1 rounded-full border w-fit border-gray-3 bg-gray-2"
>
<ModeTab
- active={mode === "single"}
+ active={activeMode === "single"}
icon={faLink}
label="Single Video"
onClick={() => setMode("single")}
/>
<ModeTab
- active={mode === "csv"}
+ active={activeMode === "csv"}
icon={faFileCsv}
label="Bulk Import"
onClick={() => setMode("csv")}
@@ -543,7 +563,7 @@ export const ImportLoomPage = () => {
</div>
)}
- {mode === "single" ? (
+ {activeMode === "single" ? (
<div className="flex overflow-hidden flex-col rounded-xl border bg-gray-1 border-gray-3">
<div className="flex flex-col gap-1 px-6 py-5 border-b border-gray-3">
<p className="text-sm font-medium text-gray-12">Loom video URL</p>