forked from calcom/cal.diy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchangeMemberRole.handler.ts
More file actions
82 lines (69 loc) · 2.52 KB
/
changeMemberRole.handler.ts
File metadata and controls
82 lines (69 loc) · 2.52 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
76
77
78
79
80
81
82
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { RoleManagementFactory } from "@calcom/features/pbac/services/role-management.factory";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import { TRPCError } from "@trpc/server";
import type { TChangeMemberRoleInputSchema } from "./changeMemberRole.schema";
type ChangeMemberRoleOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TChangeMemberRoleInputSchema;
};
export const changeMemberRoleHandler = async ({ ctx, input }: ChangeMemberRoleOptions) => {
// Get team info to check if it's part of an organization
const teamRepo = new TeamRepository(prisma);
const team = await teamRepo.findById({ id: input.teamId });
if (!team) {
throw new TRPCError({ code: "NOT_FOUND", message: "Team not found" });
}
// Get the organization ID (either the team's parent or the team itself if it's an org)
const organizationId = team.parentId || input.teamId;
// Create role manager for this organization/team
const roleManager = await RoleManagementFactory.getInstance().createRoleManager(organizationId);
// Check permission to change roles (includes legacy validation for LegacyRoleManager)
try {
await roleManager.checkPermissionToChangeRole(
ctx.user.id,
input.teamId,
"team",
input.memberId,
input.role
);
} catch (error) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: error instanceof Error ? error.message : "Unauthorized",
});
}
// Get the target membership for the assignRole method
const targetMembership = await prisma.membership.findUnique({
where: {
userId_teamId: { userId: input.memberId, teamId: input.teamId },
},
});
if (!targetMembership) {
throw new TRPCError({ code: "NOT_FOUND", message: "Target membership not found" });
}
// Use role manager to assign the role
try {
await roleManager.assignRole(input.memberId, input.teamId, input.role, targetMembership.id);
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: error instanceof Error ? error.message : "Failed to assign role",
});
}
// Return updated membership
const updatedMembership = await prisma.membership.findUnique({
where: {
userId_teamId: { userId: input.memberId, teamId: input.teamId },
},
include: {
team: true,
user: true,
},
});
return updatedMembership;
};
export default changeMemberRoleHandler;