feat: admin org list now shows all, dns check added (#10875)

* chore: admin org list now shows all, dns check added

* Updating email template

* type fixes
This commit is contained in:
Leo Giovanetti authored and GitHub committed 2023-08-23 21:01:12 +00:00
1 parent 68ec946c59
commit e6e6f09547
15 files changed
+432 -147

No files matched your search

@@ -63,11 +63,8 @@ export const viewerOrganizationsRouter = router({
const handler = await importHandler(namespaced("getMembers"), () => import("./getMembers.handler"));
return handler(opts);
}),
adminGetUnverified: authedAdminProcedure.query(async (opts) => {
const handler = await importHandler(
namespaced("adminGetUnverified"),
() => import("./adminGetUnverified.handler")
);
adminGetAll: authedAdminProcedure.query(async (opts) => {
const handler = await importHandler(namespaced("adminGetAll"), () => import("./adminGetAll.handler"));
return handler(opts);
}),
adminVerify: authedAdminProcedure.input(ZAdminVerifyInput).mutation(async (opts) => {
@@ -1,15 +1,16 @@
import { prisma } from "@calcom/prisma";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
import type { TrpcSessionUser } from "../../../trpc";
type AdminGetUnverifiedOptions = {
type AdminGetAllOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
};
export const adminGetUnverifiedHandler = async ({ ctx }: AdminGetUnverifiedOptions) => {
const unVerifiedTeams = await prisma.team.findMany({
export const adminGetUnverifiedHandler = async ({ ctx }: AdminGetAllOptions) => {
const allOrgs = await prisma.team.findMany({
where: {
AND: [
{
@@ -18,18 +19,13 @@ export const adminGetUnverifiedHandler = async ({ ctx }: AdminGetUnverifiedOptio
equals: true,
},
},
{
metadata: {
path: ["isOrganizationVerified"],
equals: false,
},
},
],
},
select: {
id: true,
name: true,
slug: true,
metadata: true,
members: {
where: {
role: "OWNER",
@@ -47,7 +43,7 @@ export const adminGetUnverifiedHandler = async ({ ctx }: AdminGetUnverifiedOptio
},
});
return unVerifiedTeams;
return allOrgs.map((org) => ({ ...org, metadata: teamMetadataSchema.parse(org.metadata) }));
};
export default adminGetUnverifiedHandler;
@@ -1,19 +1,21 @@
import { createHash } from "crypto";
import { lookup } from "dns";
import { totp } from "otplib";
import { sendOrganizationEmailVerification } from "@calcom/emails";
import { sendAdminOrganizationNotification } from "@calcom/emails";
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
import {
IS_CALCOM,
IS_TEAM_BILLING_ENABLED,
RESERVED_SUBDOMAINS,
IS_PRODUCTION,
WEBAPP_URL,
} from "@calcom/lib/constants";
import { getTranslation } from "@calcom/lib/server/i18n";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import { MembershipRole, UserPermissionRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
@@ -27,6 +29,15 @@ type CreateOptions = {
input: TCreateInputSchema;
};
const getIPAddress = async (url: string): Promise<string> => {
return new Promise((resolve, reject) => {
lookup(url, (err, address) => {
if (err) reject(err);
resolve(address);
});
});
};
const vercelCreateDomain = async (domain: string) => {
const response = await fetch(
`https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains?teamId=${process.env.TEAM_ID_VERCEL}`,
@@ -43,12 +54,10 @@ const vercelCreateDomain = async (domain: string) => {
const data = await response.json();
// Domain is already owned by another team but you can request delegation to access it
if (data.error?.code === "forbidden")
throw new TRPCError({ code: "CONFLICT", message: "domain_taken_team" });
if (data.error?.code === "forbidden") return false;
// Domain is already being used by a different project
if (data.error?.code === "domain_taken")
throw new TRPCError({ code: "CONFLICT", message: "domain_taken_project" });
if (data.error?.code === "domain_taken") return false;
return true;
};
@@ -85,9 +94,35 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {
const t = await getTranslation(ctx.user.locale ?? "en", "common");
const availability = getAvailabilityFromSchedule(DEFAULT_SCHEDULE);
let isOrganizationConfigured = false;
if (check === false) {
if (IS_CALCOM) await vercelCreateDomain(slug);
// eslint-disable-next-line turbo/no-undeclared-env-vars
if (process.env.VERCEL) {
// We only want to proceed to register the subdomain for the org in Vercel
// within a Vercel context
isOrganizationConfigured = await vercelCreateDomain(slug);
} else {
// Otherwise, we proceed to send an administrative email to admins regarding
// the need to configure DNS registry to support the newly created org
const instanceAdmins = await prisma.user.findMany({
where: { role: UserPermissionRole.ADMIN },
select: { email: true },
});
if (instanceAdmins.length) {
await sendAdminOrganizationNotification({
instanceAdmins,
orgSlug: slug,
ownerEmail: adminEmail,
webappIPAddress: await getIPAddress(
WEBAPP_URL.replace("https://", "")?.replace("http://", "").replace(/(:.*)/, "")
),
t,
});
} else {
console.warn("Organization created: subdomain not configured and couldn't notify adminnistrators");
}
}
const createOwnerOrg = await prisma.user.create({
data: {
@@ -118,6 +153,7 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {
...(IS_TEAM_BILLING_ENABLED && { requestedSlug: slug }),
isOrganization: true,
isOrganizationVerified: false,
isOrganizationConfigured,
orgAutoAcceptEmail: emailDomain,
},
},
@@ -1,9 +1,11 @@
import type { Prisma } from "@prisma/client";
import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants";
import { getMetadataHelpers } from "@calcom/lib/getMetadataHelpers";
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import { closeComUpdateTeam } from "@calcom/lib/sync/SyncServiceManager";
import { prisma } from "@calcom/prisma";
import { UserPermissionRole } from "@calcom/prisma/enums";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
import { TRPCError } from "@trpc/server";
@@ -20,11 +22,13 @@ type UpdateOptions = {
export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
// A user can only have one org so we pass in their currentOrgId here
const currentOrgId = ctx.user?.organization?.id;
const currentOrgId = ctx.user?.organization?.id || input.orgId;
if (!currentOrgId) throw new TRPCError({ code: "UNAUTHORIZED" });
if (!currentOrgId || ctx.user.role !== UserPermissionRole.ADMIN)
throw new TRPCError({ code: "UNAUTHORIZED" });
if (!(await isOrganisationAdmin(ctx.user?.id, currentOrgId))) throw new TRPCError({ code: "UNAUTHORIZED" });
if (!(await isOrganisationAdmin(ctx.user?.id, currentOrgId)) || ctx.user.role !== UserPermissionRole.ADMIN)
throw new TRPCError({ code: "UNAUTHORIZED" });
if (input.slug) {
const userConflict = await prisma.team.findMany({
@@ -51,6 +55,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
});
if (!prevOrganisation) throw new TRPCError({ code: "NOT_FOUND", message: "Organisation not found." });
const { mergeMetadata } = getMetadataHelpers(teamMetadataSchema.unwrap(), prevOrganisation.metadata);
const data: Prisma.TeamUpdateArgs["data"] = {
name: input.name,
@@ -64,6 +69,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
timeZone: input.timeZone,
weekStart: input.weekStart,
timeFormat: input.timeFormat,
metadata: mergeMetadata({ ...input.metadata }),
};
if (input.slug) {
@@ -73,20 +79,14 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
!prevOrganisation.slug
) {
// Save it on the metadata so we can use it later
data.metadata = {
requestedSlug: input.slug,
};
data.metadata = mergeMetadata({ requestedSlug: input.slug });
} else {
data.slug = input.slug;
// If we save slug, we don't need the requestedSlug anymore
const metadataParse = teamMetadataSchema.safeParse(prevOrganisation.metadata);
if (metadataParse.success) {
const { requestedSlug: _, ...cleanMetadata } = metadataParse.data || {};
data.metadata = {
...cleanMetadata,
};
}
data.metadata = mergeMetadata({
// If we save slug, we don't need the requestedSlug anymore
requestedSlug: undefined,
...input.metadata,
});
}
}
@@ -1,11 +1,14 @@
import { z } from "zod";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
export const ZUpdateInputSchema = z.object({
name: z.string().optional(),
orgId: z
.string()
.regex(/^\d+$/)
.transform((id) => parseInt(id))
.or(z.number())
.optional(),
bio: z.string().optional(),
logo: z
@@ -22,6 +25,7 @@ export const ZUpdateInputSchema = z.object({
timeZone: z.string().optional(),
weekStart: z.string().optional(),
timeFormat: z.number().optional(),
metadata: teamMetadataSchema.unwrap().pick({ isOrganizationConfigured: true }).optional(),
});
export type TUpdateInputSchema = z.infer<typeof ZUpdateInputSchema>;