## What does this PR do? Similar to #25721, adds uuid in session so that BookingAudit has it readily available Adds the user's UUID to the booking metadata by: 1. Extending the NextAuth `User` interface to include an optional `uuid` property from PrismaUser 2. Making `uuid` required on `Session.user` via intersection type (`User & { uuid: PrismaUser["uuid"] }`) 3. Adding `uuid` to the session user object in `getServerSession.ts` 4. Adding `uuid` to the `AdapterUser` transformation in `next-auth-custom-adapter.ts` 5. Passing `userUuid` from the session to the booking creation flow 6. Updating the API key verification flow to include `uuid` in the user data (repository, service, and type definitions) 7. Adding `req.userUuid` as a required field on the request object (like `req.userId`) 8. Adding `uuid` to mock session objects in web app routes and test context 9. Adding `uuid` to the `findByEmailAndIncludeProfilesAndPassword` query in UserRepository Also removes commented-out code that was placeholder for future work and fixes lint warnings for unused variables. ## Mandatory Tasks (DO NOT REMOVE) - [x] I have self-reviewed the code (A decent size PR without self-review might be rejected). - [x] I have updated the developer docs in /docs if this PR makes changes that would require a [documentation change](https://cal.com/docs). N/A - no documentation changes needed. - [x] I confirm automated tests are in place that prove my fix is effective or that my feature works. ## How should this be tested? 1. Verify that the NextAuth session callback is already populating the `uuid` field on the user object 2. Create a booking and confirm `userUuid` is included in the booking metadata 3. Test API v1 endpoints (`/api/invites` POST and `/api/teams/[teamId]/publish`) to verify they receive the uuid from the authenticated user 4. Check that the booking flow works correctly with the new parameter 5. Test SAML login flow to verify session still works correctly (uuid is resolved from database after authentication) ## Human Review Checklist - [ ] Verify the NextAuth session callback populates `uuid` - if not, this change will pass `undefined` at runtime - [ ] Confirm `userUuid` is consumed downstream in the booking service - [ ] Verify that `PrismaApiKeyRepository.findByHashedKey()` correctly fetches the user's uuid from the database - [ ] Verify the discriminated union type in `ApiKeyService.ts` ensures `result.user` is always defined when `result.valid` is true - [ ] Confirm all API v1 endpoints using `req.userUuid` go through the `verifyApiKey` middleware - [ ] Verify `UserRepository.findByEmailAndIncludeProfilesAndPassword()` includes `uuid` in the select clause - [ ] Verify SAML login still works correctly - uuid is now optional on User interface so SAML providers don't need to supply it at profile stage ## Updates since last revision - **Made uuid optional on User, required on Session**: Changed the type strategy so `uuid` is optional on the NextAuth `User` interface but required on `Session.user` via intersection type. This allows SAML providers to not supply uuid at the profile stage while ensuring uuid is always present on the session after the user is resolved from the database. - **Removed uuid from SAML functions**: Since uuid is now optional on User, the SAML profile and authorize functions no longer need to include it. --- Link to Devin run: https://app.devin.ai/sessions/97e5603b719a420b9b35041252c9db26 Requested by: hariom@cal.com (@hariombalhara)
161 lines
5.0 KiB
TypeScript
161 lines
5.0 KiB
TypeScript
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
|
|
import { parseRequestData } from "app/api/parseRequestData";
|
|
import { headers, cookies } from "next/headers";
|
|
import type { NextRequest } from "next/server";
|
|
import { NextResponse } from "next/server";
|
|
import { z } from "zod";
|
|
|
|
import prisma from "@calcom/prisma";
|
|
import { UserPermissionRole } from "@calcom/prisma/enums";
|
|
import { createContext } from "@calcom/trpc/server/createContext";
|
|
import { bookingsRouter } from "@calcom/trpc/server/routers/viewer/bookings/_router";
|
|
import { createCallerFactory } from "@calcom/trpc/server/trpc";
|
|
import type { UserProfile } from "@calcom/types/UserProfile";
|
|
|
|
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
|
|
|
|
import { TRPCError } from "@trpc/server";
|
|
|
|
enum DirectAction {
|
|
ACCEPT = "accept",
|
|
REJECT = "reject",
|
|
}
|
|
|
|
const querySchema = z.object({
|
|
action: z.nativeEnum(DirectAction),
|
|
token: z.string(),
|
|
bookingUid: z.string(),
|
|
userId: z.string(),
|
|
});
|
|
|
|
async function getHandler(request: NextRequest) {
|
|
const queryParams = Object.fromEntries(request.nextUrl.searchParams.entries());
|
|
|
|
try {
|
|
const { action, token, bookingUid, userId } = querySchema.parse(queryParams);
|
|
|
|
if (action === DirectAction.REJECT) {
|
|
// Rejections should use POST method
|
|
return NextResponse.redirect(
|
|
new URL(`/booking/${bookingUid}?error=${encodeURIComponent("Rejection requires POST method")}`, request.url)
|
|
);
|
|
}
|
|
|
|
return await handleBookingAction(action, token, bookingUid, userId, request, undefined);
|
|
} catch {
|
|
const bookingUid = queryParams.bookingUid || "";
|
|
return NextResponse.redirect(
|
|
new URL(`/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`, request.url)
|
|
);
|
|
}
|
|
}
|
|
|
|
async function postHandler(request: NextRequest) {
|
|
const queryParams = Object.fromEntries(request.nextUrl.searchParams.entries());
|
|
|
|
try {
|
|
const { action, token, bookingUid, userId } = querySchema.parse(queryParams);
|
|
const body = await parseRequestData(request).catch(() => ({}));
|
|
const { reason } = z.object({ reason: z.string().optional() }).parse(body || {});
|
|
|
|
return await handleBookingAction(action, token, bookingUid, userId, request, reason);
|
|
} catch {
|
|
const bookingUid = queryParams.bookingUid || "";
|
|
return NextResponse.redirect(
|
|
new URL(`/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`, request.url),
|
|
{ status: 303 }
|
|
);
|
|
}
|
|
}
|
|
|
|
async function handleBookingAction(
|
|
action: DirectAction,
|
|
token: string,
|
|
bookingUid: string,
|
|
userId: string,
|
|
request: NextRequest,
|
|
reason?: string
|
|
) {
|
|
const booking = await prisma.booking.findUnique({
|
|
where: { oneTimePassword: token },
|
|
});
|
|
|
|
if (!booking) {
|
|
return NextResponse.redirect(
|
|
new URL(`/booking/${bookingUid}?error=${encodeURIComponent("Error confirming booking")}`, request.url),
|
|
{ status: 303 }
|
|
);
|
|
}
|
|
|
|
const user = await prisma.user.findUniqueOrThrow({
|
|
where: { id: Number(userId) },
|
|
});
|
|
|
|
/** We shape the session as required by tRPC router */
|
|
async function sessionGetter() {
|
|
return {
|
|
user: {
|
|
id: Number(userId),
|
|
uuid: user.uuid,
|
|
username: "" /* Not used in this context */,
|
|
role: UserPermissionRole.USER,
|
|
/* Not used in this context */
|
|
profile: {
|
|
id: null,
|
|
organizationId: null,
|
|
organization: null,
|
|
username: "",
|
|
upId: "",
|
|
} satisfies UserProfile,
|
|
},
|
|
upId: "",
|
|
hasValidLicense: true,
|
|
expires: "" /* Not used in this context */,
|
|
};
|
|
}
|
|
|
|
try {
|
|
/** @see https://trpc.io/docs/server-side-calls */
|
|
const createCaller = createCallerFactory(bookingsRouter);
|
|
|
|
// Use buildLegacyRequest to create a request object compatible with Pages Router
|
|
|
|
const legacyReq = request ? buildLegacyRequest(await headers(), await cookies()) : ({} as any);
|
|
|
|
const res = {} as any;
|
|
|
|
const ctx = await createContext({ req: legacyReq, res }, sessionGetter);
|
|
const caller = createCaller({
|
|
...ctx,
|
|
req: legacyReq,
|
|
res,
|
|
user: { ...user, locale: user?.locale ?? "en" },
|
|
});
|
|
|
|
await caller.confirm({
|
|
bookingId: booking.id,
|
|
recurringEventId: booking.recurringEventId || undefined,
|
|
confirmed: action === DirectAction.ACCEPT,
|
|
/** Ignored reason input unless we're rejecting */
|
|
reason: action === DirectAction.REJECT ? reason : undefined,
|
|
});
|
|
} catch (e) {
|
|
let message = "Error confirming booking";
|
|
if (e instanceof TRPCError) message = (e as TRPCError).message;
|
|
return NextResponse.redirect(
|
|
new URL(`/booking/${booking.uid}?error=${encodeURIComponent(message)}`, request.url),
|
|
{ status: 303 }
|
|
);
|
|
}
|
|
|
|
await prisma.booking.update({
|
|
where: { id: booking.id },
|
|
data: { oneTimePassword: null },
|
|
});
|
|
|
|
return NextResponse.redirect(new URL(`/booking/${booking.uid}`, request.url), { status: 303 });
|
|
}
|
|
|
|
export const GET = defaultResponderForAppDir(getHandler);
|
|
export const POST = defaultResponderForAppDir(postHandler);
|