0.0.1.0
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user