cal.pub0.org/packages/trpc/server/middlewares/sessionMiddleware.ts

142 lines
3.6 KiB
TypeScript
Raw Normal View History

import type { Session } from "next-auth";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { defaultAvatarSrc } from "@calcom/lib/defaultAvatarImage";
feat: event settings booker layout toggle (#9082) * WIP for adding booker layout toggle in event settings pages * Prevent form error from getting form stuck in loading state * Fixed types for bookerlayouts settings and preselect correct layout in booker * Added defaultlayout settings to profile too, and use that in booker plus as default for events. * Made layout settings responsive * Added feature toggle for new layout settings * Fixed user builder for tests by adding defaultlyotu * Show toggles on booker for layout switch based on selected layouts. Also added a small fix for the settings toggles to preselect the correct toggle for defaultlayout when user profile settings are used. * Used zod parse to fix type errors. * Fix unit test * Set selected date to today in datepicker when week or column view is default layout. It uses that date to show in the title bar. * Moved booker layout settings to event and user meta data instead of new db column. * Converted booker layout strings into an enum. * Renamed booker layouts feature flag and deleted unused v2 booker feature flag. * Update packages/trpc/server/routers/viewer/eventTypes/update.handler.ts Co-authored-by: Omar López <zomars@me.com> * Fix import * Fix lint warnings in EventTypeSingleLayout * Fixed bug where when selected date was passed via query param page booking form wouldn't automatically show up. It would still serve you the date selection. This should fix e2e tests. * Fixed layout header. * Enabled booking layout toggle feature flag. --------- Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Alex van Andel <me@alexvanandel.com>
2023-06-06 15:31:43 +00:00
import { userMetadata } from "@calcom/prisma/zod-utils";
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,
emailVerified: 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,
allowDynamicBooking: 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;
}
feat: event settings booker layout toggle (#9082) * WIP for adding booker layout toggle in event settings pages * Prevent form error from getting form stuck in loading state * Fixed types for bookerlayouts settings and preselect correct layout in booker * Added defaultlayout settings to profile too, and use that in booker plus as default for events. * Made layout settings responsive * Added feature toggle for new layout settings * Fixed user builder for tests by adding defaultlyotu * Show toggles on booker for layout switch based on selected layouts. Also added a small fix for the settings toggles to preselect the correct toggle for defaultlayout when user profile settings are used. * Used zod parse to fix type errors. * Fix unit test * Set selected date to today in datepicker when week or column view is default layout. It uses that date to show in the title bar. * Moved booker layout settings to event and user meta data instead of new db column. * Converted booker layout strings into an enum. * Renamed booker layouts feature flag and deleted unused v2 booker feature flag. * Update packages/trpc/server/routers/viewer/eventTypes/update.handler.ts Co-authored-by: Omar López <zomars@me.com> * Fix import * Fix lint warnings in EventTypeSingleLayout * Fixed bug where when selected date was passed via query param page booking form wouldn't automatically show up. It would still serve you the date selection. This should fix e2e tests. * Fixed layout header. * Enabled booking layout toggle feature flag. --------- Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Alex van Andel <me@alexvanandel.com>
2023-06-06 15:31:43 +00:00
const userMetaData = userMetadata.parse(user.metadata || {});
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,
feat: event settings booker layout toggle (#9082) * WIP for adding booker layout toggle in event settings pages * Prevent form error from getting form stuck in loading state * Fixed types for bookerlayouts settings and preselect correct layout in booker * Added defaultlayout settings to profile too, and use that in booker plus as default for events. * Made layout settings responsive * Added feature toggle for new layout settings * Fixed user builder for tests by adding defaultlyotu * Show toggles on booker for layout switch based on selected layouts. Also added a small fix for the settings toggles to preselect the correct toggle for defaultlayout when user profile settings are used. * Used zod parse to fix type errors. * Fix unit test * Set selected date to today in datepicker when week or column view is default layout. It uses that date to show in the title bar. * Moved booker layout settings to event and user meta data instead of new db column. * Converted booker layout strings into an enum. * Renamed booker layouts feature flag and deleted unused v2 booker feature flag. * Update packages/trpc/server/routers/viewer/eventTypes/update.handler.ts Co-authored-by: Omar López <zomars@me.com> * Fix import * Fix lint warnings in EventTypeSingleLayout * Fixed bug where when selected date was passed via query param page booking form wouldn't automatically show up. It would still serve you the date selection. This should fix e2e tests. * Fixed layout header. * Enabled booking layout toggle feature flag. --------- Co-authored-by: Peer Richelsen <peeroke@gmail.com> Co-authored-by: Omar López <zomars@me.com> Co-authored-by: Alex van Andel <me@alexvanandel.com>
2023-06-06 15:31:43 +00:00
defaultBookerLayouts: userMetaData?.defaultBookerLayouts || null,
};
}
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;