-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollections.ts
More file actions
75 lines (64 loc) · 1.97 KB
/
collections.ts
File metadata and controls
75 lines (64 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { TRPCError } from "@trpc/server";
import { isOwnerEmail } from "@/lib/owners";
import { assertValidCollectionSlug, collectionPrefix } from "@/lib/paths";
import { prefixHasAnyObject } from "@/lib/s3";
import { prisma } from "@/lib/prisma";
export type CollectionAccessState =
| { kind: "owner" }
| { kind: "creator" }
| { kind: "grant" }
| { kind: "none" };
export function canRenameOrDeleteCollection(
state: CollectionAccessState,
): boolean {
// Restrict destructive collection-level operations to owner/creator.
return state.kind === "owner" || state.kind === "creator";
}
export async function loadCollectionAccessState(params: {
userId: string;
email: string | null | undefined;
slug: string;
}): Promise<CollectionAccessState> {
assertValidCollectionSlug(params.slug);
if (isOwnerEmail(params.email)) {
return { kind: "owner" };
}
const row = await prisma.collection.findUnique({
where: { slug: params.slug },
include: {
accessGrants: { where: { userId: params.userId } },
},
});
if (!row) {
return { kind: "none" };
}
if (row.createdById === params.userId) {
return { kind: "creator" };
}
if (row.accessGrants[0]) {
return { kind: "grant" };
}
return { kind: "none" };
}
/** Open /vault/[slug] — owners need a real S3 prefix; others need a DB row and creator or grant. */
export async function userCanOpenVaultCollection(params: {
userId: string;
email: string | null | undefined;
slug: string;
}): Promise<boolean> {
assertValidCollectionSlug(params.slug);
if (isOwnerEmail(params.email)) {
return prefixHasAnyObject(collectionPrefix(params.slug));
}
const state = await loadCollectionAccessState(params);
if (state.kind === "none") return false;
return true;
}
export function assertRelativePathAllowed(state: CollectionAccessState): void {
if (state.kind === "none") {
throw new TRPCError({
code: "FORBIDDEN",
message: "No access to this collection",
});
}
}