[Feat] Bulk Invite of Users + Google Workspace (#8969)
* Base UI work * Bulk invite users * WIP workspace oauth implementation * Seperate components - add existing gcal check * Move callback session to getServerSession * Implementation of state redirect back to teams on login * Add callback to populate text field * Change error message * Redirect from callback and open modal * Fix bulk translations * Fix translations for google button * Delete Query * Feature flag this * Update packages/trpc/server/routers/viewer/teams/inviteMember.handler.ts * Check if Gcal in installed globally * Add new router * Add missing [trpc] route * Feedback * Update packages/trpc/server/routers/viewer/googleWorkspace/googleWorkspace.handler.ts * Typefixes * More typefixes --------- Co-authored-by: Hariom Balhara <[email protected]> Co-authored-by: zomars <[email protected]>
This commit is contained in:
22 files changed
+738
-170
No files matched your search
@@ -14,6 +14,7 @@ import { availabilityRouter } from "./availability/_router";
|
||||
import { bookingsRouter } from "./bookings/_router";
|
||||
import { deploymentSetupRouter } from "./deploymentSetup/_router";
|
||||
import { eventTypesRouter } from "./eventTypes/_router";
|
||||
import { googleWorkspaceRouter } from "./googleWorkspace/_router";
|
||||
import { paymentsRouter } from "./payments/_router";
|
||||
import { slotsRouter } from "./slots/_router";
|
||||
import { ssoRouter } from "./sso/_router";
|
||||
@@ -46,5 +47,6 @@ export const viewerRouter = mergeRouters(
|
||||
features: featureFlagRouter,
|
||||
appsRouter,
|
||||
users: userAdminRouter,
|
||||
googleWorkspace: googleWorkspaceRouter,
|
||||
})
|
||||
);
|
||||
@@ -1,5 +1,6 @@
|
||||
import authedProcedure, { authedAdminProcedure } from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { checkGlobalKeysSchema } from "./checkGlobalKeys.schema";
|
||||
import { ZListLocalInputSchema } from "./listLocal.schema";
|
||||
import { ZQueryForDependenciesInputSchema } from "./queryForDependencies.schema";
|
||||
import { ZSaveKeysInputSchema } from "./saveKeys.schema";
|
||||
@@ -13,6 +14,7 @@ type AppsRouterHandlerCache = {
|
||||
checkForGCal?: typeof import("./checkForGCal.handler").checkForGCalHandler;
|
||||
updateAppCredentials?: typeof import("./updateAppCredentials.handler").updateAppCredentialsHandler;
|
||||
queryForDependencies?: typeof import("./queryForDependencies.handler").queryForDependenciesHandler;
|
||||
checkGlobalKeys?: typeof import("./checkGlobalKeys.handler").checkForGlobalKeysHandler;
|
||||
};
|
||||
|
||||
const UNSTABLE_HANDLER_CACHE: AppsRouterHandlerCache = {};
|
||||
@@ -124,4 +126,21 @@ export const appsRouter = router({
|
||||
input,
|
||||
});
|
||||
}),
|
||||
checkGlobalKeys: authedProcedure.input(checkGlobalKeysSchema).query(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.checkGlobalKeys) {
|
||||
UNSTABLE_HANDLER_CACHE.checkGlobalKeys = await import("./checkGlobalKeys.handler").then(
|
||||
(mod) => mod.checkForGlobalKeysHandler
|
||||
);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.checkGlobalKeys) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.checkGlobalKeys({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../trpc";
|
||||
import type { CheckGlobalKeysSchemaType } from "./checkGlobalKeys.schema";
|
||||
|
||||
type checkForGlobalKeys = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: CheckGlobalKeysSchemaType;
|
||||
};
|
||||
|
||||
export const checkForGlobalKeysHandler = async ({ ctx, input }: checkForGlobalKeys) => {
|
||||
const appIsGloballyInstalled = await prisma.app.findUnique({
|
||||
where: {
|
||||
slug: input.slug,
|
||||
},
|
||||
});
|
||||
|
||||
return !!appIsGloballyInstalled;
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const checkGlobalKeysSchema = z.object({
|
||||
slug: z.string(),
|
||||
});
|
||||
|
||||
export type CheckGlobalKeysSchemaType = z.infer<typeof checkGlobalKeysSchema>;
|
||||
@@ -0,0 +1,61 @@
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
|
||||
type GoogleWorkspaceCache = {
|
||||
checkForGWorkspace?: typeof import("./googleWorkspace.handler").checkForGWorkspace;
|
||||
getUsersFromGWorkspace?: typeof import("./googleWorkspace.handler").getUsersFromGWorkspace;
|
||||
removeCurrentGoogleWorkspaceConnection?: typeof import("./googleWorkspace.handler").removeCurrentGoogleWorkspaceConnection;
|
||||
};
|
||||
|
||||
const UNSTABLE_HANDLER_CACHE: GoogleWorkspaceCache = {};
|
||||
|
||||
export const googleWorkspaceRouter = router({
|
||||
checkForGWorkspace: authedProcedure.query(async ({ ctx }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.checkForGWorkspace) {
|
||||
UNSTABLE_HANDLER_CACHE.checkForGWorkspace = await import("./googleWorkspace.handler").then(
|
||||
(mod) => mod.checkForGWorkspace
|
||||
);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.checkForGWorkspace) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.checkForGWorkspace({
|
||||
ctx,
|
||||
});
|
||||
}),
|
||||
getUsersFromGWorkspace: authedProcedure.mutation(async ({ ctx }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.getUsersFromGWorkspace) {
|
||||
UNSTABLE_HANDLER_CACHE.getUsersFromGWorkspace = await import("./googleWorkspace.handler").then(
|
||||
(mod) => mod.getUsersFromGWorkspace
|
||||
);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.getUsersFromGWorkspace) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.getUsersFromGWorkspace({
|
||||
ctx,
|
||||
});
|
||||
}),
|
||||
removeCurrentGoogleWorkspaceConnection: authedProcedure.mutation(async ({ ctx }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.removeCurrentGoogleWorkspaceConnection) {
|
||||
UNSTABLE_HANDLER_CACHE.removeCurrentGoogleWorkspaceConnection = await import(
|
||||
"./googleWorkspace.handler"
|
||||
).then((mod) => mod.removeCurrentGoogleWorkspaceConnection);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.removeCurrentGoogleWorkspaceConnection) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.removeCurrentGoogleWorkspaceConnection({
|
||||
ctx,
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { google } from "googleapis";
|
||||
import { z } from "zod";
|
||||
|
||||
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../trpc";
|
||||
|
||||
type CheckForGCalOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
};
|
||||
|
||||
const credentialsSchema = z.object({
|
||||
refresh_token: z.string().optional(),
|
||||
expiry_date: z.number().optional(),
|
||||
access_token: z.string().optional(),
|
||||
token_type: z.string().optional(),
|
||||
id_token: z.string().optional(),
|
||||
scope: z.string().optional(),
|
||||
});
|
||||
|
||||
export const checkForGWorkspace = async ({ ctx }: CheckForGCalOptions) => {
|
||||
const gWorkspacePresent = await prisma.credential.findFirst({
|
||||
where: {
|
||||
type: "google_workspace_directory",
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
return { id: gWorkspacePresent?.id };
|
||||
};
|
||||
|
||||
export const getUsersFromGWorkspace = async ({ ctx }: CheckForGCalOptions) => {
|
||||
const { client_id, client_secret } = await getAppKeysFromSlug("google-calendar");
|
||||
if (!client_id || typeof client_id !== "string") throw new Error("Google client_id missing.");
|
||||
if (!client_secret || typeof client_secret !== "string") throw new Error("Google client_secret missing.");
|
||||
|
||||
const hasExistingCredentials = await prisma.credential.findFirst({
|
||||
where: {
|
||||
type: "google_workspace_directory",
|
||||
},
|
||||
});
|
||||
if (!hasExistingCredentials) {
|
||||
throw new Error("No workspace credentials found");
|
||||
}
|
||||
|
||||
const credentials = credentialsSchema.parse(hasExistingCredentials.key);
|
||||
|
||||
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret);
|
||||
|
||||
// Set users credentials instead of our app credentials - allowing us to make requests on their behalf
|
||||
oAuth2Client.setCredentials(credentials);
|
||||
|
||||
// Create a new instance of the Admin SDK directory API
|
||||
const directory = google.admin({ version: "directory_v1", auth: oAuth2Client });
|
||||
|
||||
const { data } = await directory.users.list({
|
||||
maxResults: 200, // Up this if we ever need to get more than 200 users
|
||||
customer: "my_customer", // This only works for single domain setups - we'll need to change this if we ever support multi-domain setups (unlikely we'll ever need to)
|
||||
});
|
||||
|
||||
// We only want their email addresses
|
||||
const emails = data.users?.map((user) => user.primaryEmail as string) ?? ([] as string[]);
|
||||
return emails;
|
||||
};
|
||||
|
||||
export const removeCurrentGoogleWorkspaceConnection = async ({ ctx }: CheckForGCalOptions) => {
|
||||
// There should only ever be one google_workspace_directory credential per user but we delete many as we can't make type unique
|
||||
const gWorkspacePresent = await prisma.credential.deleteMany({
|
||||
where: {
|
||||
type: "google_workspace_directory",
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
|
||||
return { deleted: gWorkspacePresent?.count };
|
||||
};
|
||||
@@ -37,113 +37,121 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) =
|
||||
|
||||
if (!team) throw new TRPCError({ code: "NOT_FOUND", message: "Team not found" });
|
||||
|
||||
// A user can exist even if they have not completed onboarding
|
||||
const invitee = await prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [{ username: input.usernameOrEmail }, { email: input.usernameOrEmail }],
|
||||
},
|
||||
});
|
||||
const emailsToInvite = Array.isArray(input.usernameOrEmail)
|
||||
? input.usernameOrEmail
|
||||
: [input.usernameOrEmail];
|
||||
|
||||
if (!invitee) {
|
||||
// liberal email match
|
||||
|
||||
if (!isEmail(input.usernameOrEmail))
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: `Invite failed because there is no corresponding user for ${input.usernameOrEmail}`,
|
||||
});
|
||||
|
||||
// valid email given, create User and add to team
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
email: input.usernameOrEmail,
|
||||
invitedTo: input.teamId,
|
||||
teams: {
|
||||
create: {
|
||||
teamId: input.teamId,
|
||||
role: input.role as MembershipRole,
|
||||
},
|
||||
},
|
||||
emailsToInvite.forEach(async (usernameOrEmail) => {
|
||||
const invitee = await prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [{ username: usernameOrEmail }, { email: usernameOrEmail }],
|
||||
},
|
||||
});
|
||||
|
||||
const token: string = randomBytes(32).toString("hex");
|
||||
if (!invitee) {
|
||||
// liberal email match
|
||||
|
||||
await prisma.verificationToken.create({
|
||||
data: {
|
||||
identifier: input.usernameOrEmail,
|
||||
token,
|
||||
expires: new Date(new Date().setHours(168)), // +1 week
|
||||
},
|
||||
});
|
||||
if (ctx?.user?.name && team?.name) {
|
||||
await sendTeamInviteEmail({
|
||||
language: translation,
|
||||
from: ctx.user.name,
|
||||
to: input.usernameOrEmail,
|
||||
teamName: team.name,
|
||||
joinLink: `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`, // we know that the user has not completed onboarding yet, so we can redirect them to the onboarding flow
|
||||
isCalcomMember: false,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// create provisional membership
|
||||
try {
|
||||
await prisma.membership.create({
|
||||
data: {
|
||||
teamId: input.teamId,
|
||||
userId: invitee.id,
|
||||
role: input.role as MembershipRole,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002") {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "This user is a member of this team / has a pending invitation.",
|
||||
});
|
||||
}
|
||||
} else throw e;
|
||||
}
|
||||
|
||||
let sendTo = input.usernameOrEmail;
|
||||
if (!isEmail(input.usernameOrEmail)) {
|
||||
sendTo = invitee.email;
|
||||
}
|
||||
// inform user of membership by email
|
||||
if (input.sendEmailInvitation && ctx?.user?.name && team?.name) {
|
||||
const inviteTeamOptions = {
|
||||
joinLink: `${WEBAPP_URL}/auth/login?callbackUrl=/settings/teams`,
|
||||
isCalcomMember: true,
|
||||
};
|
||||
/**
|
||||
* Here we want to redirect to a differnt place if onboarding has been completed or not. This prevents the flash of going to teams -> Then to onboarding - also show a differnt email template.
|
||||
* This only changes if the user is a CAL user and has not completed onboarding and has no password
|
||||
*/
|
||||
if (!invitee.completedOnboarding && !invitee.password && invitee.identityProvider === "CAL") {
|
||||
const token = randomBytes(32).toString("hex");
|
||||
await prisma.verificationToken.create({
|
||||
data: {
|
||||
identifier: input.usernameOrEmail,
|
||||
token,
|
||||
expires: new Date(new Date().setHours(168)), // +1 week
|
||||
},
|
||||
if (!isEmail(usernameOrEmail))
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: `Invite failed because there is no corresponding user for ${usernameOrEmail}`,
|
||||
});
|
||||
|
||||
inviteTeamOptions.joinLink = `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`;
|
||||
inviteTeamOptions.isCalcomMember = false;
|
||||
// valid email given, create User and add to team
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
email: usernameOrEmail,
|
||||
invitedTo: input.teamId,
|
||||
teams: {
|
||||
create: {
|
||||
teamId: input.teamId,
|
||||
role: input.role as MembershipRole,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const token: string = randomBytes(32).toString("hex");
|
||||
|
||||
await prisma.verificationToken.create({
|
||||
data: {
|
||||
identifier: usernameOrEmail,
|
||||
token,
|
||||
expires: new Date(new Date().setHours(168)), // +1 week
|
||||
},
|
||||
});
|
||||
if (ctx?.user?.name && team?.name) {
|
||||
await sendTeamInviteEmail({
|
||||
language: translation,
|
||||
from: ctx.user.name,
|
||||
to: usernameOrEmail,
|
||||
teamName: team.name,
|
||||
joinLink: `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`, // we know that the user has not completed onboarding yet, so we can redirect them to the onboarding flow
|
||||
isCalcomMember: false,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// create provisional membership
|
||||
try {
|
||||
await prisma.membership.create({
|
||||
data: {
|
||||
teamId: input.teamId,
|
||||
userId: invitee.id,
|
||||
role: input.role as MembershipRole,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
// Don't throw an error if the user is already a member of the team when inviting multiple users
|
||||
if (!Array.isArray(input.usernameOrEmail) && e.code === "P2002") {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "This user is a member of this team / has a pending invitation.",
|
||||
});
|
||||
} else {
|
||||
console.log(`User ${invitee.id} is already a member of this team.`);
|
||||
}
|
||||
} else throw e;
|
||||
}
|
||||
|
||||
await sendTeamInviteEmail({
|
||||
language: translation,
|
||||
from: ctx.user.name,
|
||||
to: sendTo,
|
||||
teamName: team.name,
|
||||
...inviteTeamOptions,
|
||||
});
|
||||
let sendTo = usernameOrEmail;
|
||||
if (!isEmail(usernameOrEmail)) {
|
||||
sendTo = invitee.email;
|
||||
}
|
||||
// inform user of membership by email
|
||||
if (input.sendEmailInvitation && ctx?.user?.name && team?.name) {
|
||||
const inviteTeamOptions = {
|
||||
joinLink: `${WEBAPP_URL}/auth/login?callbackUrl=/settings/teams`,
|
||||
isCalcomMember: true,
|
||||
};
|
||||
/**
|
||||
* Here we want to redirect to a differnt place if onboarding has been completed or not. This prevents the flash of going to teams -> Then to onboarding - also show a differnt email template.
|
||||
* This only changes if the user is a CAL user and has not completed onboarding and has no password
|
||||
*/
|
||||
if (!invitee.completedOnboarding && !invitee.password && invitee.identityProvider === "CAL") {
|
||||
const token = randomBytes(32).toString("hex");
|
||||
await prisma.verificationToken.create({
|
||||
data: {
|
||||
identifier: usernameOrEmail,
|
||||
token,
|
||||
expires: new Date(new Date().setHours(168)), // +1 week
|
||||
},
|
||||
});
|
||||
|
||||
inviteTeamOptions.joinLink = `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`;
|
||||
inviteTeamOptions.isCalcomMember = false;
|
||||
}
|
||||
|
||||
await sendTeamInviteEmail({
|
||||
language: translation,
|
||||
from: ctx.user.name,
|
||||
to: sendTo,
|
||||
teamName: team.name,
|
||||
...inviteTeamOptions,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (IS_TEAM_BILLING_ENABLED) await updateQuantitySubscriptionFromStripe(input.teamId);
|
||||
return input;
|
||||
};
|
||||
@@ -4,7 +4,12 @@ import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
export const ZInviteMemberInputSchema = z.object({
|
||||
teamId: z.number(),
|
||||
usernameOrEmail: z.string().transform((usernameOrEmail) => usernameOrEmail.trim().toLowerCase()),
|
||||
usernameOrEmail: z.union([z.string(), z.array(z.string())]).transform((usernameOrEmail) => {
|
||||
if (typeof usernameOrEmail === "string") {
|
||||
return usernameOrEmail.trim().toLowerCase();
|
||||
}
|
||||
return usernameOrEmail.map((item) => item.trim().toLowerCase());
|
||||
}),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
language: z.string(),
|
||||
sendEmailInvitation: z.boolean(),
|
||||
|
||||
Reference in new issue
Block a user