返回 presentation-ai
authorization.ts
根目录 / src / server / share / authorization.ts
1 import { auth } from "@/server/auth";
2 import { db } from "@/server/db";
3
4 interface SessionIdentity {
5 userId: string | null;
6 userEmail: string | null;
7 }
8
9 export async function getSessionIdentity(): Promise<SessionIdentity> {
10 const session = await auth();
11 return {
12 userId: session?.user.id ?? null,
13 userEmail: session?.user.email ?? null,
14 };
15 }
16
17 export async function canReadDocument(
18 documentId: string,
19 identity: SessionIdentity,
20 ) {
21 const document = await db.baseDocument.findUnique({
22 where: { id: documentId },
23 select: { userId: true, isPublic: true },
24 });
25
26 if (!document) {
27 return false;
28 }
29
30 return document.isPublic || document.userId === identity.userId;
31 }
32
33 export async function canEditDocument(
34 documentId: string,
35 identity: SessionIdentity,
36 ) {
37 const document = await db.baseDocument.findUnique({
38 where: { id: documentId },
39 select: { userId: true },
40 });
41
42 if (!document) {
43 return false;
44 }
45
46 return document.userId === identity.userId;
47 }
48
49 export async function getDocumentAccessForUser(
50 documentId: string,
51 userId: string | null,
52 userEmail: string | null,
53 ) {
54 const identity = { userId, userEmail };
55 const [canRead, canEdit] = await Promise.all([
56 canReadDocument(documentId, identity),
57 canEditDocument(documentId, identity),
58 ]);
59
60 return { canRead, canEdit };
61 }
62
62 lines TYPESCRIPT