feat: SCIM Group Provisioning To Teams Within An Org (#13850)
Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: Keith Williams <[email protected]> Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Udit Takkar <[email protected]> Co-authored-by: Kiran K <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: sean-brydon <[email protected]> Co-authored-by: zomars <[email protected]> Co-authored-by: Carina Wollendorfer <[email protected]>
This commit is contained in:
33 files changed
+1014
-195
No files matched your search
@@ -1,14 +1,10 @@
|
||||
import type { DirectorySyncEvent, DirectorySyncRequest, User } from "@boxyhq/saml-jackson";
|
||||
import type { DirectorySyncEvent, DirectorySyncRequest } from "@boxyhq/saml-jackson";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import createUserAndInviteToOrg from "@calcom/features/ee/dsync/lib/createUserAndInviteToOrg";
|
||||
import inviteExistingUserToOrg from "@calcom/features/ee/dsync/lib/inviteExistingUserToOrg";
|
||||
import removeUserFromOrg from "@calcom/features/ee/dsync/lib/removeUserFromOrg";
|
||||
import handleGroupEvents from "@calcom/features/ee/dsync/lib/handleGroupEvents";
|
||||
import handleUserEvents from "@calcom/features/ee/dsync/lib/handleUserEvents";
|
||||
import jackson from "@calcom/features/ee/sso/lib/jackson";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { UserWithMembership } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
import { getTeamOrThrow } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
|
||||
// This is the handler for the SCIM API requests
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
@@ -47,14 +43,13 @@ export const extractAuthToken = (req: NextApiRequest): string | null => {
|
||||
|
||||
// Handle the SCIM events
|
||||
const handleEvents = async (event: DirectorySyncEvent) => {
|
||||
console.log("Received event", event);
|
||||
const dSyncData = await prisma.dSyncData.findFirst({
|
||||
where: {
|
||||
directoryId: event.directory_id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
orgId: true,
|
||||
organizationId: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -62,69 +57,17 @@ const handleEvents = async (event: DirectorySyncEvent) => {
|
||||
throw new Error("Directory sync data not found");
|
||||
}
|
||||
|
||||
const { orgId } = dSyncData;
|
||||
const { organizationId } = dSyncData;
|
||||
|
||||
if (!orgId) {
|
||||
if (!organizationId) {
|
||||
throw new Error(`Org ID not found for dsync ${dSyncData.id}`);
|
||||
}
|
||||
|
||||
if (event.event.includes("group")) {
|
||||
handleGroupEvents(event, organizationId);
|
||||
}
|
||||
|
||||
if (event.event === "user.created" || event.event === "user.updated") {
|
||||
const eventData = event.data as User;
|
||||
const userEmail = eventData.email;
|
||||
const translation = await getTranslation("en", "common");
|
||||
// Check if user exists in DB
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
email: userEmail,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
organizationId: true,
|
||||
completedOnboarding: true,
|
||||
identityProvider: true,
|
||||
profiles: true,
|
||||
password: {
|
||||
select: {
|
||||
hash: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// User is already a part of that org
|
||||
if (user?.organizationId && eventData.active) {
|
||||
return;
|
||||
}
|
||||
|
||||
const org = await getTeamOrThrow(orgId);
|
||||
|
||||
if (!org) {
|
||||
throw new Error("Org not found");
|
||||
}
|
||||
|
||||
if (user) {
|
||||
// If data.active is true then provision the user into the org
|
||||
eventData.active
|
||||
? await inviteExistingUserToOrg({
|
||||
user: user as UserWithMembership,
|
||||
org,
|
||||
translation,
|
||||
})
|
||||
: // If data.active is false then remove the user from the org
|
||||
await removeUserFromOrg({
|
||||
userId: user.id,
|
||||
orgId,
|
||||
});
|
||||
|
||||
// If user is not in DB, create user and add to the org
|
||||
} else {
|
||||
await createUserAndInviteToOrg({
|
||||
userEmail,
|
||||
org,
|
||||
translation,
|
||||
});
|
||||
}
|
||||
await handleUserEvents(event, organizationId);
|
||||
}
|
||||
};
|
||||
@@ -2287,6 +2287,9 @@
|
||||
"field_identifiers_as_variables": "Use field identifiers as variables for your custom event redirect",
|
||||
"field_identifiers_as_variables_with_example": "Use field identifiers as variables for your custom event redirect (e.g. {{variable}})",
|
||||
"account_already_linked": "Account is already linked",
|
||||
"team_will_be_under_org": "New teams will be under your organization",
|
||||
"add_group_name": "Add group name",
|
||||
"group_name": "Group Name",
|
||||
"routers": "Routers",
|
||||
"primary": "Primary",
|
||||
"make_primary": "Make primary",
|
||||
|
||||
@@ -18,13 +18,14 @@ import { AlertTriangle, Trash2 } from "@calcom/ui/components/icon";
|
||||
|
||||
import CreateDirectory from "./CreateDirectory";
|
||||
import DirectoryInfo from "./DirectoryInfo";
|
||||
import GroupTeamMappingTable from "./GroupTeamMappingTable";
|
||||
|
||||
const ConfigureDirectorySync = ({ orgId }: { orgId: number | null }) => {
|
||||
const ConfigureDirectorySync = ({ organizationId }: { organizationId: number | null }) => {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
const [deleteDirectoryOpen, setDeleteDirectoryOpen] = useState(false);
|
||||
|
||||
const { data, isLoading, isError, error } = trpc.viewer.dsync.get.useQuery({ orgId });
|
||||
const { data, isLoading, isError, error } = trpc.viewer.dsync.get.useQuery({ organizationId });
|
||||
|
||||
const deleteMutation = trpc.viewer.dsync.delete.useMutation({
|
||||
async onSuccess() {
|
||||
@@ -47,7 +48,7 @@ const ConfigureDirectorySync = ({ orgId }: { orgId: number | null }) => {
|
||||
return;
|
||||
}
|
||||
|
||||
deleteMutation.mutate({ orgId, directoryId: directory.id });
|
||||
deleteMutation.mutate({ organizationId, directoryId: directory.id });
|
||||
};
|
||||
|
||||
if (error || isError) {
|
||||
@@ -65,10 +66,14 @@ const ConfigureDirectorySync = ({ orgId }: { orgId: number | null }) => {
|
||||
return (
|
||||
<div>
|
||||
{!directory ? (
|
||||
<CreateDirectory orgId={orgId} />
|
||||
<CreateDirectory orgId={organizationId} />
|
||||
) : (
|
||||
<>
|
||||
<DirectoryInfo directory={directory} />
|
||||
<div className="mt-4">
|
||||
<GroupTeamMappingTable />
|
||||
</div>
|
||||
|
||||
<hr className="border-subtle my-6" />
|
||||
<Label>{t("danger_zone")}</Label>
|
||||
{/* Delete directory sync connection */}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { CreateANewTeamForm } from "@calcom/features/ee/teams/components";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Dialog, DialogContent } from "@calcom/ui";
|
||||
|
||||
interface CreateTeamDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const CreateTeamDialog = (props: CreateTeamDialogProps) => {
|
||||
const { open, onOpenChange } = props;
|
||||
const { t } = useLocale();
|
||||
|
||||
const utils = trpc.useContext();
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent type="creation" title={t("create_new_team")} description={t("team_will_be_under_org")}>
|
||||
<CreateANewTeamForm
|
||||
inDialog
|
||||
submitLabel="Create"
|
||||
onCancel={() => onOpenChange(false)}
|
||||
onSuccess={async () => {
|
||||
await utils.viewer.dsync.teamGroupMapping.get.invalidate();
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
onOpenChange(false);
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateTeamDialog;
|
||||
@@ -0,0 +1,117 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Badge, TextField, showToast } from "@calcom/ui";
|
||||
import { X, Plus } from "@calcom/ui/components/icon";
|
||||
|
||||
interface GroupNameCellProps {
|
||||
groupNames: string[];
|
||||
teamId: number;
|
||||
directoryId: string;
|
||||
}
|
||||
|
||||
const GroupNameCell = ({ groupNames, teamId, directoryId }: GroupNameCellProps) => {
|
||||
const [showTextInput, setShowTextInput] = useState(false);
|
||||
const [newGroupName, setNewGroupName] = useState("");
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const createMutation = trpc.viewer.dsync.teamGroupMapping.create.useMutation({
|
||||
onSuccess: (data) => {
|
||||
utils.viewer.dsync.teamGroupMapping.get.setData(undefined, (prev) => {
|
||||
if (prev) {
|
||||
const teamIndex = prev.teamGroupMapping.findIndex((team) => team.id === teamId);
|
||||
prev.teamGroupMapping[teamIndex].groupNames.push(data.newGroupName);
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
setShowTextInput(false);
|
||||
setNewGroupName("");
|
||||
showToast(`Group added`, "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(`Error adding group name${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const deleteMutation = trpc.viewer.dsync.teamGroupMapping.delete.useMutation({
|
||||
onSuccess: (data) => {
|
||||
utils.viewer.dsync.teamGroupMapping.get.setData(undefined, (prev) => {
|
||||
if (prev) {
|
||||
const teamIndex = prev.teamGroupMapping.findIndex((team) => team.id === teamId);
|
||||
const indexToRemove = prev.teamGroupMapping[teamIndex].groupNames.indexOf(data.deletedGroupName);
|
||||
prev.teamGroupMapping[teamIndex].groupNames.splice(indexToRemove, 1);
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
showToast(`Group removed`, "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(`Error removing group name${error.message}`, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const addGroupName = (groupName: string) => {
|
||||
if (groupNames.some((name: string) => name === groupName)) {
|
||||
showToast(`Group name already added`, "error");
|
||||
return;
|
||||
}
|
||||
|
||||
createMutation.mutate({ teamId: teamId, name: groupName, directoryId: directoryId });
|
||||
};
|
||||
|
||||
const removeGroupName = (groupName: string) => {
|
||||
deleteMutation.mutate({
|
||||
teamId: teamId,
|
||||
groupName: groupName,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-4">
|
||||
{groupNames.map((name) => (
|
||||
<Badge variant="gray" size="lg" key={name} className="h-8 py-4">
|
||||
<div className="flex items-center space-x-2 ">
|
||||
<p>{name}</p>
|
||||
<div className="hover:bg-emphasis rounded p-1">
|
||||
<X className="h-4 w-4 stroke-[3px]" onClick={() => removeGroupName(name)} />
|
||||
</div>
|
||||
</div>
|
||||
</Badge>
|
||||
))}
|
||||
<Badge variant="gray" size="lg" className={classNames(!showTextInput && "hover:bg-emphasis")}>
|
||||
<div
|
||||
className="flex items-center space-x-1"
|
||||
onClick={() => {
|
||||
if (!showTextInput) setShowTextInput(true);
|
||||
}}>
|
||||
{showTextInput ? (
|
||||
<TextField
|
||||
autoFocus
|
||||
className="mb-0 h-6"
|
||||
onBlur={() => {
|
||||
if (!newGroupName) setShowTextInput(false);
|
||||
}}
|
||||
onChange={(e) => setNewGroupName(e.target.value)}
|
||||
value={newGroupName}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
addGroupName(newGroupName);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p>{t("add_group_name")}</p>
|
||||
)}
|
||||
<div className={classNames("rounded p-1", showTextInput && "hover:bg-emphasis ml-2")}>
|
||||
<Plus className="h-4 w-4 stroke-[3px]" onClick={() => addGroupName(newGroupName)} />
|
||||
</div>
|
||||
</div>
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default GroupNameCell;
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { DataTable, Button } from "@calcom/ui";
|
||||
|
||||
import CreateTeamDialog from "./CreateTeamDialog";
|
||||
import GroupNameCell from "./GroupNameCell";
|
||||
|
||||
interface TeamGroupMapping {
|
||||
name: string;
|
||||
id: number;
|
||||
groupNames: string[];
|
||||
directoryId: string;
|
||||
}
|
||||
|
||||
const GroupTeamMappingTable = () => {
|
||||
const { t } = useLocale();
|
||||
const [createTeamDialogOpen, setCreateTeamDialogOpen] = useState(false);
|
||||
|
||||
const { data } = trpc.viewer.dsync.teamGroupMapping.get.useQuery();
|
||||
|
||||
const tableContainerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const columns: ColumnDef<TeamGroupMapping>[] = [
|
||||
{
|
||||
id: "name",
|
||||
header: t("team"),
|
||||
cell: ({ row }) => {
|
||||
const { name } = row.original;
|
||||
|
||||
return <p>{name}</p>;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "group",
|
||||
header: t("group_name"),
|
||||
cell: ({ row }) => {
|
||||
const { id, groupNames, directoryId } = row.original;
|
||||
|
||||
return <GroupNameCell groupNames={groupNames} teamId={id} directoryId={directoryId} />;
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<DataTable
|
||||
data={data ? data.teamGroupMapping : []}
|
||||
tableContainerRef={tableContainerRef}
|
||||
columns={columns}
|
||||
tableCTA={<Button onClick={() => setCreateTeamDialogOpen(true)}>Create team</Button>}
|
||||
/>
|
||||
<CreateTeamDialog open={createTeamDialogOpen} onOpenChange={setCreateTeamDialogOpen} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default GroupTeamMappingTable;
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { DirectorySyncEvent, Group } from "@boxyhq/saml-jackson";
|
||||
|
||||
import jackson from "@calcom/features/ee/sso/lib/jackson";
|
||||
import { createAProfileForAnExistingUser } from "@calcom/lib/createAProfileForAnExistingUser";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
import {
|
||||
getTeamOrThrow,
|
||||
sendSignupToOrganizationEmail,
|
||||
sendExistingUserTeamInviteEmails,
|
||||
} from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
|
||||
import createUsersAndConnectToOrg from "./users/createUsersAndConnectToOrg";
|
||||
|
||||
const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: number) => {
|
||||
const { dsyncController } = await jackson();
|
||||
// Find the group name associated with the event
|
||||
const eventData = event.data as Group;
|
||||
|
||||
// If the group doesn't have any members assigned then return early
|
||||
if (!eventData.raw.members.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const groupNames = await prisma.dSyncTeamGroupMapping.findMany({
|
||||
where: {
|
||||
directoryId: event.directory_id,
|
||||
groupName: eventData.name,
|
||||
organizationId,
|
||||
},
|
||||
select: {
|
||||
teamId: true,
|
||||
team: {
|
||||
include: {
|
||||
parent: {
|
||||
include: {
|
||||
organizationSettings: true,
|
||||
},
|
||||
},
|
||||
organizationSettings: true,
|
||||
},
|
||||
},
|
||||
groupName: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!groupNames.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const org = await getTeamOrThrow(organizationId);
|
||||
|
||||
// Check if the group member display property is an email
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
const isEmail = emailRegex.test(eventData.raw.members[0].display);
|
||||
|
||||
let userEmails: string[] = [];
|
||||
|
||||
// TODO: Handle the case where display property is not an email
|
||||
|
||||
if (isEmail) {
|
||||
userEmails = eventData.raw.members.map((member: { display: string }) => member.display);
|
||||
}
|
||||
|
||||
// Find existing users
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
email: {
|
||||
in: userEmails,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
organizationId: true,
|
||||
completedOnboarding: true,
|
||||
identityProvider: true,
|
||||
profiles: true,
|
||||
locale: true,
|
||||
teams: true,
|
||||
password: {
|
||||
select: {
|
||||
hash: true,
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const translation = await getTranslation("en", "common");
|
||||
|
||||
const newUserEmails = userEmails.filter((email) => !users.find((user) => user.email === email));
|
||||
// For each team linked to the dsync group name provision members
|
||||
for (const group of groupNames) {
|
||||
if (newUserEmails.length) {
|
||||
const newUsers = await createUsersAndConnectToOrg({
|
||||
emailsToCreate: newUserEmails,
|
||||
org,
|
||||
});
|
||||
await prisma.membership.createMany({
|
||||
data: newUsers.map((user) => ({
|
||||
userId: user.id,
|
||||
teamId: group.teamId,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
})),
|
||||
});
|
||||
await Promise.all(
|
||||
newUserEmails.map((email) => {
|
||||
return sendSignupToOrganizationEmail({
|
||||
usernameOrEmail: email,
|
||||
team: { ...group.team, metadata: teamMetadataSchema.parse(group.team.metadata) },
|
||||
translation,
|
||||
inviterName: org.name,
|
||||
teamId: group.teamId,
|
||||
isOrg: false,
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// For existing users create membership for team and org if needed
|
||||
await prisma.membership.createMany({
|
||||
data: [
|
||||
...users
|
||||
.map((user) => {
|
||||
return [
|
||||
{
|
||||
userId: user.id,
|
||||
teamId: group.teamId,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
},
|
||||
{
|
||||
userId: user.id,
|
||||
teamId: organizationId,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
},
|
||||
];
|
||||
})
|
||||
.flat(),
|
||||
],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
|
||||
// Send emails to new members
|
||||
const newMembers = users.filter((user) => !user.teams.find((team) => team.id === group.teamId));
|
||||
const newOrgMembers = users.filter(
|
||||
(user) => !user.profiles.find((profile) => profile.organizationId === organizationId)
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
...newMembers.map(async (user) => {
|
||||
const translation = await getTranslation(user.locale || "en", "common");
|
||||
return sendExistingUserTeamInviteEmails({
|
||||
currentUserTeamName: group.team.name,
|
||||
existingUsersWithMembersips: [user],
|
||||
language: translation,
|
||||
isOrg: false,
|
||||
teamId: group.teamId,
|
||||
isAutoJoin: true,
|
||||
currentUserParentTeamName: org.name,
|
||||
});
|
||||
}),
|
||||
...newOrgMembers.map((user) => {
|
||||
return createAProfileForAnExistingUser({
|
||||
user,
|
||||
organizationId,
|
||||
});
|
||||
}),
|
||||
]);
|
||||
}
|
||||
};
|
||||
|
||||
export default handleGroupEvents;
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { DirectorySyncEvent, User } from "@boxyhq/saml-jackson";
|
||||
|
||||
import removeUserFromOrg from "@calcom/features/ee/dsync/lib/removeUserFromOrg";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { getTeamOrThrow } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
import type { UserWithMembership } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
import { sendExistingUserTeamInviteEmails } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
import { sendSignupToOrganizationEmail } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
|
||||
import createUsersAndConnectToOrg from "./users/createUsersAndConnectToOrg";
|
||||
import dSyncUserSelect from "./users/dSyncUserSelect";
|
||||
import inviteExistingUserToOrg from "./users/inviteExistingUserToOrg";
|
||||
|
||||
const handleUserEvents = async (event: DirectorySyncEvent, organizationId: number) => {
|
||||
const eventData = event.data as User;
|
||||
const userEmail = eventData.email;
|
||||
// Check if user exists in DB
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
email: userEmail,
|
||||
},
|
||||
select: dSyncUserSelect,
|
||||
});
|
||||
|
||||
// User is already a part of that org
|
||||
if (user?.organizationId && eventData.active) {
|
||||
return;
|
||||
}
|
||||
|
||||
const translation = await getTranslation(user?.locale || "en", "common");
|
||||
|
||||
const org = await getTeamOrThrow(organizationId);
|
||||
|
||||
if (!org) {
|
||||
throw new Error("Org not found");
|
||||
}
|
||||
|
||||
if (user) {
|
||||
if (eventData.active) {
|
||||
// If data.active is true then provision the user into the org
|
||||
const addedUser = await inviteExistingUserToOrg({
|
||||
user: user as UserWithMembership,
|
||||
org,
|
||||
translation,
|
||||
});
|
||||
|
||||
await sendExistingUserTeamInviteEmails({
|
||||
currentUserName: user.username,
|
||||
currentUserTeamName: org.name,
|
||||
existingUsersWithMembersips: [addedUser],
|
||||
language: translation,
|
||||
isOrg: true,
|
||||
teamId: org.id,
|
||||
isAutoJoin: true,
|
||||
currentUserParentTeamName: org?.parent?.name,
|
||||
});
|
||||
} else {
|
||||
// If data.active is false then remove the user from the org
|
||||
await removeUserFromOrg({
|
||||
userId: user.id,
|
||||
orgId: organizationId,
|
||||
});
|
||||
}
|
||||
// If user is not in DB, create user and add to the org
|
||||
} else {
|
||||
await createUsersAndConnectToOrg({
|
||||
emailsToCreate: [userEmail],
|
||||
org,
|
||||
});
|
||||
|
||||
await sendSignupToOrganizationEmail({
|
||||
usernameOrEmail: userEmail,
|
||||
team: org,
|
||||
translation,
|
||||
inviterName: org.name,
|
||||
teamId: organizationId,
|
||||
isOrg: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default handleUserEvents;
|
||||
@@ -1,7 +1,7 @@
|
||||
import removeMember from "@calcom/features/ee/teams/lib/removeMember";
|
||||
|
||||
const removeUserFromOrg = async ({ userId, orgId }: { userId: number; orgId: number }) => {
|
||||
await removeMember({
|
||||
return removeMember({
|
||||
memberId: userId,
|
||||
teamId: orgId,
|
||||
isOrg: true,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { canAccess } from "@calcom/features/ee/sso/lib/saml";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
const userCanCreateTeamGroupMapping = async (
|
||||
user: NonNullable<TrpcSessionUser>,
|
||||
organizationId: number | null,
|
||||
teamId?: number
|
||||
) => {
|
||||
if (!organizationId) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Could not find organization id",
|
||||
});
|
||||
}
|
||||
|
||||
const { message, access } = await canAccess(user, organizationId);
|
||||
if (!access) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
if (teamId) {
|
||||
const orgTeam = await prisma.team.findFirst({
|
||||
where: {
|
||||
id: teamId,
|
||||
parentId: organizationId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!orgTeam) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Could not find team",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { organizationId };
|
||||
};
|
||||
|
||||
export default userCanCreateTeamGroupMapping;
|
||||
@@ -0,0 +1,64 @@
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { getTeamOrThrow } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
|
||||
import dSyncUserSelect from "./dSyncUserSelect";
|
||||
|
||||
const createUsersAndConnectToOrg = async ({
|
||||
emailsToCreate,
|
||||
org,
|
||||
}: {
|
||||
emailsToCreate: string[];
|
||||
org: Awaited<ReturnType<typeof getTeamOrThrow>>;
|
||||
}) => {
|
||||
const orgId = org.id;
|
||||
|
||||
// As of Mar 2024 Prisma createMany does not support nested creates and returning created records
|
||||
await prisma.user.createMany({
|
||||
data: emailsToCreate.map((email) => {
|
||||
const [emailUser, emailDomain] = email.split("@");
|
||||
const username = slugify(`${emailUser}-${emailDomain.split(".")[0]}`);
|
||||
return {
|
||||
username,
|
||||
email,
|
||||
// Assume verified since coming from directory
|
||||
verified: true,
|
||||
invitedTo: orgId,
|
||||
organizationId: orgId,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
email: {
|
||||
in: emailsToCreate,
|
||||
},
|
||||
},
|
||||
select: dSyncUserSelect,
|
||||
});
|
||||
|
||||
await prisma.membership.createMany({
|
||||
data: users.map((user) => ({
|
||||
userId: user.id,
|
||||
teamId: orgId,
|
||||
role: MembershipRole.MEMBER,
|
||||
})),
|
||||
});
|
||||
|
||||
await prisma.profile.createMany({
|
||||
data: users.map((user) => ({
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: user.id,
|
||||
// The username is already set when creating the user
|
||||
username: user.username!,
|
||||
organizationId: orgId,
|
||||
})),
|
||||
});
|
||||
|
||||
return users;
|
||||
};
|
||||
|
||||
export default createUsersAndConnectToOrg;
|
||||
@@ -0,0 +1,17 @@
|
||||
const dSyncUserSelect = {
|
||||
id: true,
|
||||
email: true,
|
||||
username: true,
|
||||
organizationId: true,
|
||||
completedOnboarding: true,
|
||||
identityProvider: true,
|
||||
profiles: true,
|
||||
locale: true,
|
||||
password: {
|
||||
select: {
|
||||
hash: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default dSyncUserSelect;
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { TFunction } from "next-i18next";
|
||||
|
||||
import { createAProfileForAnExistingUser } from "@calcom/lib/createAProfileForAnExistingUser";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { UserWithMembership } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/utils";
|
||||
|
||||
/**
|
||||
* This should only be used in a dsync context
|
||||
*/
|
||||
const inviteExistingUserToOrg = async ({
|
||||
user,
|
||||
org,
|
||||
translation,
|
||||
}: {
|
||||
user: UserWithMembership;
|
||||
org: { id: number; name: string; parent: { name: string } | null };
|
||||
translation: TFunction;
|
||||
}) => {
|
||||
await createAProfileForAnExistingUser({
|
||||
user,
|
||||
organizationId: org.id,
|
||||
});
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
organizationId: org.id,
|
||||
teams: {
|
||||
create: {
|
||||
teamId: org.id,
|
||||
role: "MEMBER",
|
||||
// Since coming from directory assume it'll be verified
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return user;
|
||||
};
|
||||
|
||||
export default inviteExistingUserToOrg;
|
||||
@@ -4,8 +4,7 @@ import { useEffect } from "react";
|
||||
import { HOSTED_CAL_FEATURES } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Meta, SkeletonLoader } from "@calcom/ui";
|
||||
import { showToast } from "@calcom/ui";
|
||||
import { Meta, SkeletonLoader, showToast } from "@calcom/ui";
|
||||
|
||||
import { getLayout } from "../../../settings/layouts/SettingsLayout";
|
||||
import ConfigureDirectorySync from "../components/ConfigureDirectorySync";
|
||||
@@ -38,7 +37,21 @@ const DirectorySync = () => {
|
||||
return (
|
||||
<div className="bg-default w-full sm:mx-0 xl:mt-0">
|
||||
<Meta title={t("directory_sync")} description={t("directory_sync_description")} />
|
||||
{HOSTED_CAL_FEATURES && <ConfigureDirectorySync orgId={currentOrg?.id || null} />}
|
||||
{HOSTED_CAL_FEATURES && <ConfigureDirectorySync organizationId={currentOrg?.id || null} />}
|
||||
{/* TODO add additional settings for dsync */}
|
||||
{/* <SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title="Map groups to teams 1:1"
|
||||
description="Members will be auto assigned to teams with the same name as their group."
|
||||
switchContainerClassName="mt-6"
|
||||
/>
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title="Create new teams based on groups"
|
||||
description="Automatically create new teams if a new group is pushed"
|
||||
switchContainerClassName="mt-6"
|
||||
/>
|
||||
<Button>Default team config</Button> */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "DSyncTeamGroupMapping" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"orgId" INTEGER NOT NULL,
|
||||
"teamId" INTEGER NOT NULL,
|
||||
"directoryId" TEXT NOT NULL,
|
||||
"groupName" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "DSyncTeamGroupMapping_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "DSyncTeamGroupMapping_teamId_groupName_key" ON "DSyncTeamGroupMapping"("teamId", "groupName");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "DSyncTeamGroupMapping" ADD CONSTRAINT "DSyncTeamGroupMapping_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "DSyncData" DROP CONSTRAINT "DSyncData_orgId_fkey";
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "DSyncData" ADD CONSTRAINT "DSyncData_orgId_fkey" FOREIGN KEY ("orgId") REFERENCES "OrganizationSettings"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `orgId` on the `DSyncData` table. All the data in the column will be lost.
|
||||
- A unique constraint covering the columns `[organizationId]` on the table `DSyncData` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "DSyncData" DROP CONSTRAINT "DSyncData_orgId_fkey";
|
||||
|
||||
-- DropIndex
|
||||
DROP INDEX "DSyncData_orgId_key";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "DSyncData" DROP COLUMN "orgId",
|
||||
ADD COLUMN "organizationId" INTEGER;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "DSyncData_organizationId_key" ON "DSyncData"("organizationId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "DSyncData" ADD CONSTRAINT "DSyncData_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "OrganizationSettings"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `orgId` on the `DSyncTeamGroupMapping` table. All the data in the column will be lost.
|
||||
- Added the required column `organizationId` to the `DSyncTeamGroupMapping` table without a default value. This is not possible if the table is not empty.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "DSyncTeamGroupMapping" DROP COLUMN "orgId",
|
||||
ADD COLUMN "organizationId" INTEGER NOT NULL;
|
||||
@@ -324,62 +324,63 @@ model Profile {
|
||||
}
|
||||
|
||||
model Team {
|
||||
id Int @id @default(autoincrement())
|
||||
id Int @id @default(autoincrement())
|
||||
/// @zod.min(1)
|
||||
name String
|
||||
name String
|
||||
/// @zod.min(1)
|
||||
slug String?
|
||||
logo String?
|
||||
logoUrl String?
|
||||
calVideoLogo String?
|
||||
appLogo String?
|
||||
appIconLogo String?
|
||||
bio String?
|
||||
hideBranding Boolean @default(false)
|
||||
isPrivate Boolean @default(false)
|
||||
hideBookATeamMember Boolean @default(false)
|
||||
members Membership[]
|
||||
eventTypes EventType[]
|
||||
workflows Workflow[]
|
||||
createdAt DateTime @default(now())
|
||||
slug String?
|
||||
logo String?
|
||||
logoUrl String?
|
||||
calVideoLogo String?
|
||||
appLogo String?
|
||||
appIconLogo String?
|
||||
bio String?
|
||||
hideBranding Boolean @default(false)
|
||||
isPrivate Boolean @default(false)
|
||||
hideBookATeamMember Boolean @default(false)
|
||||
members Membership[]
|
||||
eventTypes EventType[]
|
||||
workflows Workflow[]
|
||||
createdAt DateTime @default(now())
|
||||
/// @zod.custom(imports.teamMetadataSchema)
|
||||
metadata Json?
|
||||
theme String?
|
||||
brandColor String?
|
||||
darkBrandColor String?
|
||||
verifiedNumbers VerifiedNumber[]
|
||||
bannerUrl String?
|
||||
parentId Int?
|
||||
parent Team? @relation("organization", fields: [parentId], references: [id], onDelete: Cascade)
|
||||
children Team[] @relation("organization")
|
||||
orgUsers User[] @relation("scope")
|
||||
inviteTokens VerificationToken[]
|
||||
webhooks Webhook[]
|
||||
timeFormat Int?
|
||||
timeZone String @default("Europe/London")
|
||||
weekStart String @default("Sunday")
|
||||
routingForms App_RoutingForms_Form[]
|
||||
apiKeys ApiKey[]
|
||||
credentials Credential[]
|
||||
accessCodes AccessCode[]
|
||||
isOrganization Boolean @default(false)
|
||||
organizationSettings OrganizationSettings?
|
||||
instantMeetingTokens InstantMeetingToken[]
|
||||
orgProfiles Profile[]
|
||||
pendingPayment Boolean @default(false)
|
||||
dSyncData DSyncData?
|
||||
metadata Json?
|
||||
theme String?
|
||||
brandColor String?
|
||||
darkBrandColor String?
|
||||
verifiedNumbers VerifiedNumber[]
|
||||
bannerUrl String?
|
||||
parentId Int?
|
||||
parent Team? @relation("organization", fields: [parentId], references: [id], onDelete: Cascade)
|
||||
children Team[] @relation("organization")
|
||||
orgUsers User[] @relation("scope")
|
||||
inviteTokens VerificationToken[]
|
||||
webhooks Webhook[]
|
||||
timeFormat Int?
|
||||
timeZone String @default("Europe/London")
|
||||
weekStart String @default("Sunday")
|
||||
routingForms App_RoutingForms_Form[]
|
||||
apiKeys ApiKey[]
|
||||
credentials Credential[]
|
||||
accessCodes AccessCode[]
|
||||
isOrganization Boolean @default(false)
|
||||
organizationSettings OrganizationSettings?
|
||||
instantMeetingTokens InstantMeetingToken[]
|
||||
orgProfiles Profile[]
|
||||
pendingPayment Boolean @default(false)
|
||||
dsyncTeamGroupMapping DSyncTeamGroupMapping[]
|
||||
|
||||
@@unique([slug, parentId])
|
||||
@@index([parentId])
|
||||
}
|
||||
|
||||
model OrganizationSettings {
|
||||
id Int @id @default(autoincrement())
|
||||
organization Team @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
organizationId Int @unique
|
||||
isOrganizationConfigured Boolean @default(false)
|
||||
isOrganizationVerified Boolean @default(false)
|
||||
id Int @id @default(autoincrement())
|
||||
organization Team @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
organizationId Int @unique
|
||||
isOrganizationConfigured Boolean @default(false)
|
||||
isOrganizationVerified Boolean @default(false)
|
||||
orgAutoAcceptEmail String
|
||||
dSyncData DSyncData?
|
||||
}
|
||||
|
||||
enum MembershipRole {
|
||||
@@ -1148,11 +1149,22 @@ model OutOfOfficeEntry {
|
||||
}
|
||||
|
||||
model DSyncData {
|
||||
id Int @id @default(autoincrement())
|
||||
directoryId String
|
||||
tenant String
|
||||
orgId Int? @unique
|
||||
org Team? @relation(fields: [orgId], references: [id], onDelete: Cascade)
|
||||
id Int @id @default(autoincrement())
|
||||
directoryId String
|
||||
tenant String
|
||||
organizationId Int? @unique
|
||||
org OrganizationSettings? @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
}
|
||||
|
||||
model DSyncTeamGroupMapping {
|
||||
id Int @id @default(autoincrement())
|
||||
organizationId Int
|
||||
teamId Int
|
||||
team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
|
||||
directoryId String
|
||||
groupName String
|
||||
|
||||
@@unique([teamId, groupName])
|
||||
}
|
||||
|
||||
model SecondaryEmail {
|
||||
|
||||
@@ -1,66 +1,30 @@
|
||||
import authedOrgAdminProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { router, importHandler } from "../../../trpc";
|
||||
import { ZCreateInputSchema } from "./create.schema";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
import { ZGetInputSchema } from "./get.schema";
|
||||
import { teamGroupMappingRouter } from "./teamGroupMapping/_router";
|
||||
|
||||
type DsyncRouterHandlerCache = {
|
||||
create?: typeof import("./create.handler").createHandler;
|
||||
get?: typeof import("./get.handler").getHandler;
|
||||
delete?: typeof import("./delete.handler").deleteHandler;
|
||||
};
|
||||
const NAMESPACE = "dsync";
|
||||
|
||||
const UNSTABLE_HANDLER_CACHE: DsyncRouterHandlerCache = {};
|
||||
const namespaced = (s: string) => `${NAMESPACE}.${s}`;
|
||||
|
||||
export const dsyncRouter = router({
|
||||
// Create directory sync connection
|
||||
create: authedOrgAdminProcedure.input(ZCreateInputSchema).mutation(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.create) {
|
||||
UNSTABLE_HANDLER_CACHE.create = await import("./create.handler").then((mod) => mod.createHandler);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.create) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.create({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
create: authedOrgAdminProcedure.input(ZCreateInputSchema).mutation(async (opts) => {
|
||||
const handler = await importHandler(namespaced("create"), () => import("./create.handler"));
|
||||
return handler(opts);
|
||||
}),
|
||||
|
||||
// Get directory sync connection
|
||||
get: authedOrgAdminProcedure.input(ZGetInputSchema).query(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.get) {
|
||||
UNSTABLE_HANDLER_CACHE.get = await import("./get.handler").then((mod) => mod.getHandler);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.get) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.get({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
get: authedOrgAdminProcedure.input(ZGetInputSchema).query(async (opts) => {
|
||||
const handler = await importHandler(namespaced("get"), () => import("./get.handler"));
|
||||
return handler(opts);
|
||||
}),
|
||||
|
||||
// Delete directory sync connection
|
||||
delete: authedOrgAdminProcedure.input(ZDeleteInputSchema).mutation(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.delete) {
|
||||
UNSTABLE_HANDLER_CACHE.delete = await import("./delete.handler").then((mod) => mod.deleteHandler);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.delete) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.delete({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
delete: authedOrgAdminProcedure.input(ZDeleteInputSchema).mutation(async (opts) => {
|
||||
const handler = await importHandler(namespaced("delete"), () => import("./delete.handler"));
|
||||
return handler(opts);
|
||||
}),
|
||||
|
||||
teamGroupMapping: teamGroupMappingRouter,
|
||||
});
|
||||
@@ -54,3 +54,5 @@ export const createHandler = async ({ ctx, input }: Options) => {
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export default createHandler;
|
||||
@@ -18,7 +18,7 @@ type Options = {
|
||||
export const deleteHandler = async ({ ctx, input }: Options) => {
|
||||
const { dsyncController } = await jackson();
|
||||
|
||||
const { message, access } = await canAccess(ctx.user, input.orgId);
|
||||
const { message, access } = await canAccess(ctx.user, input.organizationId);
|
||||
|
||||
if (!access) {
|
||||
throw new TRPCError({
|
||||
@@ -29,10 +29,12 @@ export const deleteHandler = async ({ ctx, input }: Options) => {
|
||||
|
||||
await prisma.dSyncData.delete({
|
||||
where: {
|
||||
orgId: input.orgId || undefined,
|
||||
organizationId: input.organizationId || undefined,
|
||||
},
|
||||
});
|
||||
await dsyncController.directories.delete(input.directoryId);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default deleteHandler;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZDeleteInputSchema = z.object({
|
||||
orgId: z.union([z.number(), z.null()]),
|
||||
organizationId: z.union([z.number(), z.null()]),
|
||||
directoryId: z.string(),
|
||||
});
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ type Options = {
|
||||
export const getHandler = async ({ ctx, input }: Options) => {
|
||||
const { dsyncController } = await jackson();
|
||||
|
||||
const { message, access } = await canAccess(ctx.user, input.orgId);
|
||||
const { message, access } = await canAccess(ctx.user, input.organizationId);
|
||||
|
||||
if (!access) {
|
||||
throw new TRPCError({
|
||||
@@ -26,7 +26,7 @@ export const getHandler = async ({ ctx, input }: Options) => {
|
||||
});
|
||||
}
|
||||
|
||||
const tenant = input.orgId ? `${tenantPrefix}${input.orgId}` : (samlTenantID as string);
|
||||
const tenant = input.organizationId ? `${tenantPrefix}${input.organizationId}` : (samlTenantID as string);
|
||||
|
||||
const { data, error } = await dsyncController.directories.getByTenantAndProduct(tenant, samlProductID);
|
||||
|
||||
@@ -37,3 +37,5 @@ export const getHandler = async ({ ctx, input }: Options) => {
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export default getHandler;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZGetInputSchema = z.object({
|
||||
orgId: z.union([z.number(), z.null()]),
|
||||
organizationId: z.union([z.number(), z.null()]),
|
||||
});
|
||||
|
||||
export type ZGetInputSchema = z.infer<typeof ZGetInputSchema>;
|
||||
@@ -0,0 +1,24 @@
|
||||
import authedOrgAdminProcedure from "@calcom/trpc/server/procedures/authedProcedure";
|
||||
import { router, importHandler } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { ZCreateInputSchema } from "./create.schema";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
|
||||
const NAMESPACE = "teamGroupMapping";
|
||||
|
||||
const namespaced = (s: string) => `${NAMESPACE}.${s}`;
|
||||
|
||||
export const teamGroupMappingRouter = router({
|
||||
get: authedOrgAdminProcedure.query(async (opts) => {
|
||||
const handler = await importHandler(namespaced("get"), () => import("./get.handler"));
|
||||
return handler(opts);
|
||||
}),
|
||||
create: authedOrgAdminProcedure.input(ZCreateInputSchema).mutation(async (opts) => {
|
||||
const handler = await importHandler(namespaced("create"), () => import("./create.handler"));
|
||||
return handler(opts);
|
||||
}),
|
||||
delete: authedOrgAdminProcedure.input(ZDeleteInputSchema).mutation(async (opts) => {
|
||||
const handler = await importHandler(namespaced("delete"), () => import("./delete.handler"));
|
||||
return handler(opts);
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import userCanCreateTeamGroupMapping from "@calcom/features/ee/dsync/lib/server/userCanCreateTeamGroupMapping";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import type { ZCreateInputSchema } from "./create.schema";
|
||||
|
||||
type Options = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: ZCreateInputSchema;
|
||||
};
|
||||
|
||||
export const createHandler = async ({ ctx, input }: Options) => {
|
||||
const { organizationId } = await userCanCreateTeamGroupMapping(
|
||||
ctx.user,
|
||||
ctx.user.organizationId,
|
||||
input.teamId
|
||||
);
|
||||
|
||||
await prisma.dSyncTeamGroupMapping.create({
|
||||
data: {
|
||||
organizationId,
|
||||
teamId: input.teamId,
|
||||
groupName: input.name,
|
||||
directoryId: input.directoryId,
|
||||
},
|
||||
});
|
||||
|
||||
return { newGroupName: input.name };
|
||||
};
|
||||
|
||||
export default createHandler;
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZCreateInputSchema = z.object({
|
||||
name: z.string(),
|
||||
teamId: z.number(),
|
||||
directoryId: z.string(),
|
||||
});
|
||||
|
||||
export type ZCreateInputSchema = z.infer<typeof ZCreateInputSchema>;
|
||||
@@ -0,0 +1,30 @@
|
||||
import userCanCreateTeamGroupMapping from "@calcom/features/ee/dsync/lib/server/userCanCreateTeamGroupMapping";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import type { ZDeleteInputSchema } from "./delete.schema";
|
||||
|
||||
type Options = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: ZDeleteInputSchema;
|
||||
};
|
||||
|
||||
// Delete directory sync connection for a team
|
||||
export const deleteHandler = async ({ ctx, input }: Options) => {
|
||||
await userCanCreateTeamGroupMapping(ctx.user, ctx.user.organizationId, input.teamId);
|
||||
|
||||
await prisma.dSyncTeamGroupMapping.delete({
|
||||
where: {
|
||||
teamId_groupName: {
|
||||
teamId: input.teamId,
|
||||
groupName: input.groupName,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { deletedGroupName: input.groupName };
|
||||
};
|
||||
|
||||
export default deleteHandler;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZDeleteInputSchema = z.object({
|
||||
groupName: z.string(),
|
||||
teamId: z.number(),
|
||||
});
|
||||
|
||||
export type ZDeleteInputSchema = z.infer<typeof ZDeleteInputSchema>;
|
||||
@@ -0,0 +1,72 @@
|
||||
import userCanCreateTeamGroupMapping from "@calcom/features/ee/dsync/lib/server/userCanCreateTeamGroupMapping";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
type Options = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
};
|
||||
|
||||
export const getHandler = async ({ ctx }: Options) => {
|
||||
const { organizationId } = await userCanCreateTeamGroupMapping(ctx.user, ctx.user.organizationId);
|
||||
|
||||
// Get org teams
|
||||
const teamsQuery = await prisma.team.findMany({
|
||||
where: {
|
||||
parentId: organizationId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
});
|
||||
|
||||
const directoryId = await prisma.dSyncData.findFirst({
|
||||
where: {
|
||||
organizationId,
|
||||
},
|
||||
select: {
|
||||
directoryId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!directoryId) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Could not find directory id" });
|
||||
}
|
||||
|
||||
const teamGroupMappingQuery = await prisma.dSyncTeamGroupMapping.findMany({
|
||||
where: {
|
||||
directoryId: directoryId.directoryId,
|
||||
},
|
||||
select: {
|
||||
teamId: true,
|
||||
groupName: true,
|
||||
},
|
||||
});
|
||||
|
||||
const teamGroupMapping = teamsQuery.map((team) => {
|
||||
return {
|
||||
id: team.id,
|
||||
name: team.name,
|
||||
slug: team.slug,
|
||||
directoryId: directoryId?.directoryId,
|
||||
groupNames: teamGroupMappingQuery.reduce((groupNames, mapping) => {
|
||||
if (mapping.teamId === team.id) {
|
||||
groupNames.push(mapping.groupName);
|
||||
}
|
||||
|
||||
return groupNames;
|
||||
}, [] as string[]),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
teamGroupMapping,
|
||||
};
|
||||
};
|
||||
|
||||
export default getHandler;
|
||||
@@ -120,7 +120,8 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) =
|
||||
team,
|
||||
translation,
|
||||
inviterName: ctx.user.name ?? "",
|
||||
input,
|
||||
teamId: input.teamId,
|
||||
isOrg: input.isOrg,
|
||||
});
|
||||
});
|
||||
sendEmails(sendVerifEmailsPromises);
|
||||
|
||||
@@ -369,19 +369,15 @@ export async function sendSignupToOrganizationEmail({
|
||||
team,
|
||||
translation,
|
||||
inviterName,
|
||||
input,
|
||||
teamId,
|
||||
isOrg,
|
||||
}: {
|
||||
usernameOrEmail: string;
|
||||
team: Awaited<ReturnType<typeof getTeamOrThrow>>;
|
||||
translation: TFunction;
|
||||
inviterName: string;
|
||||
input: {
|
||||
teamId: number;
|
||||
role: "ADMIN" | "MEMBER" | "OWNER";
|
||||
usernameOrEmail: string | string[];
|
||||
language: string;
|
||||
isOrg: boolean;
|
||||
};
|
||||
teamId: number;
|
||||
isOrg: boolean;
|
||||
}) {
|
||||
const token: string = randomBytes(32).toString("hex");
|
||||
|
||||
@@ -392,7 +388,7 @@ export async function sendSignupToOrganizationEmail({
|
||||
expires: new Date(new Date().setHours(168)), // +1 week
|
||||
team: {
|
||||
connect: {
|
||||
id: input.teamId,
|
||||
id: teamId,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -404,7 +400,7 @@ export async function sendSignupToOrganizationEmail({
|
||||
teamName: team.name,
|
||||
joinLink: `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`,
|
||||
isCalcomMember: false,
|
||||
isOrg: input.isOrg,
|
||||
isOrg: isOrg,
|
||||
parentTeamName: team?.parent?.name,
|
||||
isAutoJoin: false,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user