Files
chinese-family-tree-2/lib/permissions.ts
T
freedakgmail e92884ae53 0.0.1.0
2025-11-23 03:07:39 +08:00

50 lines
1000 B
TypeScript

import { prisma } from "./prisma"
import { Role } from "@prisma/client"
export async function checkPermission(
userId: string,
treeId: string,
requiredRole: Role = Role.VIEWER
) {
// 检查是否是所有者
const tree = await prisma.familyTree.findFirst({
where: {
id: treeId,
ownerId: userId
}
})
if (tree) {
return { hasPermission: true, role: Role.OWNER }
}
// 检查协作者权限
const collaborator = await prisma.treeCollaborator.findFirst({
where: {
treeId,
userId
}
})
if (!collaborator) {
return { hasPermission: false, role: null }
}
const roleHierarchy = {
[Role.OWNER]: 3,
[Role.EDITOR]: 2,
[Role.VIEWER]: 1
}
const hasPermission = roleHierarchy[collaborator.role] >= roleHierarchy[requiredRole]
return { hasPermission, role: collaborator.role }
}
export async function requireAuth(userId: string | undefined) {
if (!userId) {
throw new Error("未授权")
}
return userId
}