perf: tRPC procedures and middleware refactor (#8419)
* trpc procedures an middleware refactor * allow use sessionMiddleware without a req object * sync with the new tRPC structure * tRPC refactor on routing form app * import Prisma from @prisma/client * Lazy load apps from appstore * remove unrelated changes * Add types for PaymentService * type fixes * Merge branch 'main' into roae85/cal-1514-set-the-user-session-only-on-the * fix typo * remove console.log * remove explicit types from apstore object * linter fixes --------- Co-authored-by: Keith Williams <[email protected]> Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
63 files changed
+1818
-1019
No files matched your search
@@ -1,35 +1,36 @@
|
||||
import type { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from "next";
|
||||
import type { Session } from "next-auth";
|
||||
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
|
||||
import type { serverSideTranslations } from "next-i18next/serverSideTranslations";
|
||||
|
||||
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import { getLocaleFromHeaders } from "@calcom/lib/i18n";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { SelectedCalendar, User as PrismaUser, Credential } from "@calcom/prisma/client";
|
||||
import type { SelectedCalendar, User as PrismaUser } from "@calcom/prisma/client";
|
||||
|
||||
import type { CreateNextContextOptions } from "@trpc/server/adapters/next";
|
||||
|
||||
type CreateContextOptions = CreateNextContextOptions | GetServerSidePropsContext;
|
||||
|
||||
export type CreateInnerContextOptions = {
|
||||
session: Session | null;
|
||||
session?: Session | null;
|
||||
locale: string;
|
||||
user?: Omit<
|
||||
PrismaUser,
|
||||
| "locale"
|
||||
| "twoFactorSecret"
|
||||
| "emailVerified"
|
||||
| "password"
|
||||
| "identityProviderId"
|
||||
| "invitedTo"
|
||||
| "allowDynamicBooking"
|
||||
| "verified"
|
||||
> & {
|
||||
locale: NonNullable<PrismaUser["locale"]>;
|
||||
credentials?: Credential[];
|
||||
selectedCalendars?: Partial<SelectedCalendar>[];
|
||||
};
|
||||
i18n: Awaited<ReturnType<typeof serverSideTranslations>>;
|
||||
user?:
|
||||
| Omit<
|
||||
PrismaUser,
|
||||
| "locale"
|
||||
| "twoFactorSecret"
|
||||
| "emailVerified"
|
||||
| "password"
|
||||
| "identityProviderId"
|
||||
| "invitedTo"
|
||||
| "allowDynamicBooking"
|
||||
| "verified"
|
||||
> & {
|
||||
locale: Exclude<PrismaUser["locale"], null>;
|
||||
credentials?: Credential[];
|
||||
selectedCalendars?: Partial<SelectedCalendar>[];
|
||||
rawAvatar?: string;
|
||||
};
|
||||
i18n?: Awaited<ReturnType<typeof serverSideTranslations>>;
|
||||
} & Partial<CreateContextOptions>;
|
||||
|
||||
export type GetSessionFn =
|
||||
@@ -39,8 +40,6 @@ export type GetSessionFn =
|
||||
}) => Promise<Session | null>)
|
||||
| (() => Promise<Session | null>);
|
||||
|
||||
const DEFAULT_SESSION_GETTER: GetSessionFn = ({ req, res }) => getServerSession({ req, res });
|
||||
|
||||
/**
|
||||
* Inner context. Will always be available in your procedures, in contrast to the outer context.
|
||||
*
|
||||
@@ -61,16 +60,10 @@ export async function createContextInner(opts: CreateInnerContextOptions) {
|
||||
* Creates context for an incoming request
|
||||
* @link https://trpc.io/docs/context
|
||||
*/
|
||||
export const createContext = async (
|
||||
{ req, res }: CreateContextOptions,
|
||||
sessionGetter: GetSessionFn = DEFAULT_SESSION_GETTER
|
||||
) => {
|
||||
// for API-response caching see https://trpc.io/docs/caching
|
||||
const session = await sessionGetter({ req, res });
|
||||
|
||||
export const createContext = async ({ req, res }: CreateContextOptions) => {
|
||||
const locale = getLocaleFromHeaders(req);
|
||||
const i18n = await serverSideTranslations(getLocaleFromHeaders(req), ["common", "vital"]);
|
||||
const contextInner = await createContextInner({ session, i18n, locale });
|
||||
|
||||
const contextInner = await createContextInner({ locale });
|
||||
return {
|
||||
...contextInner,
|
||||
req,
|
||||
@@ -79,3 +72,8 @@ export const createContext = async (
|
||||
};
|
||||
|
||||
export type TRPCContext = Awaited<ReturnType<typeof createContext>>;
|
||||
export type TRPCContextInner = Awaited<ReturnType<typeof createContextInner>>;
|
||||
export type WithLocale<T extends TRPCContext = any> = T &
|
||||
Required<Pick<CreateInnerContextOptions, "i18n" | "locale">>;
|
||||
export type WithSession<T extends TRPCContext = any> = T &
|
||||
Required<Pick<CreateInnerContextOptions, "session">>;
|
||||
@@ -0,0 +1,19 @@
|
||||
import sessionMiddleware from "./sessionMiddleware";
|
||||
|
||||
const localeMiddleware = sessionMiddleware.unstable_pipe(async ({ ctx, next }) => {
|
||||
const { serverSideTranslations } = await import("next-i18next/serverSideTranslations");
|
||||
const { user } = ctx;
|
||||
|
||||
const i18n = await serverSideTranslations(
|
||||
user?.locale && user?.locale !== ctx.locale ? user.locale : ctx.locale,
|
||||
["common", "vital"]
|
||||
);
|
||||
|
||||
const locale = user?.locale || ctx.locale;
|
||||
|
||||
return next({
|
||||
ctx: { locale, i18n, user: { ...user, locale } },
|
||||
});
|
||||
});
|
||||
|
||||
export default localeMiddleware;
|
||||
@@ -0,0 +1,11 @@
|
||||
import { middleware } from "../trpc";
|
||||
|
||||
const perfMiddleware = middleware(async ({ path, type, next }) => {
|
||||
performance.mark("Start");
|
||||
const result = await next();
|
||||
performance.mark("End");
|
||||
performance.measure(`[${result.ok ? "OK" : "ERROR"}][$1] ${type} '${path}'`, "Start", "End");
|
||||
return result;
|
||||
});
|
||||
|
||||
export default perfMiddleware;
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { Session } from "next-auth";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { defaultAvatarSrc } from "@calcom/lib/defaultAvatarImage";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import type { Maybe } from "@trpc/server";
|
||||
|
||||
import type { TRPCContextInner } from "../createContext";
|
||||
import { middleware } from "../trpc";
|
||||
|
||||
export async function getUserFromSession(ctx: TRPCContextInner, session: Maybe<Session>) {
|
||||
const { prisma } = ctx;
|
||||
if (!session?.user?.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
bio: true,
|
||||
timeZone: true,
|
||||
weekStart: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
defaultScheduleId: true,
|
||||
bufferTime: true,
|
||||
theme: true,
|
||||
createdDate: true,
|
||||
hideBranding: true,
|
||||
avatar: true,
|
||||
twoFactorEnabled: true,
|
||||
disableImpersonation: true,
|
||||
identityProvider: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
away: true,
|
||||
credentials: {
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
key: true,
|
||||
userId: true,
|
||||
appId: true,
|
||||
invalid: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
},
|
||||
selectedCalendars: {
|
||||
select: {
|
||||
externalId: true,
|
||||
integration: true,
|
||||
},
|
||||
},
|
||||
completedOnboarding: true,
|
||||
destinationCalendar: true,
|
||||
locale: true,
|
||||
timeFormat: true,
|
||||
trialEndsAt: true,
|
||||
metadata: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
// some hacks to make sure `username` and `email` are never inferred as `null`
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { email, username, id } = user;
|
||||
if (!email || !id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rawAvatar = user.avatar;
|
||||
// This helps to prevent reaching the 4MB payload limit by avoiding base64 and instead passing the avatar url
|
||||
user.avatar = rawAvatar ? `${WEBAPP_URL}/${user.username}/avatar.png` : defaultAvatarSrc({ email });
|
||||
const locale = user?.locale || ctx.locale;
|
||||
return {
|
||||
...user,
|
||||
id,
|
||||
rawAvatar,
|
||||
email,
|
||||
username,
|
||||
locale,
|
||||
};
|
||||
}
|
||||
|
||||
export type UserFromSession = Awaited<ReturnType<typeof getUserFromSession>>;
|
||||
|
||||
const getUserSession = async (ctx: TRPCContextInner) => {
|
||||
const { getServerSession } = await import("@calcom/features/auth/lib/getServerSession");
|
||||
const { req, res } = ctx;
|
||||
|
||||
const session = req ? await getServerSession({ req, res }) : null;
|
||||
const user = session ? await getUserFromSession(ctx, session) : null;
|
||||
|
||||
return { user, session };
|
||||
};
|
||||
const sessionMiddleware = middleware(async ({ ctx, next }) => {
|
||||
const { user, session } = await getUserSession(ctx);
|
||||
|
||||
return next({
|
||||
ctx: { user, session },
|
||||
});
|
||||
});
|
||||
|
||||
export const isAuthed = middleware(async ({ ctx, next }) => {
|
||||
const { user, session } = await getUserSession(ctx);
|
||||
|
||||
if (!user || !session) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
return next({
|
||||
ctx: { ...ctx, user, session },
|
||||
});
|
||||
});
|
||||
|
||||
export const isAdminMiddleware = isAuthed.unstable_pipe(({ ctx, next }) => {
|
||||
const { user } = ctx;
|
||||
if (user?.role !== "ADMIN") {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return next({ ctx: { ...ctx, user: user } });
|
||||
});
|
||||
|
||||
export default sessionMiddleware;
|
||||
@@ -0,0 +1,31 @@
|
||||
import perfMiddleware from "../middlewares/perfMiddleware";
|
||||
import { isAdminMiddleware, isAuthed } from "../middlewares/sessionMiddleware";
|
||||
import { procedure } from "../trpc";
|
||||
import publicProcedure from "./publicProcedure";
|
||||
|
||||
/*interface IRateLimitOptions {
|
||||
intervalInMs: number;
|
||||
limit: number;
|
||||
}
|
||||
const isRateLimitedByUserIdMiddleware = ({ intervalInMs, limit }: IRateLimitOptions) =>
|
||||
middleware(({ ctx, next }) => {
|
||||
// validate user exists
|
||||
if (!ctx.user) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
const { isRateLimited } = rateLimit({ intervalInMs }).check(limit, ctx.user.id.toString());
|
||||
|
||||
if (isRateLimited) {
|
||||
throw new TRPCError({ code: "TOO_MANY_REQUESTS" });
|
||||
}
|
||||
|
||||
return next({ ctx: { user: ctx.user, session: ctx.session } });
|
||||
});
|
||||
*/
|
||||
const authedProcedure = procedure.use(perfMiddleware).use(isAuthed);
|
||||
/*export const authedRateLimitedProcedure = ({ intervalInMs, limit }: IRateLimitOptions) =>
|
||||
authedProcedure.use(isRateLimitedByUserIdMiddleware({ intervalInMs, limit }));*/
|
||||
export const authedAdminProcedure = publicProcedure.use(isAdminMiddleware);
|
||||
|
||||
export default authedProcedure;
|
||||
@@ -0,0 +1,6 @@
|
||||
import perfMiddleware from "../middlewares/perfMiddleware";
|
||||
import { tRPCContext } from "../trpc";
|
||||
|
||||
const publicProcedure = tRPCContext.procedure.use(perfMiddleware);
|
||||
|
||||
export default publicProcedure;
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authedProcedure, router } from "../../trpc";
|
||||
import authedProcedure from "../../procedures/authedProcedure";
|
||||
import { router } from "../../trpc";
|
||||
import { ZAppByIdInputSchema } from "./appById.schema";
|
||||
import { ZAppCredentialsByTypeInputSchema } from "./appCredentialsByType.schema";
|
||||
import { ZAppsInputSchema } from "./apps.schema";
|
||||
|
||||
+2
-2
@@ -4,11 +4,11 @@ import { IS_SELF_HOSTED } from "@calcom/lib/constants";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { CreateInnerContextOptions } from "../../createContext";
|
||||
import type { WithSession } from "../../createContext";
|
||||
import type { TGetDownloadLinkOfCalVideoRecordingsInputSchema } from "./getDownloadLinkOfCalVideoRecordings.schema";
|
||||
|
||||
type GetDownloadLinkOfCalVideoRecordingsHandlerOptions = {
|
||||
ctx: CreateInnerContextOptions;
|
||||
ctx: WithSession;
|
||||
input: TGetDownloadLinkOfCalVideoRecordingsInputSchema;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { publicProcedure, router } from "../../trpc";
|
||||
import localeMiddleware from "../../middlewares/localeMiddleware";
|
||||
import sessionMiddleware from "../../middlewares/sessionMiddleware";
|
||||
import publicProcedure from "../../procedures/publicProcedure";
|
||||
import { router } from "../../trpc";
|
||||
import { slotsRouter } from "../viewer/slots/_router";
|
||||
import { ZEventInputSchema } from "./event.schema";
|
||||
import { ZSamlTenantProductInputSchema } from "./samlTenantProduct.schema";
|
||||
@@ -18,7 +21,7 @@ const UNSTABLE_HANDLER_CACHE: PublicViewerRouterHandlerCache = {};
|
||||
|
||||
// things that unauthenticated users can query about themselves
|
||||
export const publicViewerRouter = router({
|
||||
session: publicProcedure.query(async ({ ctx }) => {
|
||||
session: publicProcedure.use(sessionMiddleware).query(async ({ ctx }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.session) {
|
||||
UNSTABLE_HANDLER_CACHE.session = await import("./session.handler").then((mod) => mod.sessionHandler);
|
||||
}
|
||||
@@ -33,7 +36,7 @@ export const publicViewerRouter = router({
|
||||
});
|
||||
}),
|
||||
|
||||
i18n: publicProcedure.query(async ({ ctx }) => {
|
||||
i18n: publicProcedure.use(localeMiddleware).query(async ({ ctx }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.i18n) {
|
||||
UNSTABLE_HANDLER_CACHE.i18n = await import("./i18n.handler").then((mod) => mod.i18nHandler);
|
||||
}
|
||||
@@ -43,9 +46,7 @@ export const publicViewerRouter = router({
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.i18n({
|
||||
ctx,
|
||||
});
|
||||
return UNSTABLE_HANDLER_CACHE.i18n({ ctx });
|
||||
}),
|
||||
|
||||
countryCode: publicProcedure.query(async ({ ctx }) => {
|
||||
@@ -83,27 +84,24 @@ export const publicViewerRouter = router({
|
||||
});
|
||||
}),
|
||||
|
||||
stripeCheckoutSession: publicProcedure
|
||||
.input(ZStripeCheckoutSessionInputSchema)
|
||||
.query(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.stripeCheckoutSession) {
|
||||
UNSTABLE_HANDLER_CACHE.stripeCheckoutSession = await import("./stripeCheckoutSession.handler").then(
|
||||
(mod) => mod.stripeCheckoutSessionHandler
|
||||
);
|
||||
}
|
||||
stripeCheckoutSession: publicProcedure.input(ZStripeCheckoutSessionInputSchema).query(async ({ input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.stripeCheckoutSession) {
|
||||
UNSTABLE_HANDLER_CACHE.stripeCheckoutSession = await import("./stripeCheckoutSession.handler").then(
|
||||
(mod) => mod.stripeCheckoutSessionHandler
|
||||
);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.stripeCheckoutSession) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.stripeCheckoutSession) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.stripeCheckoutSession({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
return UNSTABLE_HANDLER_CACHE.stripeCheckoutSession({
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
cityTimezones: publicProcedure.query(async ({ ctx }) => {
|
||||
cityTimezones: publicProcedure.query(async () => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.cityTimezones) {
|
||||
UNSTABLE_HANDLER_CACHE.cityTimezones = await import("./cityTimezones.handler").then(
|
||||
(mod) => mod.cityTimezonesHandler
|
||||
@@ -115,9 +113,7 @@ export const publicViewerRouter = router({
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.cityTimezones({
|
||||
ctx,
|
||||
});
|
||||
return UNSTABLE_HANDLER_CACHE.cityTimezones();
|
||||
}),
|
||||
|
||||
// REVIEW: This router is part of both the public and private viewer router?
|
||||
|
||||
@@ -1,12 +1,4 @@
|
||||
import type { Session } from "next-auth";
|
||||
|
||||
type CityTimezonesOptions = {
|
||||
ctx: {
|
||||
session: Session | null;
|
||||
};
|
||||
};
|
||||
|
||||
export const cityTimezonesHandler = async ({ ctx: _ctx }: CityTimezonesOptions) => {
|
||||
export const cityTimezonesHandler = async () => {
|
||||
/**
|
||||
* Lazy loads third party dependency to avoid loading 1.5Mb for ALL tRPC procedures.
|
||||
* Thanks @roae for the tip 🙏
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import type { CreateInnerContextOptions } from "../../createContext";
|
||||
import { getLocale } from "../../trpc";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import type { WithLocale } from "../../createContext";
|
||||
|
||||
type I18nOptions = {
|
||||
ctx: CreateInnerContextOptions;
|
||||
ctx: WithLocale & {
|
||||
req: NextApiRequest | undefined;
|
||||
res: NextApiResponse | undefined;
|
||||
};
|
||||
};
|
||||
|
||||
export const i18nHandler = async ({ ctx }: I18nOptions) => {
|
||||
const { locale, i18n } = await getLocale(ctx);
|
||||
const { locale, i18n } = ctx;
|
||||
|
||||
return {
|
||||
i18n,
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import type { Session } from "next-auth";
|
||||
import type { PrismaClient } from "@prisma/client";
|
||||
|
||||
import { samlTenantProduct } from "@calcom/features/ee/sso/lib/saml";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
import type { TSamlTenantProductInputSchema } from "./samlTenantProduct.schema";
|
||||
|
||||
type SamlTenantProductOptions = {
|
||||
ctx: {
|
||||
session: Session | null;
|
||||
prisma: PrismaClient;
|
||||
};
|
||||
input: TSamlTenantProductInputSchema;
|
||||
};
|
||||
|
||||
export const samlTenantProductHandler = async ({ ctx: _ctx, input }: SamlTenantProductOptions) => {
|
||||
export const samlTenantProductHandler = ({ ctx, input }: SamlTenantProductOptions) => {
|
||||
const { prisma } = ctx;
|
||||
const { email } = input;
|
||||
|
||||
return await samlTenantProduct(prisma, email);
|
||||
return samlTenantProduct(prisma, email);
|
||||
};
|
||||
@@ -1,13 +1,8 @@
|
||||
import type { Session } from "next-auth";
|
||||
|
||||
import stripe from "@calcom/app-store/stripepayment/lib/server";
|
||||
|
||||
import type { TStripeCheckoutSessionInputSchema } from "./stripeCheckoutSession.schema";
|
||||
|
||||
type StripeCheckoutSessionOptions = {
|
||||
ctx: {
|
||||
session: Session | null;
|
||||
};
|
||||
input: TStripeCheckoutSessionInputSchema;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authedProcedure, router } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZCreateInputSchema } from "./create.schema";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
import { ZEditInputSchema } from "./edit.schema";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authedAdminProcedure, authedProcedure, router } from "../../../trpc";
|
||||
import authedProcedure, { authedAdminProcedure } from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZListLocalInputSchema } from "./listLocal.schema";
|
||||
import { ZQueryForDependenciesInputSchema } from "./queryForDependencies.schema";
|
||||
import { ZSaveKeysInputSchema } from "./saveKeys.schema";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { router, authedProcedure } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZChangePasswordInputSchema } from "./changePassword.schema";
|
||||
import { ZVerifyPasswordInputSchema } from "./verifyPassword.schema";
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authedProcedure, router } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { scheduleRouter } from "./schedule/_router";
|
||||
import { ZUserInputSchema } from "./user.schema";
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authedProcedure, router } from "../../../../trpc";
|
||||
import authedProcedure from "../../../../procedures/authedProcedure";
|
||||
import { router } from "../../../../trpc";
|
||||
import { ZCreateInputSchema } from "./create.schema";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
import { ZGetInputSchema } from "./get.schema";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authedProcedure, router } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZConfirmInputSchema } from "./confirm.schema";
|
||||
import { ZEditLocationInputSchema } from "./editLocation.schema";
|
||||
import { ZGetInputSchema } from "./get.schema";
|
||||
|
||||
@@ -9,6 +9,7 @@ import { getTranslation } from "@calcom/lib/server";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { BookingStatus, MembershipRole, SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
import type { IAbstractPaymentService } from "@calcom/types/PaymentService";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
@@ -274,14 +275,15 @@ export const confirmHandler = async ({ ctx, input }: ConfirmOptions) => {
|
||||
}
|
||||
|
||||
// Posible to refactor TODO:
|
||||
const paymentApp = await appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore];
|
||||
const paymentApp = await appStore[paymentAppCredential?.app?.dirName as keyof typeof appStore]();
|
||||
if (!(paymentApp && "lib" in paymentApp && "PaymentService" in paymentApp.lib)) {
|
||||
console.warn(`payment App service of type ${paymentApp} is not implemented`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const PaymentService = paymentApp.lib.PaymentService;
|
||||
const paymentInstance = new PaymentService(paymentAppCredential);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const PaymentService = paymentApp.lib.PaymentService as any;
|
||||
const paymentInstance = new PaymentService(paymentAppCredential) as IAbstractPaymentService;
|
||||
const paymentData = await paymentInstance.refund(successPayment.id);
|
||||
if (!paymentData.refunded) {
|
||||
throw new Error("Payment could not be refunded");
|
||||
|
||||
@@ -13,7 +13,7 @@ import { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { authedProcedure } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { commonBookingSchema } from "./types";
|
||||
|
||||
export const bookingsProcedure = authedProcedure
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { router, authedAdminProcedure } from "../../../trpc";
|
||||
import { authedAdminProcedure } from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZUpdateInputSchema } from "./update.schema";
|
||||
|
||||
type DeploymentSetupRouterHandlerCache = {
|
||||
|
||||
@@ -2,7 +2,8 @@ import { z } from "zod";
|
||||
|
||||
import { logP } from "@calcom/lib/perf";
|
||||
|
||||
import { authedProcedure, router } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZCreateInputSchema } from "./create.schema";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
import { ZDuplicateInputSchema } from "./duplicate.schema";
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { CustomInputSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { authedProcedure } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import type { EventTypeUpdateInput } from "./types";
|
||||
|
||||
export const eventOwnerProcedure = authedProcedure
|
||||
|
||||
@@ -8,7 +8,8 @@ import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
import authedProcedure from "../../procedures/authedProcedure";
|
||||
import { router } from "../../trpc";
|
||||
|
||||
export const paymentsRouter = router({
|
||||
chargeCard: authedProcedure
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { router, authedProcedure } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZChargerCardInputSchema } from "./chargeCard.schema";
|
||||
|
||||
interface PaymentsRouterHandlerCache {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { sendNoShowFeeChargedEmail } from "@calcom/emails";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import type { PrismaClient } from "@calcom/prisma/client";
|
||||
import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
import type { IAbstractPaymentService } from "@calcom/types/PaymentService";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
@@ -93,14 +94,14 @@ export const chargeCardHandler = async ({ ctx, input }: ChargeCardHandlerOptions
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Invalid payment credential" });
|
||||
}
|
||||
|
||||
const paymentApp = await appStore[paymentCredential?.app?.dirName as keyof typeof appStore];
|
||||
const paymentApp = await appStore[paymentCredential?.app?.dirName as keyof typeof appStore]();
|
||||
|
||||
if (!("lib" in paymentApp && "PaymentService" in paymentApp.lib)) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Payment service not found" });
|
||||
}
|
||||
|
||||
const PaymentService = paymentApp.lib.PaymentService;
|
||||
const paymentInstance = new PaymentService(paymentCredential);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const PaymentService = paymentApp.lib.PaymentService as any;
|
||||
const paymentInstance = new PaymentService(paymentCredential) as IAbstractPaymentService;
|
||||
|
||||
try {
|
||||
const paymentData = await paymentInstance.chargeCard(booking.payment[0]);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { router, publicProcedure } from "../../../trpc";
|
||||
import publicProcedure from "../../../procedures/publicProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZGetScheduleInputSchema } from "./getSchedule.schema";
|
||||
import { ZReserveSlotInputSchema } from "./reserveSlot.schema";
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { router, authedProcedure } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
import { ZGetInputSchema } from "./get.schema";
|
||||
import { ZUpdateInputSchema } from "./update.schema";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authedProcedure, router } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZAcceptOrLeaveInputSchema } from "./acceptOrLeave.schema";
|
||||
import { ZChangeMemberRoleInputSchema } from "./changeMemberRole.schema";
|
||||
import { ZCreateInputSchema } from "./create.schema";
|
||||
|
||||
@@ -2,7 +2,7 @@ import { prisma } from "@calcom/prisma";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { authedProcedure } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { webhookIdAndEventTypeIdSchema } from "./types";
|
||||
|
||||
export const webhookProcedure = authedProcedure
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authedProcedure, router } from "../../../trpc";
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { router } from "../../../trpc";
|
||||
import { ZActivateEventTypeInputSchema } from "./activateEventType.schema";
|
||||
import { ZCreateInputSchema } from "./create.schema";
|
||||
import { ZDeleteInputSchema } from "./delete.schema";
|
||||
|
||||
@@ -1,176 +1,17 @@
|
||||
import type { Session } from "next-auth";
|
||||
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
|
||||
import superjson from "superjson";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { defaultAvatarSrc } from "@calcom/lib/defaultAvatarImage";
|
||||
import rateLimit from "@calcom/lib/rateLimit";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { initTRPC } from "@trpc/server";
|
||||
|
||||
import type { Maybe } from "@trpc/server";
|
||||
import { initTRPC, TRPCError } from "@trpc/server";
|
||||
import type { createContextInner } from "./createContext";
|
||||
import type { UserFromSession } from "./middlewares/sessionMiddleware";
|
||||
|
||||
import type { createContextInner, CreateInnerContextOptions } from "./createContext";
|
||||
|
||||
async function getUserFromSession({ session }: { session: Maybe<Session> }) {
|
||||
if (!session?.user?.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session.user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
bio: true,
|
||||
timeZone: true,
|
||||
weekStart: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
defaultScheduleId: true,
|
||||
bufferTime: true,
|
||||
theme: true,
|
||||
createdDate: true,
|
||||
hideBranding: true,
|
||||
avatar: true,
|
||||
twoFactorEnabled: true,
|
||||
disableImpersonation: true,
|
||||
identityProvider: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
away: true,
|
||||
credentials: {
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
key: true,
|
||||
userId: true,
|
||||
appId: true,
|
||||
invalid: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
},
|
||||
selectedCalendars: {
|
||||
select: {
|
||||
externalId: true,
|
||||
integration: true,
|
||||
},
|
||||
},
|
||||
completedOnboarding: true,
|
||||
destinationCalendar: true,
|
||||
locale: true,
|
||||
timeFormat: true,
|
||||
trialEndsAt: true,
|
||||
metadata: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
// some hacks to make sure `username` and `email` are never inferred as `null`
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
const { email, username } = user;
|
||||
if (!email) {
|
||||
return null;
|
||||
}
|
||||
const rawAvatar = user.avatar;
|
||||
// This helps to prevent reaching the 4MB payload limit by avoiding base64 and instead passing the avatar url
|
||||
user.avatar = rawAvatar ? `${WEBAPP_URL}/${user.username}/avatar.png` : defaultAvatarSrc({ email });
|
||||
|
||||
return {
|
||||
...user,
|
||||
rawAvatar,
|
||||
email,
|
||||
username,
|
||||
};
|
||||
}
|
||||
|
||||
export type TrpcSessionUser = Awaited<ReturnType<typeof getUserFromSession>>;
|
||||
|
||||
const t = initTRPC.context<typeof createContextInner>().create({
|
||||
export const tRPCContext = initTRPC.context<typeof createContextInner>().create({
|
||||
transformer: superjson,
|
||||
});
|
||||
|
||||
const perfMiddleware = t.middleware(async ({ path, type, next }) => {
|
||||
performance.mark("Start");
|
||||
const start = performance.now();
|
||||
const result = await next();
|
||||
const end = performance.now();
|
||||
performance.mark("End");
|
||||
performance.measure(`[${result.ok ? "OK" : "ERROR"}][$1] ${type} '${path}'`, "Start", "End");
|
||||
console.log(`[${result.ok ? "OK" : "ERROR"}][${end - start}ms] ${type} '${path}'`);
|
||||
return result;
|
||||
});
|
||||
export const router = tRPCContext.router;
|
||||
export const mergeRouters = tRPCContext.mergeRouters;
|
||||
export const middleware = tRPCContext.middleware;
|
||||
export const procedure = tRPCContext.procedure;
|
||||
|
||||
export const getLocale = async (ctx: CreateInnerContextOptions) => {
|
||||
const user = await getUserFromSession({ session: ctx.session });
|
||||
|
||||
const i18n =
|
||||
user?.locale && user?.locale !== ctx.locale
|
||||
? await serverSideTranslations(user.locale, ["common", "vital"])
|
||||
: ctx.i18n;
|
||||
const locale = user?.locale || ctx.locale;
|
||||
return { user, i18n, session: ctx.session, locale };
|
||||
};
|
||||
|
||||
export const isAuthed = t.middleware(async ({ ctx, next }) => {
|
||||
const { user, session, locale, i18n } = await getLocale(ctx);
|
||||
if (!user || !session) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
return next({
|
||||
ctx: { locale, i18n, user: { ...user, locale }, session },
|
||||
});
|
||||
});
|
||||
|
||||
const isAdminMiddleware = isAuthed.unstable_pipe(({ ctx, next }) => {
|
||||
if (ctx.user.role !== "ADMIN") {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return next({
|
||||
ctx: { user: ctx.user },
|
||||
});
|
||||
});
|
||||
|
||||
interface IRateLimitOptions {
|
||||
intervalInMs: number;
|
||||
limit: number;
|
||||
}
|
||||
const isRateLimitedByUserIdMiddleware = ({ intervalInMs, limit }: IRateLimitOptions) =>
|
||||
t.middleware(({ ctx, next }) => {
|
||||
// validate user exists
|
||||
if (!ctx.user) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
const { isRateLimited } = rateLimit({ intervalInMs }).check(limit, ctx.user.id.toString());
|
||||
|
||||
if (isRateLimited) {
|
||||
throw new TRPCError({ code: "TOO_MANY_REQUESTS" });
|
||||
}
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
// infers that `user` and `session` are non-nullable to downstream procedures
|
||||
session: ctx.session,
|
||||
user: ctx.user,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const router = t.router;
|
||||
export const mergeRouters = t.mergeRouters;
|
||||
export const middleware = t.middleware;
|
||||
export const publicProcedure = t.procedure.use(perfMiddleware);
|
||||
export const authedProcedure = t.procedure.use(perfMiddleware).use(isAuthed);
|
||||
export const authedRateLimitedProcedure = ({ intervalInMs, limit }: IRateLimitOptions) =>
|
||||
authedProcedure.use(isRateLimitedByUserIdMiddleware({ intervalInMs, limit }));
|
||||
export const authedAdminProcedure = t.procedure.use(perfMiddleware).use(isAdminMiddleware);
|
||||
export type TrpcSessionUser = UserFromSession;
|
||||
Reference in new issue
Block a user