Scheduling infrastructure for absolutely everyone.
feat: enable microsoft sign ups (#28080)
Rajiv Sahale2add3f2c921
diff --git a/.env.example b/.env.exampleindex cef10a0cf09..350c86e9c17 100644--- a/.env.example+++ b/.env.example@@ -120,6 +120,10 @@ NEXT_PUBLIC_HELPSCOUT_KEY=NEXT_PUBLIC_FRESHCHAT_TOKEN=NEXT_PUBLIC_FRESHCHAT_HOST=+# Microsoft OAuth credentials+OUTLOOK_LOGIN_ENABLED=false++# For holiday feature:# Step-by-step: Get a Google Calendar API Key# 1. Go to Google Cloud Console: https://console.cloud.google.com/@@ -127,7 +131,6 @@ NEXT_PUBLIC_FRESHCHAT_HOST=# 3. Enable Google Calendar API (APIs & Services → Library , Search for Google Calendar API)# 4. Create the API Key (APIs & Services → Credentials)GOOGLE_CALENDAR_API_KEY=-# Google OAuth credentials# To enable Login with Google you need to:# 1. Set `GOOGLE_API_CREDENTIALS` belowdiff --git a/apps/web/lib/signup/getServerSideProps.tsx b/apps/web/lib/signup/getServerSideProps.tsxindex 0bb15253fa3..d2014c5ba02 100644--- a/apps/web/lib/signup/getServerSideProps.tsx+++ b/apps/web/lib/signup/getServerSideProps.tsx@@ -2,6 +2,7 @@ import type { GetServerSidePropsContext } from "next";import { z } from "zod";import { getServerSession } from "@calcom/features/auth/lib/getServerSession";+import { IS_OUTLOOK_LOGIN_ENABLED } from "@calcom/features/auth/lib/outlook";import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";import { checkPremiumUsername } from "@calcom/features/ee/common/lib/checkPremiumUsername";import { isSAMLLoginEnabled } from "@calcom/features/ee/sso/lib/saml";@@ -59,6 +60,7 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {const props = {redirectUrl,isGoogleLoginEnabled: IS_GOOGLE_LOGIN_ENABLED,+ isOutlookLoginEnabled: IS_OUTLOOK_LOGIN_ENABLED,isSAMLLoginEnabled,prepopulateFormValues: undefined,emailVerificationEnabled,diff --git a/apps/web/modules/auth/hooks/useLastUsed.tsx b/apps/web/modules/auth/hooks/useLastUsed.tsxindex 0ab3a23f0a8..93cef616eaf 100644--- a/apps/web/modules/auth/hooks/useLastUsed.tsx+++ b/apps/web/modules/auth/hooks/useLastUsed.tsx@@ -4,7 +4,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";import { localStorage } from "@calcom/lib/webstorage";import classNames from "@calcom/ui/classNames";-type LoginType = "saml" | "google" | "credentials";+type LoginType = "saml" | "google" | "microsoft" | "credentials";export function useLastUsed() {const [lastUsed, setLastUsed] = useState<LoginType>();diff --git a/apps/web/modules/auth/login-view.tsx b/apps/web/modules/auth/login-view.tsxindex 5edc63d02d5..bf7ac4fc18a 100644--- a/apps/web/modules/auth/login-view.tsx+++ b/apps/web/modules/auth/login-view.tsx@@ -1,17 +1,6 @@"use client";-import { zodResolver } from "@hookform/resolvers/zod";-import classNames from "classnames";-import { signIn } from "next-auth/react";-import Link from "next/link";-import { useRouter } from "next/navigation";-import { useEffect, useState } from "react";-import { FormProvider, useForm } from "react-hook-form";-import { z } from "zod";--import { SAMLLogin } from "@calcom/web/modules/auth/components/SAMLLogin";import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";-import { LastUsed, useLastUsed } from "@calcom/web/modules/auth/hooks/useLastUsed";import { HOSTED_CAL_FEATURES, WEBAPP_URL, WEBSITE_URL } from "@calcom/lib/constants";import { emailRegex } from "@calcom/lib/emailSchema";import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";@@ -19,17 +8,27 @@ import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";import { useLocale } from "@calcom/lib/hooks/useLocale";import { trpc } from "@calcom/trpc/react";import { Alert } from "@calcom/ui/components/alert";-import { Button } from "@calcom/ui/components/button";-import { EmailField, PasswordField } from "@calcom/ui/components/form";--import type { inferSSRProps } from "@lib/types/inferSSRProps";-+import { Icon } from "@calcom/ui/components/icon";+import { SAMLLogin } from "@calcom/web/modules/auth/components/SAMLLogin";+import { LastUsed, useLastUsed } from "@calcom/web/modules/auth/hooks/useLastUsed";import AddToHomescreen from "@components/AddToHomescreen";import BackupCode from "@components/auth/BackupCode";import TwoFactor from "@components/auth/TwoFactor";-import AuthContainer from "@components/ui/AuthContainer";-+import { Button } from "@coss/ui/components/button";+import { Field, FieldLabel } from "@coss/ui/components/field";+import { Input } from "@coss/ui/components/input";+import { InputGroup, InputGroupAddon, InputGroupInput } from "@coss/ui/components/input-group";+import { Separator } from "@coss/ui/components/separator";+import { zodResolver } from "@hookform/resolvers/zod";+import type { inferSSRProps } from "@lib/types/inferSSRProps";import type { getServerSideProps } from "@server/lib/auth/login/getServerSideProps";+import { Eye, EyeOff } from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { signIn } from "next-auth/react";+import { useEffect, useState } from "react";+import { FormProvider, useForm } from "react-hook-form";+import { z } from "zod";interface LoginValues {email: string;@@ -39,13 +38,75 @@ interface LoginValues {csrfToken: string;}+const MicrosoftIcon = () => (+ <img className="size-4" src="/microsoft-logo.svg" alt="" />+);+const GoogleIcon = () => (- <img className="mr-2 w-4 h-4 text-subtle" src="/google-icon-colored.svg" alt="Continue with Google Icon" />+ <img className="size-4" src="/google-icon-colored.svg" alt="" />);++function BackgroundGrid() {+ const rows = 9;+ const cols = 18;+ const size = 60;+ const gap = 8;+ const radius = 8;+ const width = cols * size + (cols - 1) * gap;+ const height = rows * size + (rows - 1) * gap;++ return (+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center overflow-hidden">+ <svg+ width={width}+ height={height}+ viewBox={`0 0 ${width} ${height}`}+ fill="none"+ className="[--grid-fill:#f7f7f7] [--grid-stroke:rgba(34,42,53,0.08)] dark:[--grid-fill:#1f1f1f] dark:[--grid-stroke:rgba(255,255,255,0.08)]">+ <defs>+ <radialGradient id="gridFade" cx="50%" cy="50%" rx="70%" ry="70%">+ <stop offset="20%" stopColor="white" stopOpacity="1" />+ <stop offset="100%" stopColor="white" stopOpacity="0" />+ </radialGradient>+ <mask id="gridMask">+ <rect width={width} height={height} fill="url(#gridFade)" />+ </mask>+ <filter id="gridShadow" x="-20%" y="-20%" width="140%" height="140%">+ <feDropShadow dx="0" dy="4" stdDeviation="4" floodColor="rgba(34,42,53,0.05)" />+ <feDropShadow dx="0" dy="1" stdDeviation="2" floodColor="rgba(19,19,22,0.03)" />+ </filter>+ </defs>+ <g mask="url(#gridMask)">+ {Array.from({ length: rows * cols }).map((_, i) => {+ const col = i % cols;+ const row = Math.floor(i / cols);+ const x = col * (size + gap);+ const y = row * (size + gap);+ return (+ <rect+ key={i}+ x={x}+ y={y}+ width={size}+ height={size}+ rx={radius}+ fill="var(--grid-fill)"+ stroke="var(--grid-stroke)"+ strokeWidth="1"+ filter="url(#gridShadow)"+ />+ );+ })}+ </g>+ </svg>+ </div>+ );+}export type PageProps = inferSSRProps<typeof getServerSideProps>;export default function Login({csrfToken,isGoogleLoginEnabled,+ isOutlookLoginEnabled,isSAMLLoginEnabled,samlTenantID,samlProductID,@@ -70,6 +131,7 @@ export default function Login({const [twoFactorLostAccess, setTwoFactorLostAccess] = useState(false);const [errorMessage, setErrorMessage] = useState<string | null>(null);const [lastUsed, setLastUsed] = useLastUsed();+ const [showPassword, setShowPassword] = useState(false);const errorMessages: { [key: string]: string } = {// [ErrorCode.SecondFactorRequired]: t("2fa_enabled_instructions"),@@ -93,57 +155,20 @@ export default function Login({callbackUrl = safeCallbackUrl || "";- const signupUrl = callbackUrl- ? `${WEBSITE_URL}/signup?redirect=${encodeURIComponent(callbackUrl)}`- : `${WEBSITE_URL}/signup`;-- const LoginFooter = (- <Link href={signupUrl} className="font-medium text-brand-500">- {t("dont_have_an_account")}- </Link>- );+ const { data, isPending, error } = trpc.viewer.public.ssoConnections.useQuery();- const TwoFactorFooter = (- <>- <Button- onClick={() => {- if (twoFactorLostAccess) {- setTwoFactorLostAccess(false);- methods.setValue("backupCode", "");- } else {- setTwoFactorRequired(false);- methods.setValue("totpCode", "");- }- setErrorMessage(null);- }}- StartIcon="arrow-left"- color="minimal">- {t("go_back")}- </Button>- {!twoFactorLostAccess ? (- <Button- onClick={() => {- setTwoFactorLostAccess(true);- setErrorMessage(null);- methods.setValue("totpCode", "");- }}- StartIcon="lock"- color="minimal">- {t("lost_access")}- </Button>- ) : null}- </>+ useEffect(+ function refactorMeWithoutEffect() {+ if (error) {+ setErrorMessage(error.message);+ }+ },+ [error]);- const ExternalTotpFooter = (- <Button- onClick={() => {- window.location.replace("/");- }}- color="minimal">- {t("cancel")}- </Button>- );+ const displaySSOLogin = HOSTED_CAL_FEATURES+ ? true+ : isSAMLLoginEnabled && !isPending && data?.connectionExists;const onSubmit = async (values: LoginValues) => {setErrorMessage(null);@@ -165,132 +190,232 @@ export default function Login({else setErrorMessage(errorMessages[res.error] || t("something_went_wrong"));};- const { data, isPending, error } = trpc.viewer.public.ssoConnections.useQuery();+ const showSocialLogin = isGoogleLoginEnabled || isOutlookLoginEnabled;+ const showSignupLink =+ process.env.NEXT_PUBLIC_DISABLE_SIGNUP !== "true" && searchParams?.get("register") !== "false";- useEffect(- function refactorMeWithoutEffect() {- if (error) {- setErrorMessage(error.message);- }- },- [error]- );+ return (+ <div className="relative flex min-h-screen items-center justify-center bg-default/80 px-4 py-10">+ <BackgroundGrid />- const displaySSOLogin = HOSTED_CAL_FEATURES- ? true- : isSAMLLoginEnabled && !isPending && data?.connectionExists;+ <div className="relative z-10 flex w-full max-w-md flex-col items-center">+ {/* Main Card */}+ <div className="w-full rounded-xl border border-subtle bg-default p-10 shadow-sm">+ {/* Logo */}+ <div className="mb-2 text-center">+ <h1 className="font-cal text-xl font-bold text-emphasis">Cal.com</h1>+ </div>- return (- <div className="text-emphasis min-h-screen [--cal-brand-emphasis:#101010] [--cal-brand-subtle:#9CA3AF] [--cal-brand-text:white] [--cal-brand:#111827] dark:[--cal-brand-emphasis:#e1e1e1] dark:[--cal-brand-text:black] dark:[--cal-brand:white]">- <AuthContainer- showLogo- heading={twoFactorRequired ? t("2fa_code") : t("welcome_back")}- footerText={- twoFactorRequired- ? !totpEmail- ? TwoFactorFooter- : ExternalTotpFooter- : process.env.NEXT_PUBLIC_DISABLE_SIGNUP !== "true" && searchParams?.get("register") !== "false"- ? LoginFooter- : null- }>- <FormProvider {...methods}>- {!twoFactorRequired && (- <>- <div className="stack-y-3">- {isGoogleLoginEnabled && (- <Button- color="primary"- className="justify-center w-full"- disabled={formState.isSubmitting}- data-testid="google"- CustomStartIcon={<GoogleIcon />}- onClick={async (e) => {- e.preventDefault();- setLastUsed("google");- await signIn("google", {- callbackUrl,- });- }}>- <span>{t("signin_with_google")}</span>- {lastUsed === "google" && <LastUsed />}- </Button>- )}- {displaySSOLogin && (- <SAMLLogin- disabled={formState.isSubmitting}- samlTenantID={samlTenantID}- samlProductID={samlProductID}- setErrorMessage={setErrorMessage}- />- )}- </div>- {(isGoogleLoginEnabled || displaySSOLogin) && (- <div className="my-8">- <div className="flex relative items-center">- <div className="border-t border-subtle grow" />- <span className="mx-2 text-sm font-normal leading-none text-subtle shrink">- {t("or").toLocaleLowerCase()}- </span>- <div className="border-t border-subtle grow" />- </div>+ {/* Heading */}+ <p className="mb-8 text-center text-sm text-subtle" data-testid="login-subtitle">+ {twoFactorRequired ? t("2fa_code") : t("welcome_back_sign_in")}+ </p>++ <FormProvider {...methods}>+ {/* Social Login Buttons */}+ {!twoFactorRequired && showSocialLogin && (+ <>+ <div className="flex flex-col gap-2">+ {isGoogleLoginEnabled && (+ <Button+ className="w-full"+ disabled={formState.isSubmitting}+ data-testid="google"+ onClick={async (e) => {+ e.preventDefault();+ setLastUsed("google");+ await signIn("google", {+ callbackUrl,+ });+ }}>+ <GoogleIcon />+ <span>{t("signin_with_google")}</span>+ {lastUsed === "google" && <LastUsed />}+ </Button>+ )}+ {isOutlookLoginEnabled && (+ <Button+ variant="outline"+ className="w-full"+ data-testid="microsoft"+ onClick={async (e) => {+ e.preventDefault();+ setLastUsed("microsoft");+ await signIn("azure-ad", {+ callbackUrl,+ });+ }}>+ <MicrosoftIcon />+ <span>{t("signin_with_microsoft")}</span>+ {lastUsed === "microsoft" && <LastUsed />}+ </Button>+ )}</div>- )}- </>- )}- <form onSubmit={methods.handleSubmit(onSubmit)} noValidate data-testid="login-form">- <div>+ {/* Divider */}+ <div className="my-6 flex items-center gap-4">+ <Separator className="flex-1" />+ <span className="text-sm text-zinc-400">{t("or").toLowerCase()}</span>+ <Separator className="flex-1" />+ </div>+ </>+ )}++ <form onSubmit={methods.handleSubmit(onSubmit)} noValidate data-testid="login-form"><input defaultValue={csrfToken || undefined} type="hidden" hidden {...register("csrfToken")} />- </div>- <div className="stack-y-6">- <div- className={classNames("stack-y-6", {- hidden: twoFactorRequired,- })}>- <EmailField- id="email"- label={t("email_address")}- defaultValue={totpEmail || (searchParams?.get("email") as string)}- placeholder="[email protected]"- required- autoComplete="email"- {...register("email")}- />- <div className="relative">- <PasswordField- id="password"- autoComplete="current-password"- required={!totpEmail}- className="mb-0"- {...register("password")}- />- <div className="absolute -top-[2px] ltr:right-0 rtl:left-0">- <Link- href="/auth/forgot-password"- tabIndex={-1}- className="text-sm font-medium text-default">- {t("forgot")}- </Link>- </div>++ {!twoFactorRequired && (+ <div className="space-y-6">+ {/* Email Field */}+ <Field>+ <FieldLabel>{t("email")}</FieldLabel>+ <Input+ id="email"+ type="email"+ defaultValue={totpEmail || (searchParams?.get("email") as string)}+ autoComplete="email"+ {...register("email")}+ />+ {formState.errors.email && (+ <p data-testid="field-error" className="text-destructive-foreground text-xs">+ {formState.errors.email.message}+ </p>+ )}+ </Field>++ {/* Password Field */}+ <Field>+ <div className="flex w-full items-center justify-between">+ <FieldLabel>{t("password")}</FieldLabel>+ <Link href="/auth/forgot-password" className="text-sm text-subtle hover:text-emphasis">+ {t("forgot")}+ </Link>+ </div>+ <InputGroup className="overflow-hidden">+ <InputGroupInput+ id="password"+ type={showPassword ? "text" : "password"}+ autoComplete="current-password"+ {...register("password")}+ />+ <InputGroupAddon align="inline-end">+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ onClick={() => setShowPassword(!showPassword)}+ aria-label={showPassword ? t("hide_password") : t("show_password")}>+ {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}+ </Button>+ </InputGroupAddon>+ </InputGroup>+ {formState.errors.password && (+ <p data-testid="field-error" className="text-destructive-foreground text-xs">+ {formState.errors.password.message}+ </p>+ )}+ </Field></div>- </div>+ )}- {twoFactorRequired ? !twoFactorLostAccess ? <TwoFactor center /> : <BackupCode center /> : null}+ {/* Two Factor */}+ {twoFactorRequired && (+ <div className="space-y-4">+ {!twoFactorLostAccess ? <TwoFactor center /> : <BackupCode center />}+ </div>+ )}- {errorMessage && <Alert severity="error" title={errorMessage} />}+ {/* Error Message */}+ {errorMessage && <Alert severity="error" title={errorMessage} className="mt-4" />}++ {/* Submit Button */}<Buttontype="submit"- color="secondary"- disabled={formState.isSubmitting}- className="justify-center w-full">- <span>{twoFactorRequired ? t("submit") : t("sign_in")}</span>- {lastUsed === "credentials" && !twoFactorRequired && <LastUsed className="text-gray-600" />}+ variant="outline"+ className="mt-8 w-full"+ disabled={formState.isSubmitting}>+ {twoFactorRequired ? t("submit") : t("continue")}</Button>- </div>- </form>- </FormProvider>- </AuthContainer>+ </form>++ {/* Two Factor Footer */}+ {twoFactorRequired && (+ <div className="mt-4 flex justify-center gap-4">+ {!totpEmail ? (+ <>+ <Button+ variant="ghost"+ onClick={() => {+ if (twoFactorLostAccess) {+ setTwoFactorLostAccess(false);+ methods.setValue("backupCode", "");+ } else {+ setTwoFactorRequired(false);+ methods.setValue("totpCode", "");+ }+ setErrorMessage(null);+ }}>+ <Icon name="arrow-left" className="mr-2 size-4" />+ {t("go_back")}+ </Button>+ {!twoFactorLostAccess && (+ <Button+ variant="ghost"+ onClick={() => {+ setTwoFactorLostAccess(true);+ setErrorMessage(null);+ methods.setValue("totpCode", "");+ }}>+ <Icon name="lock" className="mr-2 size-4" />+ {t("lost_access")}+ </Button>+ )}+ </>+ ) : (+ <Button+ variant="ghost"+ onClick={() => {+ window.location.replace("/");+ }}>+ {t("cancel")}+ </Button>+ )}+ </div>+ )}+ </FormProvider>+ </div>++ {/* Footer Links */}+ {!twoFactorRequired && (+ <div className="mt-6 flex items-center justify-center gap-4 text-center">+ {showSignupLink && (+ <Link+ href={+ callbackUrl+ ? `${WEBSITE_URL}/signup?redirect=${encodeURIComponent(callbackUrl)}`+ : `${WEBSITE_URL}/signup`+ }+ className="text-sm font-medium text-emphasis hover:underline">+ {t("create_account")}+ </Link>+ )}+ {displaySSOLogin && (+ <>+ {showSignupLink && <span className="text-subtle">·</span>}+ <SAMLLogin+ samlTenantID={samlTenantID}+ samlProductID={samlProductID}+ setErrorMessage={setErrorMessage}+ color="minimal"+ StartIcon={undefined}+ className="text-sm font-medium text-emphasis hover:underline p-0 h-auto"+ />+ </>+ )}+ </div>+ )}+ </div>+<AddToHomescreen /></div>);diff --git a/apps/web/modules/auth/sso/provider-view.tsx b/apps/web/modules/auth/sso/provider-view.tsxindex bc9d5a59643..aebc25fa7c8 100644--- a/apps/web/modules/auth/sso/provider-view.tsx+++ b/apps/web/modules/auth/sso/provider-view.tsx@@ -32,6 +32,8 @@ export default function Provider(props: SSOProviderPageProps) {signIn("saml", {}, { tenant: props.tenant, product: props.product });} else if (props.provider === "google" && email) {signIn("google", {}, { login_hint: email });+ } else if (props.provider === "microsoft") {+ signIn("azure-ad");} else {signIn(props.provider);}diff --git a/apps/web/modules/signup-view.tsx b/apps/web/modules/signup-view.tsxindex e72fbde1b38..f315c9461f9 100644--- a/apps/web/modules/signup-view.tsx+++ b/apps/web/modules/signup-view.tsx@@ -187,6 +187,7 @@ export default function Signup({token,orgSlug,isGoogleLoginEnabled,+ isOutlookLoginEnabled,isSAMLLoginEnabled,orgAutoAcceptEmail,redirectUrl,@@ -198,6 +199,7 @@ export default function Signup({const [premiumUsername, setPremiumUsername] = useState(false);const [usernameTaken, setUsernameTaken] = useState(false);const [isGoogleLoading, setIsGoogleLoading] = useState(false);+ const [isMicrosoftLoading, setIsMicrosoftLoading] = useState(false);const [accountUnderReview, setAccountUnderReview] = useState(false);const [displayEmailForm, setDisplayEmailForm] = useState(token);const [turnstileKey, setTurnstileKey] = useState(0);@@ -652,6 +654,7 @@ export default function Signup({<Buttoncolor="primary"loading={isGoogleLoading}+ disabled={isMicrosoftLoading}CustomStartIcon={<>{/* eslint-disable @next/next/no-img-element */}@@ -684,8 +687,8 @@ export default function Signup({searchQueryParams.set("username", prepopulateFormValues.username);localStorage.setItem("username", prepopulateFormValues.username);}- if (token) {- searchQueryParams.set("email", prepopulateFormValues?.email);+ if (token && prepopulateFormValues?.email) {+ searchQueryParams.set("email", prepopulateFormValues.email);}const url = searchQueryParams.toString()? `${GOOGLE_AUTH_URL}?${searchQueryParams.toString()}`@@ -698,7 +701,59 @@ export default function Signup({</div>)}- {isGoogleLoginEnabled && (+ {isOutlookLoginEnabled && (+ <div className="flex flex-col gap-2 md:flex-row">+ <Button+ color="secondary"+ loading={isMicrosoftLoading}+ disabled={isGoogleLoading}+ CustomStartIcon={+ <>+ {/* eslint-disable @next/next/no-img-element */}+ <img+ className={classNames(+ "text-subtle mr-2 h-4 w-4",+ premiumUsername && "opacity-50"+ )}+ src="/microsoft-logo.svg"+ alt="Continue with Microsoft Icon"+ />+ </>+ }+ className={classNames("w-full justify-center rounded-md text-center")}+ data-testid="continue-with-microsoft-button"+ onClick={async () => {+ posthog.capture("signup_microsoft_button_clicked", {+ has_token: !!token,+ is_org_invite: isOrgInviteByLink,+ org_slug: orgSlug,+ has_prepopulated_username: !!prepopulateFormValues?.username,+ });+ setIsSamlSignup(false);+ setIsMicrosoftLoading(true);+ const baseUrl = process.env.NEXT_PUBLIC_WEBAPP_URL;+ const MICROSOFT_AUTH_URL = `${baseUrl}/auth/sso/microsoft`;+ const searchQueryParams = new URLSearchParams();+ if (prepopulateFormValues?.username) {+ // If username is present we save it in query params to check for premium+ searchQueryParams.set("username", prepopulateFormValues.username);+ localStorage.setItem("username", prepopulateFormValues.username);+ }+ if (token && prepopulateFormValues?.email) {+ searchQueryParams.set("email", prepopulateFormValues.email);+ }+ const url = searchQueryParams.toString()+ ? `${MICROSOFT_AUTH_URL}?${searchQueryParams.toString()}`+ : MICROSOFT_AUTH_URL;++ router.push(url);+ }}>+ {t("continue_with_microsoft")}+ </Button>+ </div>+ )}++ {(isGoogleLoginEnabled || isOutlookLoginEnabled) && (<div><div className="relative flex items-center"><div className="border-subtle grow border-t" />@@ -714,7 +769,7 @@ export default function Signup({<div className="flex flex-col gap-2"><Buttoncolor="secondary"- disabled={isGoogleLoading}+ disabled={isGoogleLoading || isMicrosoftLoading}className={classNames("w-full justify-center rounded-md text-center")}onClick={() => {posthog.capture("signup_email_button_clicked", {diff --git a/apps/web/playwright/locale.e2e.ts b/apps/web/playwright/locale.e2e.tsindex ec4206bf624..c916091f20b 100644--- a/apps/web/playwright/locale.e2e.ts+++ b/apps/web/playwright/locale.e2e.ts@@ -19,14 +19,9 @@ test.describe("unauthorized user sees correct translations (de)", async () => {await page.locator("html[dir=ltr]").waitFor({ state: "attached" });{- await page.waitForSelector("text=Willkommen zurück");- const locator = page.getByText("Willkommen zurück", { exact: true });- expect(await locator.count()).toEqual(1);- }-- {- const locator = page.getByText("Welcome back", { exact: true });- expect(await locator.count()).toEqual(0);+ const subtitle = page.getByTestId("login-subtitle");+ await expect(subtitle).toBeVisible();+ await expect(subtitle).not.toHaveText(/Welcome back/i);}});});@@ -44,14 +39,9 @@ test.describe("unauthorized user sees correct translations (ar)", async () => {await page.locator("html[dir=rtl]").waitFor({ state: "attached" });{- await page.waitForSelector("text=أهلاً بك من جديد");- const locator = page.getByText("أهلاً بك من جديد", { exact: true });- expect(await locator.count()).toEqual(1);- }-- {- const locator = page.getByText("Welcome back", { exact: true });- expect(await locator.count()).toEqual(0);+ const subtitle = page.getByTestId("login-subtitle");+ await expect(subtitle).toBeVisible();+ await expect(subtitle).not.toHaveText(/Welcome back/i);}});});@@ -69,14 +59,9 @@ test.describe("unauthorized user sees correct translations (zh)", async () => {await page.locator("html[dir=ltr]").waitFor({ state: "attached" });{- await page.waitForSelector("text=欢迎回来");- const locator = page.getByText("欢迎回来", { exact: true });- expect(await locator.count()).toEqual(1);- }-- {- const locator = page.getByText("Welcome back", { exact: true });- expect(await locator.count()).toEqual(0);+ const subtitle = page.getByTestId("login-subtitle");+ await expect(subtitle).toBeVisible();+ await expect(subtitle).not.toHaveText(/Welcome back/i);}});});@@ -94,14 +79,9 @@ test.describe("unauthorized user sees correct translations (zh-CN)", async () =>await page.locator("html[dir=ltr]").waitFor({ state: "attached" });{- await page.waitForSelector("text=欢迎回来");- const locator = page.getByText("欢迎回来", { exact: true });- expect(await locator.count()).toEqual(1);- }-- {- const locator = page.getByText("Welcome back", { exact: true });- expect(await locator.count()).toEqual(0);+ const subtitle = page.getByTestId("login-subtitle");+ await expect(subtitle).toBeVisible();+ await expect(subtitle).not.toHaveText(/Welcome back/i);}});});@@ -119,14 +99,9 @@ test.describe("unauthorized user sees correct translations (zh-TW)", async () =>await page.locator("html[dir=ltr]").waitFor({ state: "attached" });{- await page.waitForSelector("text=歡迎回來");- const locator = page.getByText("歡迎回來", { exact: true });- expect(await locator.count()).toEqual(1);- }-- {- const locator = page.getByText("Welcome back", { exact: true });- expect(await locator.count()).toEqual(0);+ const subtitle = page.getByTestId("login-subtitle");+ await expect(subtitle).toBeVisible();+ await expect(subtitle).not.toHaveText(/Welcome back/i);}});});@@ -144,14 +119,9 @@ test.describe("unauthorized user sees correct translations (pt)", async () => {await page.locator("html[dir=ltr]").waitFor({ state: "attached" });{- await page.waitForSelector("text=Olá novamente");- const locator = page.getByText("Olá novamente", { exact: true });- expect(await locator.count()).toEqual(1);- }-- {- const locator = page.getByText("Welcome back", { exact: true });- expect(await locator.count()).toEqual(0);+ const subtitle = page.getByTestId("login-subtitle");+ await expect(subtitle).toBeVisible();+ await expect(subtitle).not.toHaveText(/Welcome back/i);}});});@@ -169,14 +139,9 @@ test.describe("unauthorized user sees correct translations (pt-br)", async () =>await page.locator("html[dir=ltr]").waitFor({ state: "attached" });{- await page.waitForSelector("text=Bem-vindo(a) novamente");- const locator = page.getByText("Bem-vindo(a) novamente", { exact: true });- expect(await locator.count()).toEqual(1);- }-- {- const locator = page.getByText("Welcome back", { exact: true });- expect(await locator.count()).toEqual(0);+ const subtitle = page.getByTestId("login-subtitle");+ await expect(subtitle).toBeVisible();+ await expect(subtitle).not.toHaveText(/Welcome back/i);}});});@@ -195,14 +160,9 @@ test.describe("unauthorized user sees correct translations (es-419)", async () =await page.locator("html[dir=ltr]").waitFor({ state: "attached" });{- await page.waitForSelector("text=Bienvenido de nuevo");- const locator = page.getByText("Bienvenido de nuevo", { exact: true });- expect(await locator.count()).toEqual(1);- }-- {- const locator = page.getByText("Welcome back", { exact: true });- expect(await locator.count()).toEqual(0);+ const subtitle = page.getByTestId("login-subtitle");+ await expect(subtitle).toBeVisible();+ await expect(subtitle).not.toHaveText(/Welcome back/i);}});});diff --git a/apps/web/playwright/login.oauth.e2e.ts b/apps/web/playwright/login.oauth.e2e.tsindex 0c66518583a..f3c43a4ce1a 100644--- a/apps/web/playwright/login.oauth.e2e.ts+++ b/apps/web/playwright/login.oauth.e2e.ts@@ -1,6 +1,8 @@import { expect, test } from "@playwright/test";-import { IS_GOOGLE_LOGIN_ENABLED, IS_SAML_LOGIN_ENABLED } from "../server/lib/constants";+import { isSAMLLoginEnabled } from "@calcom/features/ee/sso/lib/saml";++import { IS_GOOGLE_LOGIN_ENABLED } from "../server/lib/constants";test("Should display Google Login button", async ({ page }) => {// eslint-disable-next-line playwright/no-skipped-test@@ -13,7 +15,7 @@ test("Should display Google Login button", async ({ page }) => {test("Should display SAML Login button", async ({ page }) => {// eslint-disable-next-line playwright/no-skipped-test- test.skip(!IS_SAML_LOGIN_ENABLED, "It should only run if SAML Login is installed");+ test.skip(!isSAMLLoginEnabled, "It should only run if SAML Login is installed");// TODO: Fix this later// Button is visible only if there is a SAML connection exists (self-hosted)diff --git a/apps/web/playwright/oauth-provider.e2e.ts b/apps/web/playwright/oauth-provider.e2e.tsindex 4e39e5196e4..5b2ff7c3582 100644--- a/apps/web/playwright/oauth-provider.e2e.ts+++ b/apps/web/playwright/oauth-provider.e2e.ts@@ -243,7 +243,8 @@ test.describe("OAuth Provider", () => {);// check if user is redirected to login page- await expect(page.getByRole("heading", { name: "Welcome back" })).toBeVisible();+ await expect(page.getByRole("heading", { name: "Cal.com" })).toBeVisible();+ await expect(page.getByTestId("login-subtitle")).toBeVisible();await page.locator("#email").fill(user.email);await page.locator("#password").fill(user.username || "");await page.locator('[type="submit"]').click();diff --git a/apps/web/playwright/onboarding.e2e.ts b/apps/web/playwright/onboarding.e2e.tsindex 769cec9bc19..ebe14736392 100644--- a/apps/web/playwright/onboarding.e2e.ts+++ b/apps/web/playwright/onboarding.e2e.ts@@ -48,4 +48,5 @@ test.describe("Onboarding", () => {testOnboarding(IdentityProvider.GOOGLE);testOnboarding(IdentityProvider.CAL);testOnboarding(IdentityProvider.SAML);+ testOnboarding(IdentityProvider.AZUREAD);});diff --git a/apps/web/public/microsoft-logo.svg b/apps/web/public/microsoft-logo.svgnew file mode 100644index 00000000000..a3a36cbd6c1--- /dev/null+++ b/apps/web/public/microsoft-logo.svg@@ -0,0 +1,8 @@+<svg width="100" height="100" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="microsoft-logo-title microsoft-logo-desc">+ <title id="microsoft-logo-title">Microsoft</title>+ <desc id="microsoft-logo-desc">Microsoft logo</desc>+ <rect x="0" y="0" width="240" height="240" fill="#F25022"/>+ <rect x="272" y="0" width="240" height="240" fill="#7FBA00"/>+ <rect x="0" y="272" width="240" height="240" fill="#00A4EF"/>+ <rect x="272" y="272" width="240" height="240" fill="#FFB900"/>+</svg>diff --git a/apps/web/server/lib/auth/login/getServerSideProps.tsx b/apps/web/server/lib/auth/login/getServerSideProps.tsxindex 671cb0cb961..9798c594d88 100644--- a/apps/web/server/lib/auth/login/getServerSideProps.tsx+++ b/apps/web/server/lib/auth/login/getServerSideProps.tsx@@ -3,7 +3,8 @@ import type { GetServerSidePropsContext } from "next";import { getCsrfToken } from "next-auth/react";import { getServerSession } from "@calcom/features/auth/lib/getServerSession";-import { isSAMLLoginEnabled, samlProductID, samlTenantID } from "@calcom/features/ee/sso/lib/saml";+import { IS_OUTLOOK_LOGIN_ENABLED } from "@calcom/features/auth/lib/outlook";+import { isSAMLLoginEnabled, samlTenantID, samlProductID } from "@calcom/features/ee/sso/lib/saml";import { WEBSITE_URL } from "@calcom/lib/constants";import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl";import prisma from "@calcom/prisma";@@ -90,6 +91,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {props: {csrfToken: await getCsrfToken(context),isGoogleLoginEnabled: IS_GOOGLE_LOGIN_ENABLED,+ isOutlookLoginEnabled: IS_OUTLOOK_LOGIN_ENABLED,isSAMLLoginEnabled,samlTenantID,samlProductID,diff --git a/apps/web/server/lib/constants.ts b/apps/web/server/lib/constants.tsindex 3332dd8a009..5a8bcdabcb6 100644--- a/apps/web/server/lib/constants.ts+++ b/apps/web/server/lib/constants.ts@@ -3,4 +3,3 @@ export const { client_id: GOOGLE_CLIENT_ID, client_secret: GOOGLE_CLIENT_SECRETJSON.parse(GOOGLE_API_CREDENTIALS)?.web || {};export const GOOGLE_LOGIN_ENABLED = process.env.GOOGLE_LOGIN_ENABLED === "true";export const IS_GOOGLE_LOGIN_ENABLED = !!(GOOGLE_CLIENT_ID && GOOGLE_CLIENT_SECRET && GOOGLE_LOGIN_ENABLED);-export const IS_SAML_LOGIN_ENABLED = !!(process.env.SAML_DATABASE_URL && process.env.SAML_ADMINS);diff --git a/packages/app-store/_utils/oauth/updateProfilePhotoMicrosoft.test.ts b/packages/app-store/_utils/oauth/updateProfilePhotoMicrosoft.test.tsnew file mode 100644index 00000000000..b438f290417--- /dev/null+++ b/packages/app-store/_utils/oauth/updateProfilePhotoMicrosoft.test.ts@@ -0,0 +1,214 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mockUploadAvatar = vi.fn();+const mockResizeBase64Image = vi.fn();+const mockUpdateUserAvatarUrl = vi.fn();+const mockLoggerInfo = vi.fn();+const mockLoggerError = vi.fn();++vi.mock("@calcom/lib/logger", () => ({+ default: {+ info: (...args: unknown[]) => mockLoggerInfo(...args),+ error: (...args: unknown[]) => mockLoggerError(...args),+ },+}));++vi.mock("@calcom/lib/server/avatar", () => ({+ uploadAvatar: (...args: unknown[]) => mockUploadAvatar(...args),+}));++vi.mock("@calcom/lib/server/resizeBase64Image", () => ({+ resizeBase64Image: (...args: unknown[]) => mockResizeBase64Image(...args),+}));++vi.mock("@calcom/lib/server/updateUserAvatarUrl", () => ({+ updateUserAvatarUrl: (...args: unknown[]) => mockUpdateUserAvatarUrl(...args),+}));++import { updateProfilePhotoMicrosoft } from "./updateProfilePhotoMicrosoft";++function createFetchResponse({+ ok = true,+ status = 200,+ statusText = "OK",+ body = new ArrayBuffer(8),+ contentType = "image/png",+}: {+ ok?: boolean;+ status?: number;+ statusText?: string;+ body?: ArrayBuffer;+ contentType?: string | null;+} = {}) {+ return {+ ok,+ status,+ statusText,+ arrayBuffer: () => Promise.resolve(body),+ headers: {+ get: (name: string) => (name === "content-type" ? contentType : null),+ },+ };+}++describe("updateProfilePhotoMicrosoft", () => {+ let originalFetch: typeof globalThis.fetch;++ beforeEach(() => {+ vi.clearAllMocks();+ originalFetch = globalThis.fetch;+ mockResizeBase64Image.mockImplementation((img: string) => Promise.resolve(img));+ mockUploadAvatar.mockResolvedValue("/api/avatar/test-key.png");+ mockUpdateUserAvatarUrl.mockResolvedValue(undefined);+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ it("fetches Microsoft Graph photo endpoint with correct Bearer header", async () => {+ const mockFetch = vi.fn().mockResolvedValue(createFetchResponse());+ globalThis.fetch = mockFetch as unknown as typeof fetch;++ await updateProfilePhotoMicrosoft("my-token", 1);++ expect(mockFetch).toHaveBeenCalledWith("https://graph.microsoft.com/v1.0/me/photo/$value", {+ headers: { Authorization: "Bearer my-token" },+ });+ });++ it("converts response to base64 with content-type from header", async () => {+ const imageBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);+ globalThis.fetch = vi+ .fn()+ .mockResolvedValue(+ createFetchResponse({ body: imageBytes.buffer as ArrayBuffer, contentType: "image/png" })+ ) as unknown as typeof fetch;++ await updateProfilePhotoMicrosoft("token", 1);++ const expectedBase64 = `data:image/png;base64,${Buffer.from(imageBytes).toString("base64")}`;+ expect(mockResizeBase64Image).toHaveBeenCalledWith(expectedBase64);+ });++ it("defaults content-type to image/jpeg when header is missing", async () => {+ globalThis.fetch = vi+ .fn()+ .mockResolvedValue(createFetchResponse({ contentType: null })) as unknown as typeof fetch;++ await updateProfilePhotoMicrosoft("token", 1);++ expect(mockResizeBase64Image).toHaveBeenCalledWith(expect.stringContaining("data:image/jpeg;base64,"));+ });++ it("resizes, uploads, and updates avatarUrl on success", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse()) as unknown as typeof fetch;+ mockResizeBase64Image.mockResolvedValue("resized-image");+ mockUploadAvatar.mockResolvedValue("/api/avatar/new-key.png");++ await updateProfilePhotoMicrosoft("token", 42);++ expect(mockUploadAvatar).toHaveBeenCalledWith({ avatar: "resized-image", userId: 42 });+ expect(mockUpdateUserAvatarUrl).toHaveBeenCalledWith({ id: 42, avatarUrl: "/api/avatar/new-key.png" });+ });++ it("returns silently on 404 without uploading", async () => {+ globalThis.fetch = vi+ .fn()+ .mockResolvedValue(+ createFetchResponse({ ok: false, status: 404, statusText: "Not Found" })+ ) as unknown as typeof fetch;++ await updateProfilePhotoMicrosoft("token", 1);++ expect(mockUploadAvatar).not.toHaveBeenCalled();+ expect(mockUpdateUserAvatarUrl).not.toHaveBeenCalled();+ expect(mockLoggerInfo).toHaveBeenCalledWith("Microsoft profile photo not found for user");+ });++ it("returns silently on 500 without uploading", async () => {+ globalThis.fetch = vi+ .fn()+ .mockResolvedValue(+ createFetchResponse({ ok: false, status: 500, statusText: "Internal Server Error" })+ ) as unknown as typeof fetch;++ await updateProfilePhotoMicrosoft("token", 1);++ expect(mockUploadAvatar).not.toHaveBeenCalled();+ expect(mockUpdateUserAvatarUrl).not.toHaveBeenCalled();+ expect(mockLoggerError).toHaveBeenCalledWith(+ "Failed to fetch Microsoft profile photo",+ expect.objectContaining({ status: 500 })+ );+ });++ it("returns silently on 403 without uploading", async () => {+ globalThis.fetch = vi+ .fn()+ .mockResolvedValue(+ createFetchResponse({ ok: false, status: 403, statusText: "Forbidden" })+ ) as unknown as typeof fetch;++ await updateProfilePhotoMicrosoft("token", 1);++ expect(mockUploadAvatar).not.toHaveBeenCalled();+ });++ it("catches network errors and logs without throwing", async () => {+ globalThis.fetch = vi.fn().mockRejectedValue(new Error("Network timeout")) as unknown as typeof fetch;++ await expect(updateProfilePhotoMicrosoft("token", 1)).resolves.toBeUndefined();++ expect(mockLoggerError).toHaveBeenCalledWith(+ "Error updating avatarUrl from Microsoft sign-in",+ expect.any(Error)+ );+ });++ it("catches upload failures and logs without throwing", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse()) as unknown as typeof fetch;+ mockUploadAvatar.mockRejectedValue(new Error("Upload failed"));++ await expect(updateProfilePhotoMicrosoft("token", 1)).resolves.toBeUndefined();++ expect(mockLoggerError).toHaveBeenCalledWith(+ "Error updating avatarUrl from Microsoft sign-in",+ expect.any(Error)+ );+ });++ it("catches updateUserAvatarUrl failures and logs without throwing", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse()) as unknown as typeof fetch;+ mockUpdateUserAvatarUrl.mockRejectedValue(new Error("DB error"));++ await expect(updateProfilePhotoMicrosoft("token", 1)).resolves.toBeUndefined();++ expect(mockLoggerError).toHaveBeenCalledWith(+ "Error updating avatarUrl from Microsoft sign-in",+ expect.any(Error)+ );+ });++ it("logs info at the start of the function", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse()) as unknown as typeof fetch;++ await updateProfilePhotoMicrosoft("token", 1);++ expect(mockLoggerInfo).toHaveBeenCalledWith("updateProfilePhotoMicrosoft called", { hasToken: true });+ });++ it("logs success message on completion", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse()) as unknown as typeof fetch;++ await updateProfilePhotoMicrosoft("token", 1);++ expect(mockLoggerInfo).toHaveBeenCalledWith("Microsoft profile photo updated successfully");+ });++ it("does not throw when function completes successfully", async () => {+ globalThis.fetch = vi.fn().mockResolvedValue(createFetchResponse()) as unknown as typeof fetch;++ await expect(updateProfilePhotoMicrosoft("token", 1)).resolves.toBeUndefined();+ });+});diff --git a/packages/app-store/_utils/oauth/updateProfilePhotoMicrosoft.ts b/packages/app-store/_utils/oauth/updateProfilePhotoMicrosoft.tsnew file mode 100644index 00000000000..14f0f7e16f2--- /dev/null+++ b/packages/app-store/_utils/oauth/updateProfilePhotoMicrosoft.ts@@ -0,0 +1,43 @@+import logger from "@calcom/lib/logger";+import { uploadAvatar } from "@calcom/lib/server/avatar";+import { resizeBase64Image } from "@calcom/lib/server/resizeBase64Image";+import { updateUserAvatarUrl } from "@calcom/lib/server/updateUserAvatarUrl";++export async function updateProfilePhotoMicrosoft(accessToken: string, userId: number) {+ logger.info("updateProfilePhotoMicrosoft called", { hasToken: !!accessToken });+ try {+ const response = await fetch("https://graph.microsoft.com/v1.0/me/photo/$value", {+ headers: {+ Authorization: `Bearer ${accessToken}`,+ },+ });++ if (!response.ok) {+ // in case user might not have a profile photo set+ if (response.status === 404) {+ logger.info("Microsoft profile photo not found for user");+ return;+ }+ logger.error("Failed to fetch Microsoft profile photo", {+ status: response.status,+ statusText: response.statusText,+ });+ return;+ }++ const arrayBuffer = await response.arrayBuffer();+ const buffer = Buffer.from(arrayBuffer);+ const contentType = response.headers.get("content-type") || "image/jpeg";+ const base64Image = `data:${contentType};base64,${buffer.toString("base64")}`;++ const resizedAvatarUrl = await uploadAvatar({+ avatar: await resizeBase64Image(base64Image),+ userId,+ });++ await updateUserAvatarUrl({ id: userId, avatarUrl: resizedAvatarUrl });+ logger.info("Microsoft profile photo updated successfully");+ } catch (error) {+ logger.error("Error updating avatarUrl from Microsoft sign-in", error);+ }+}diff --git a/packages/features/auth/lib/identityProviders.test.ts b/packages/features/auth/lib/identityProviders.test.tsnew file mode 100644index 00000000000..9fa642ed977--- /dev/null+++ b/packages/features/auth/lib/identityProviders.test.ts@@ -0,0 +1,43 @@+import { IdentityProvider } from "@calcom/prisma/enums";+import { describe, expect, it } from "vitest";+import { getIdentityProvider, NEXTAUTH_TO_IDENTITY_PROVIDER } from "./identityProviders";++describe("identityProviders", () => {+ describe("NEXTAUTH_TO_IDENTITY_PROVIDER", () => {+ it("contains exactly the expected mapping keys", () => {+ expect(Object.keys(NEXTAUTH_TO_IDENTITY_PROVIDER).sort()).toEqual(+ ["azure-ad", "cal", "google", "saml", "saml-idp"].sort()+ );+ });+ });++ describe("getIdentityProvider", () => {+ it("maps 'azure-ad' to AZUREAD", () => {+ expect(getIdentityProvider("azure-ad")).toBe(IdentityProvider.AZUREAD);+ });++ it("maps 'google' to GOOGLE", () => {+ expect(getIdentityProvider("google")).toBe(IdentityProvider.GOOGLE);+ });++ it("maps 'saml' to SAML", () => {+ expect(getIdentityProvider("saml")).toBe(IdentityProvider.SAML);+ });++ it("maps 'saml-idp' to SAML", () => {+ expect(getIdentityProvider("saml-idp")).toBe(IdentityProvider.SAML);+ });++ it("maps 'cal' to CAL", () => {+ expect(getIdentityProvider("cal")).toBe(IdentityProvider.CAL);+ });++ it("returns null for unknown provider", () => {+ expect(getIdentityProvider("unknown-provider")).toBeNull();+ });++ it("returns null for empty string", () => {+ expect(getIdentityProvider("")).toBeNull();+ });+ });+});diff --git a/packages/features/auth/lib/identityProviders.ts b/packages/features/auth/lib/identityProviders.tsnew file mode 100644index 00000000000..37d540c0e5e--- /dev/null+++ b/packages/features/auth/lib/identityProviders.ts@@ -0,0 +1,21 @@+import { IdentityProvider } from "@calcom/prisma/enums";++/**+ * Maps NextAuth provider names to IdentityProvider enum values.+ * Includes aliases (e.g., "saml-idp" -> SAML).+ */+export const NEXTAUTH_TO_IDENTITY_PROVIDER: Record<string, IdentityProvider> = {+ "azure-ad": IdentityProvider.AZUREAD,+ google: IdentityProvider.GOOGLE,+ saml: IdentityProvider.SAML,+ "saml-idp": IdentityProvider.SAML,+ cal: IdentityProvider.CAL,+};++/**+ * Get IdentityProvider enum from NextAuth provider name.+ * Returns null for unknown providers so callers can reject the login gracefully.+ */+export const getIdentityProvider = (nextAuthProvider: string): IdentityProvider | null => {+ return NEXTAUTH_TO_IDENTITY_PROVIDER[nextAuthProvider] ?? null;+};diff --git a/packages/features/auth/lib/next-auth-options.test.ts b/packages/features/auth/lib/next-auth-options.test.tsindex 38706d4145a..32f4564de58 100644--- a/packages/features/auth/lib/next-auth-options.test.ts+++ b/packages/features/auth/lib/next-auth-options.test.ts@@ -1,8 +1,6 @@-import type { User } from "next-auth";-import { describe, expect, it, vi, beforeEach } from "vitest";-import { IdentityProvider, UserPermissionRole } from "@calcom/prisma/enums";-+import type { User } from "next-auth";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ErrorCode } from "./ErrorCode";// Mock dependencies@@ -97,6 +95,151 @@ vi.mock("@calcom/features/profile/repositories/ProfileRepository", () => ({},}));+// Additional mocks for signIn/JWT callback tests+const mockCredentialRepoFindFirst = vi.fn();+const mockCredentialRepoFindFirstByUserIdAndType = vi.fn();+const mockCredentialRepoCreate = vi.fn();+const mockBuildCredentialCreateData = vi.fn();+const mockUpdateProfilePhotoMicrosoft = vi.fn();+const mockUpdateProfilePhotoGoogle = vi.fn();+const mockGetIdentityProvider = vi.fn();+const mockGetBillingProviderService = vi.fn();+const mockHostedCalRef = { value: false };+const mockValidateSamlAccountConversion = vi.fn();+const mockWaitUntil = vi.fn();+const mockPrismaUserFindFirst = vi.fn();+const mockPrismaUserCreate = vi.fn();+const mockPrismaUserUpdate = vi.fn();+const mockPrismaTeamFindFirst = vi.fn();+const mockPrismaSelectedCalendarCreate = vi.fn();+const mockLinkAccount = vi.fn();++vi.mock("@calcom/features/credentials/repositories/CredentialRepository", () => ({+ CredentialRepository: {+ findFirstByAppIdAndUserId: (...args: unknown[]) => mockCredentialRepoFindFirst(...args),+ findFirstByUserIdAndType: (...args: unknown[]) => mockCredentialRepoFindFirstByUserIdAndType(...args),+ create: (...args: unknown[]) => mockCredentialRepoCreate(...args),+ },+}));++vi.mock("@calcom/features/credentials/services/CredentialDataService", () => ({+ buildCredentialCreateData: (...args: unknown[]) => mockBuildCredentialCreateData(...args),+}));++vi.mock("@calcom/app-store/_utils/oauth/updateProfilePhotoMicrosoft", () => ({+ updateProfilePhotoMicrosoft: (...args: unknown[]) => mockUpdateProfilePhotoMicrosoft(...args),+}));++vi.mock("@calcom/app-store/_utils/oauth/updateProfilePhotoGoogle", () => ({+ updateProfilePhotoGoogle: (...args: unknown[]) => mockUpdateProfilePhotoGoogle(...args),+}));++vi.mock("@calcom/features/auth/lib/identityProviders", () => ({+ getIdentityProvider: (...args: unknown[]) => mockGetIdentityProvider(...args),+}));++vi.mock("@calcom/features/auth/lib/outlook", () => ({+ OUTLOOK_CLIENT_ID: "mock-client-id",+ OUTLOOK_CLIENT_SECRET: "mock-client-secret",+ OUTLOOK_LOGIN_ENABLED: true,+}));++vi.mock("@calcom/features/ee/billing/di/containers/Billing", () => ({+ getBillingProviderService: (...args: unknown[]) => mockGetBillingProviderService(...args),+}));++vi.mock("@calcom/features/auth/lib/samlAccountLinking", () => ({+ validateSamlAccountConversion: (...args: unknown[]) => mockValidateSamlAccountConversion(...args),+}));++vi.mock("@calcom/features/ee/sso/lib/saml", () => ({+ clientSecretVerifier: "mock-secret",+ get hostedCal() {+ return mockHostedCalRef.value;+ },+ isSAMLLoginEnabled: false,+}));++vi.mock("@calcom/features/ee/organizations/lib/orgDomains", () => ({+ getOrgFullOrigin: vi.fn((slug: string) => `https://${slug}.cal.com`),+ subdomainSuffix: vi.fn(() => ".cal.com"),+}));++vi.mock("@vercel/functions", () => ({+ waitUntil: (...args: unknown[]) => mockWaitUntil(...args),+}));++vi.mock("@calcom/features/ee/organizations/di/OrganizationRepository.container", () => ({+ getOrganizationRepository: vi.fn(() => ({})),+}));++vi.mock("@calcom/features/ee/deployment/repositories/DeploymentRepository", () => ({+ DeploymentRepository: vi.fn().mockImplementation(() => ({})),+}));++vi.mock("@calcom/features/ee/impersonation/lib/ImpersonationProvider", () => ({+ default: vi.fn(),+}));++vi.mock("@calcom/features/ee/dsync/lib/users/createUsersAndConnectToOrg", () => ({+ default: vi.fn(),+}));++vi.mock("@calcom/lib/default-cookies", () => ({+ defaultCookies: vi.fn(() => ({})),+}));++vi.mock("@calcom/lib/random", () => ({+ randomString: vi.fn(() => "abc123"),+}));++vi.mock("@calcom/lib/slugify", () => ({+ default: vi.fn((s: string) => s.toLowerCase().replace(/\s+/g, "-")),+}));++vi.mock("@calcom/app-store/googlecalendar/lib/CalendarService", () => ({+ createGoogleCalendarServiceWithGoogleType: vi.fn(),+}));++vi.mock("googleapis-common", () => ({+ OAuth2Client: vi.fn(),+}));++vi.mock("@googleapis/calendar", () => ({+ calendar_v3: {+ Calendar: vi.fn(),+ },+}));++vi.mock("next-auth/jwt", () => ({+ encode: vi.fn(),+}));++vi.mock("./signJwt", () => ({+ default: vi.fn().mockResolvedValue("mock-jwt"),+}));++vi.mock("./dub", () => ({+ dub: { track: { lead: vi.fn() } },+}));++vi.mock("../signup/utils/getOrgUsernameFromEmail", () => ({+ getOrgUsernameFromEmail: vi.fn((email: string) => email.split("@")[0]),+}));++vi.mock("@calcom/ee/common/server/LicenseKeyService", () => ({+ LicenseKeySingleton: {+ getInstance: vi.fn().mockResolvedValue({+ checkLicense: vi.fn().mockResolvedValue(true),+ }),+ },+}));++vi.mock("next-auth/providers/azure-ad", () => ({ default: vi.fn() }));+vi.mock("next-auth/providers/credentials", () => ({ default: vi.fn(() => ({ id: "credentials" })) }));+vi.mock("next-auth/providers/email", () => ({ default: vi.fn() }));+vi.mock("next-auth/providers/google", () => ({ default: vi.fn() }));+describe("CredentialsProvider authorize", () => {let authorizeCredentials: typeof import("./next-auth-options").authorizeCredentials;let verifyPassword: any;@@ -233,3 +376,910 @@ describe("CredentialsProvider authorize", () => {});});});++describe("Azure AD signIn callback", () => {+ let getOptions: typeof import("./next-auth-options").getOptions;+ let signInCallback: NonNullable<ReturnType<typeof getOptions>["callbacks"]>["signIn"];++ beforeEach(async () => {+ vi.clearAllMocks();+ mockGetIdentityProvider.mockImplementation((provider: string) => {+ const map: Record<string, string> = {+ "azure-ad": "AZUREAD",+ google: "GOOGLE",+ saml: "SAML",+ "saml-idp": "SAML",+ cal: "CAL",+ };+ return map[provider] ?? null;+ });++ // Mock prisma methods used in signIn callback+ const prismaModule = await import("@calcom/prisma");+ const prismaDefault = (prismaModule as any).default;+ prismaDefault.user = {+ ...prismaDefault.user,+ findFirst: mockPrismaUserFindFirst,+ create: mockPrismaUserCreate,+ update: mockPrismaUserUpdate,+ };+ prismaDefault.team = {+ findFirst: mockPrismaTeamFindFirst,+ };+ prismaDefault.selectedCalendar = {+ create: mockPrismaSelectedCalendarCreate,+ };++ mockPrismaUserFindFirst.mockResolvedValue(null);+ mockPrismaUserCreate.mockResolvedValue({ id: 100, email: "[email protected]", twoFactorEnabled: false });+ mockPrismaUserUpdate.mockResolvedValue({});+ mockPrismaTeamFindFirst.mockResolvedValue(null);+ mockUpdateProfilePhotoMicrosoft.mockResolvedValue(undefined);++ // Setup mock adapter+ const adapterModule = await import("./next-auth-custom-adapter");+ (adapterModule.default as any).mockReturnValue({ linkAccount: mockLinkAccount });+ mockLinkAccount.mockResolvedValue(undefined);++ mockGetBillingProviderService.mockReturnValue({+ createCustomer: vi.fn().mockResolvedValue({ stripeCustomerId: "cus_test" }),+ });+ mockWaitUntil.mockImplementation((p: Promise<any>) => p.catch(() => {}));++ const authModule = await import("./next-auth-options");+ getOptions = authModule.getOptions;+ const options = getOptions({ getDubId: () => undefined, getTrackingData: () => ({}) as any });+ signInCallback = options.callbacks!.signIn! as any;+ });++ describe("Azure AD email verification (xms_edov)", () => {+ const baseParams = {+ user: { id: "1", email: "[email protected]", name: "User", emailVerified: null },+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth" as const,+ },+ credentials: undefined,+ email: undefined,+ };++ it("allows login when xms_edov is true (boolean)", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ accounts: [{ provider: "azure-ad" }],+ twoFactorEnabled: false,+ identityProvider: "AZUREAD",+ });++ const result = await signInCallback({+ ...baseParams,+ profile: { email_verified: false, xms_edov: true } as any,+ } as any);++ expect(result).toBe(true);+ });++ it("allows login when xms_edov is string 'true'", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ accounts: [{ provider: "azure-ad" }],+ twoFactorEnabled: false,+ identityProvider: "AZUREAD",+ });++ const result = await signInCallback({+ ...baseParams,+ profile: { xms_edov: "true" } as any,+ } as any);++ expect(result).toBe(true);+ });++ it("allows login when xms_edov is string '1'", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ accounts: [{ provider: "azure-ad" }],+ twoFactorEnabled: false,+ identityProvider: "AZUREAD",+ });++ const result = await signInCallback({+ ...baseParams,+ profile: { xms_edov: "1" } as any,+ } as any);++ expect(result).toBe(true);+ });++ it("allows login when xms_edov is number 1", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ accounts: [{ provider: "azure-ad" }],+ twoFactorEnabled: false,+ identityProvider: "AZUREAD",+ });++ const result = await signInCallback({+ ...baseParams,+ profile: { xms_edov: 1 } as any,+ } as any);++ expect(result).toBe(true);+ });++ it("rejects login when xms_edov is false", async () => {+ const result = await signInCallback({+ ...baseParams,+ profile: { xms_edov: false } as any,+ } as any);++ expect(result).toBe("/auth/error?error=unverified-email");+ });++ it("rejects login when xms_edov is undefined", async () => {+ const result = await signInCallback({+ ...baseParams,+ profile: {} as any,+ } as any);++ expect(result).toBe("/auth/error?error=unverified-email");+ });++ it("rejects login when xms_edov is 0", async () => {+ const result = await signInCallback({+ ...baseParams,+ profile: { xms_edov: 0 } as any,+ } as any);++ expect(result).toBe("/auth/error?error=unverified-email");+ });++ it("rejects login when xms_edov is string '0'", async () => {+ const result = await signInCallback({+ ...baseParams,+ profile: { xms_edov: "0" } as any,+ } as any);++ expect(result).toBe("/auth/error?error=unverified-email");+ });++ it("allows non-AZUREAD with email_verified=true", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ accounts: [{ provider: "google" }],+ twoFactorEnabled: false,+ identityProvider: "GOOGLE",+ });++ const result = await signInCallback({+ user: { id: "1", email: "[email protected]", name: "User", emailVerified: null },+ account: { provider: "google", providerAccountId: "google-123", type: "oauth" as const },+ profile: { email_verified: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(result).toBe(true);+ });++ it("rejects non-AZUREAD with email_verified=false", async () => {+ const result = await signInCallback({+ user: { id: "1", email: "[email protected]", name: "User", emailVerified: null },+ account: { provider: "google", providerAccountId: "google-123", type: "oauth" as const },+ profile: { email_verified: false } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(result).toBe("/auth/error?error=unverified-email");+ });+ });++ describe("Azure AD profile photo on new user (signIn callback)", () => {+ const baseUser = { id: "1", email: "[email protected]", name: "New User", emailVerified: null };++ it("calls updateProfilePhotoMicrosoft for new Azure AD user with access_token", async () => {+ // No existing user+ mockPrismaUserFindFirst.mockResolvedValue(null);+ mockPrismaUserCreate.mockResolvedValue({+ id: 100,+ email: "[email protected]",+ twoFactorEnabled: false,+ });++ await signInCallback({+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-new-123",+ type: "oauth" as const,+ access_token: "new-user-token",+ },+ profile: { xms_edov: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(mockUpdateProfilePhotoMicrosoft).toHaveBeenCalledWith("new-user-token", 100);+ });++ it("skips updateProfilePhotoMicrosoft for new Azure AD user without access_token", async () => {+ mockPrismaUserFindFirst.mockResolvedValue(null);+ mockPrismaUserCreate.mockResolvedValue({+ id: 101,+ email: "[email protected]",+ twoFactorEnabled: false,+ });++ await signInCallback({+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-new-456",+ type: "oauth" as const,+ },+ profile: { xms_edov: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(mockUpdateProfilePhotoMicrosoft).not.toHaveBeenCalled();+ });++ it("skips updateProfilePhotoMicrosoft for new Google user", async () => {+ mockPrismaUserFindFirst.mockResolvedValue(null);+ mockPrismaUserCreate.mockResolvedValue({+ id: 102,+ email: "[email protected]",+ twoFactorEnabled: false,+ });++ await signInCallback({+ user: baseUser,+ account: {+ provider: "google",+ providerAccountId: "google-new-789",+ type: "oauth" as const,+ access_token: "google-token",+ },+ profile: { email_verified: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(mockUpdateProfilePhotoMicrosoft).not.toHaveBeenCalled();+ });++ it("photo update failure does not crash signup", async () => {+ mockPrismaUserFindFirst.mockResolvedValue(null);+ mockPrismaUserCreate.mockResolvedValue({+ id: 103,+ email: "[email protected]",+ twoFactorEnabled: false,+ });+ mockUpdateProfilePhotoMicrosoft.mockRejectedValue(new Error("Photo update failed"));++ const result = await signInCallback({+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-fail-123",+ type: "oauth" as const,+ access_token: "fail-token",+ },+ profile: { xms_edov: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ // Should still return something (true or error redirect), not throw+ expect(result).toBeDefined();+ });+ });++ describe("Azure AD identity provider conversion (signIn callback)", () => {+ beforeEach(() => {+ mockHostedCalRef.value = true;+ });++ afterEach(() => {+ mockHostedCalRef.value = false;+ });++ it("CAL user with verified email converts to AZUREAD on Azure AD login", async () => {+ // No existing user with AZUREAD identity+ mockPrismaUserFindFirst+ .mockResolvedValueOnce(null) // First call: lookup by identityProvider + providerAccountId+ .mockResolvedValueOnce(null) // Legacy lookup+ .mockResolvedValueOnce({+ // Lookup by email+ id: 50,+ email: "[email protected]",+ emailVerified: new Date(),+ identityProvider: "CAL",+ password: { hash: "hashed" },+ twoFactorEnabled: false,+ });++ const result = await signInCallback({+ user: { id: "1", email: "[email protected]", name: "User", emailVerified: null },+ account: { provider: "azure-ad", providerAccountId: "azure-conv-1", type: "oauth" as const },+ profile: { xms_edov: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(mockPrismaUserUpdate).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ identityProvider: "AZUREAD",+ identityProviderId: "azure-conv-1",+ }),+ })+ );+ expect(result).toBe(true);+ });++ it("GOOGLE user converts to AZUREAD on Azure AD login", async () => {+ mockPrismaUserFindFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(null).mockResolvedValueOnce({+ id: 51,+ email: "[email protected]",+ emailVerified: new Date(),+ identityProvider: "GOOGLE",+ password: null,+ twoFactorEnabled: false,+ });++ const result = await signInCallback({+ user: { id: "1", email: "[email protected]", name: "User", emailVerified: null },+ account: { provider: "azure-ad", providerAccountId: "azure-conv-2", type: "oauth" as const },+ profile: { xms_edov: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ // Google -> Azure AD conversion goes through the GOOGLE -> (SAML | AZUREAD) branch+ expect(mockPrismaUserUpdate).toHaveBeenCalled();+ expect(result).toBe(true);+ });++ it("AZUREAD user converts to GOOGLE on Google login", async () => {+ mockPrismaUserFindFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(null).mockResolvedValueOnce({+ id: 52,+ email: "[email protected]",+ emailVerified: new Date(),+ identityProvider: "AZUREAD",+ password: null,+ twoFactorEnabled: false,+ });++ const result = await signInCallback({+ user: { id: "1", email: "[email protected]", name: "User", emailVerified: null },+ account: { provider: "google", providerAccountId: "google-conv-1", type: "oauth" as const },+ profile: { email_verified: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(mockPrismaUserUpdate).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ identityProvider: "GOOGLE",+ identityProviderId: "google-conv-1",+ }),+ })+ );+ expect(result).toBe(true);+ });++ it("unverified CAL account blocks Azure AD linking (anti-hijack)", async () => {+ mockPrismaUserFindFirst+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({+ id: 53,+ email: "[email protected]",+ emailVerified: null,+ identityProvider: "CAL",+ password: { hash: "hashed" },+ twoFactorEnabled: false,+ });++ const result = await signInCallback({+ user: { id: "1", email: "[email protected]", name: "User", emailVerified: null },+ account: { provider: "azure-ad", providerAccountId: "azure-hijack-1", type: "oauth" as const },+ profile: { xms_edov: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(result).toBe("/auth/error?error=unverified-email");+ });++ it("AZUREAD user converts to SAML with validation", async () => {+ mockPrismaUserFindFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(null).mockResolvedValueOnce({+ id: 54,+ email: "[email protected]",+ emailVerified: new Date(),+ identityProvider: "AZUREAD",+ password: null,+ twoFactorEnabled: false,+ });+ mockValidateSamlAccountConversion.mockResolvedValue({ allowed: true });++ const result = await signInCallback({+ user: {+ id: "1",+ email: "[email protected]",+ name: "User",+ emailVerified: null,+ samlTenant: "tenant-1",+ },+ account: { provider: "saml-idp", providerAccountId: "saml-conv-1", type: "credentials" as const },+ profile: { email_verified: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ // saml-idp is credentials type, so it returns true directly+ expect(result).toBe(true);+ });++ it("AZUREAD to SAML blocked when SAML validation fails", async () => {+ mockPrismaUserFindFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(null).mockResolvedValueOnce({+ id: 55,+ email: "[email protected]",+ emailVerified: new Date(),+ identityProvider: "AZUREAD",+ password: null,+ twoFactorEnabled: false,+ });+ mockValidateSamlAccountConversion.mockResolvedValue({+ allowed: false,+ errorUrl: "/auth/error?error=saml-tenant-mismatch",+ });++ const result = await signInCallback({+ user: { id: "1", email: "[email protected]", name: "User", emailVerified: null },+ account: { provider: "saml", providerAccountId: "saml-block-1", type: "oauth" as const },+ profile: { email_verified: true } as any,+ credentials: undefined,+ email: undefined,+ } as any);++ expect(result).toBe("/auth/error?error=saml-tenant-mismatch");+ });+ });+});++describe("Azure AD JWT callback", () => {+ let getOptions: typeof import("./next-auth-options").getOptions;+ let jwtCallback: NonNullable<ReturnType<typeof getOptions>["callbacks"]>["jwt"];+ let originalFetch: typeof globalThis.fetch;++ beforeEach(async () => {+ vi.clearAllMocks();+ originalFetch = globalThis.fetch;+ mockGetIdentityProvider.mockImplementation((provider: string) => {+ const map: Record<string, string> = {+ "azure-ad": "AZUREAD",+ google: "GOOGLE",+ saml: "SAML",+ "saml-idp": "SAML",+ cal: "CAL",+ };+ return map[provider] ?? null;+ });+ mockCredentialRepoCreate.mockResolvedValue({ id: 1 });+ mockBuildCredentialCreateData.mockImplementation((data: any) => data);+ mockUpdateProfilePhotoMicrosoft.mockResolvedValue(undefined);++ // Setup prisma mocks+ const prismaModule = await import("@calcom/prisma");+ const prismaDefault = (prismaModule as any).default;+ prismaDefault.user = {+ ...prismaDefault.user,+ findFirst: mockPrismaUserFindFirst,+ };+ prismaDefault.selectedCalendar = {+ create: mockPrismaSelectedCalendarCreate,+ };+ prismaDefault.membership = {+ findUnique: vi.fn().mockResolvedValue(null),+ };++ mockPrismaSelectedCalendarCreate.mockResolvedValue({});++ const { ProfileRepository } = await import("@calcom/features/profile/repositories/ProfileRepository");+ (ProfileRepository.findAllProfilesForUserIncludingMovedUser as any).mockResolvedValue([+ { id: 1, upId: "usr_1" },+ ]);+ (ProfileRepository.findByUpIdWithAuth as any).mockResolvedValue({+ id: 1,+ username: "testuser",+ organization: null,+ });++ const authModule = await import("./next-auth-options");+ getOptions = authModule.getOptions;+ const options = getOptions({ getDubId: () => undefined, getTrackingData: () => ({}) as any });+ jwtCallback = options.callbacks!.jwt! as any;+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ describe("Azure AD calendar auto-install", () => {+ const baseToken = { sub: "1", email: "[email protected]", upId: "usr_1" } as any;+ const baseUser = {+ id: "1",+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ } as any;++ it("creates office365-calendar credential on first login with all scopes", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ mockCredentialRepoFindFirst.mockResolvedValue(null);+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: [{ id: "cal-id-1", isDefaultCalendar: true }] }),+ }) as unknown as typeof fetch;++ await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "at-123",+ refresh_token: "rt-123",+ expires_at: 1700000000,+ scope: "User.Read Calendars.Read Calendars.ReadWrite offline_access",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(mockBuildCredentialCreateData).toHaveBeenCalledWith(+ expect.objectContaining({+ appId: "office365-calendar",+ type: "office365_calendar",+ })+ );+ expect(mockCredentialRepoCreate).toHaveBeenCalled();+ });++ it("skips creation when office365-calendar credential already exists", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ mockCredentialRepoFindFirst.mockResolvedValue({ id: 99 });++ await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "at-123",+ scope: "User.Read Calendars.Read Calendars.ReadWrite",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(mockBuildCredentialCreateData).not.toHaveBeenCalledWith(+ expect.objectContaining({ appId: "office365-calendar" })+ );+ });++ it("skips creation when calendar scopes are missing", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ mockCredentialRepoFindFirst.mockResolvedValue(null);++ await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "at-123",+ scope: "User.Read",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(mockCredentialRepoCreate).not.toHaveBeenCalled();+ });++ it("offline_access is excluded from scope check", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ mockCredentialRepoFindFirst.mockResolvedValue(null);+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: [] }),+ }) as unknown as typeof fetch;++ // Scope without offline_access — should still pass scope check+ await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "at-123",+ scope: "User.Read Calendars.Read Calendars.ReadWrite",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(mockCredentialRepoCreate).toHaveBeenCalled();+ });++ it("fetches default calendar and creates selectedCalendar", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ mockCredentialRepoFindFirst.mockResolvedValue(null);+ mockCredentialRepoCreate.mockResolvedValue({ id: 77 });+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () =>+ Promise.resolve({+ value: [+ { id: "non-default-cal", isDefaultCalendar: false },+ { id: "default-cal-id", isDefaultCalendar: true },+ ],+ }),+ }) as unknown as typeof fetch;++ await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "at-123",+ scope: "User.Read Calendars.Read Calendars.ReadWrite",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(mockPrismaSelectedCalendarCreate).toHaveBeenCalledWith({+ data: expect.objectContaining({+ integration: "office365_calendar",+ externalId: "default-cal-id",+ credentialId: 77,+ }),+ });+ });++ it("Graph API fetch failure logs error but does not crash", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ mockCredentialRepoFindFirst.mockResolvedValue(null);+ globalThis.fetch = vi.fn().mockRejectedValue(new Error("Network error")) as unknown as typeof fetch;++ // Should not throw+ const result = await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "at-123",+ scope: "User.Read Calendars.Read Calendars.ReadWrite",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(result).toBeDefined();+ });++ it("calls updateProfilePhotoMicrosoft after calendar install", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ mockCredentialRepoFindFirst.mockResolvedValue(null);+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: [] }),+ }) as unknown as typeof fetch;++ await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "photo-token",+ scope: "User.Read Calendars.Read Calendars.ReadWrite",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(mockUpdateProfilePhotoMicrosoft).toHaveBeenCalledWith("photo-token", 1);+ });++ it("calls updateProfilePhotoMicrosoft even when calendar already installed (else-if branch)", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ // Calendar credential already exists+ mockCredentialRepoFindFirst.mockResolvedValue({ id: 99 });++ await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "photo-token-2",+ scope: "User.Read Calendars.Read Calendars.ReadWrite",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(mockUpdateProfilePhotoMicrosoft).toHaveBeenCalledWith("photo-token-2", 1);+ });++ it("converts expires_at from seconds to milliseconds in credential key", async () => {+ mockPrismaUserFindFirst.mockResolvedValue({+ id: 1,+ email: "[email protected]",+ name: "Test",+ username: "test",+ role: "USER",+ locale: "en",+ avatarUrl: null,+ identityProvider: "AZUREAD",+ identityProviderId: "azure-123",+ teams: [],+ movedToProfileId: null,+ });+ mockCredentialRepoFindFirst.mockResolvedValue(null);+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: [] }),+ }) as unknown as typeof fetch;++ const expiresAtSeconds = 1700000000;++ await jwtCallback({+ token: baseToken,+ user: baseUser,+ account: {+ provider: "azure-ad",+ providerAccountId: "azure-123",+ type: "oauth",+ access_token: "at-123",+ refresh_token: "rt-123",+ expires_at: expiresAtSeconds,+ scope: "User.Read Calendars.Read Calendars.ReadWrite",+ },+ trigger: undefined,+ session: undefined,+ } as any);++ expect(mockBuildCredentialCreateData).toHaveBeenCalledWith(+ expect.objectContaining({+ key: expect.objectContaining({+ expiry_date: expiresAtSeconds * 1000,+ }),+ })+ );+ });+ });++});diff --git a/packages/features/auth/lib/next-auth-options.ts b/packages/features/auth/lib/next-auth-options.tsindex cd830fc7dc0..2accd391c48 100644--- a/packages/features/auth/lib/next-auth-options.ts+++ b/packages/features/auth/lib/next-auth-options.ts@@ -1,24 +1,16 @@-import { calendar_v3 } from "@googleapis/calendar";-import { waitUntil } from "@vercel/functions";-import { OAuth2Client } from "googleapis-common";-import type { AuthOptions, Account, Session, User } from "next-auth";-import type { JWT } from "next-auth/jwt";-import { encode } from "next-auth/jwt";-import type { Provider } from "next-auth/providers";-import CredentialsProvider from "next-auth/providers/credentials";-import EmailProvider from "next-auth/providers/email";-import GoogleProvider from "next-auth/providers/google";-import { updateProfilePhotoGoogle } from "@calcom/app-store/_utils/oauth/updateProfilePhotoGoogle";-import {- createGoogleCalendarServiceWithGoogleType,- type GoogleCalendar,-} from "@calcom/app-store/googlecalendar/lib/CalendarService";+import { updateProfilePhotoMicrosoft } from "@calcom/app-store/_utils/oauth/updateProfilePhotoMicrosoft";+import { createGoogleCalendarServiceWithGoogleType } from "@calcom/app-store/googlecalendar/lib/CalendarService";import { LicenseKeySingleton } from "@calcom/ee/common/server/LicenseKeyService";-import { getBillingProviderService } from "@calcom/features/ee/billing/di/containers/Billing";+import { getIdentityProvider } from "@calcom/features/auth/lib/identityProviders";+import {+ OUTLOOK_CLIENT_ID,+ OUTLOOK_CLIENT_SECRET,+ OUTLOOK_LOGIN_ENABLED,+} from "@calcom/features/auth/lib/outlook";import { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";import { buildCredentialCreateData } from "@calcom/features/credentials/services/CredentialDataService";-import type { TrackingData } from "@calcom/lib/tracking";+import { getBillingProviderService } from "@calcom/features/ee/billing/di/containers/Billing";import { DeploymentRepository } from "@calcom/features/ee/deployment/repositories/DeploymentRepository";import createUsersAndConnectToOrg from "@calcom/features/ee/dsync/lib/users/createUsersAndConnectToOrg";import ImpersonationProvider from "@calcom/features/ee/impersonation/lib/ImpersonationProvider";@@ -30,12 +22,15 @@ import { UserRepository } from "@calcom/features/users/repositories/UserRepositoimport { isPasswordValid } from "@calcom/lib/auth/isPasswordValid";import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";import {+ ENABLE_PROFILE_SWITCHER,GOOGLE_CALENDAR_SCOPES,GOOGLE_OAUTH_SCOPES,HOSTED_CAL_FEATURES,IS_CALCOM,+ IS_TEAM_BILLING_ENABLED,+ MICROSOFT_CALENDAR_SCOPES,+ WEBAPP_URL,} from "@calcom/lib/constants";-import { ENABLE_PROFILE_SWITCHER, IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";import { symmetricDecrypt, symmetricEncrypt } from "@calcom/lib/crypto";import { defaultCookies } from "@calcom/lib/default-cookies";import { isENVDev } from "@calcom/lib/env";@@ -44,24 +39,40 @@ import { randomString } from "@calcom/lib/random";import { safeStringify } from "@calcom/lib/safeStringify";import { hashEmail } from "@calcom/lib/server/PiiHasher";import slugify from "@calcom/lib/slugify";+import type { TrackingData } from "@calcom/lib/tracking";import prisma from "@calcom/prisma";import type { Membership, Team } from "@calcom/prisma/client";-import { CreationSource } from "@calcom/prisma/enums";-import { IdentityProvider, MembershipRole, UserPermissionRole } from "@calcom/prisma/enums";+import { CreationSource, IdentityProvider, MembershipRole, UserPermissionRole } from "@calcom/prisma/enums";import { teamMetadataSchema, userMetadata } from "@calcom/prisma/zod-utils";-+import type { UserProfile } from "@calcom/types/UserProfile";+import { calendar_v3 } from "@googleapis/calendar";+import { waitUntil } from "@vercel/functions";+import { OAuth2Client } from "googleapis-common";+import type { Account, AuthOptions, Profile, Session, User } from "next-auth";+import type { AdapterUser } from "next-auth/adapters";+import type { JWT } from "next-auth/jwt";+import { encode } from "next-auth/jwt";+import AzureADProvider from "next-auth/providers/azure-ad";+import CredentialsProvider from "next-auth/providers/credentials";+import EmailProvider from "next-auth/providers/email";+import GoogleProvider from "next-auth/providers/google";+import type { Provider } from "next-auth/providers/index";import { getOrgUsernameFromEmail } from "../signup/utils/getOrgUsernameFromEmail";-import { ErrorCode } from "./ErrorCode";import { dub } from "./dub";-import { validateSamlAccountConversion } from "./samlAccountLinking";+import { ErrorCode } from "./ErrorCode";import CalComAdapter from "./next-auth-custom-adapter";+import { validateSamlAccountConversion } from "./samlAccountLinking";import { verifyPassword } from "./verifyPassword";-import { UserProfile } from "@calcom/types/UserProfile";type UserWithProfiles = NonNullable<Awaited<ReturnType<UserRepository["findByEmailAndIncludeProfilesAndPassword"]>>>;+interface ExtendedOAuthProfile extends Profile {+ email_verified?: boolean; // Google/OIDC standard+ xms_edov?: boolean | string | number; // Azure AD specific+}+// This adapts our internal user model to what NextAuth expects// NextAuth core requires id to be a string, so we handle that hereconst AdapterUserPresenter = {@@ -126,7 +137,8 @@ export const checkIfUserBelongsToActiveTeam = <T extends UserTeams>(user: T) =>const checkIfUserShouldBelongToOrg = async (idP: IdentityProvider, email: string) => {const [orgUsername, apexDomain] = email.split("@");- if (!ORGANIZATIONS_AUTOLINK || idP !== "GOOGLE") return { orgUsername, orgId: undefined };+ if (!ORGANIZATIONS_AUTOLINK || (idP !== "GOOGLE" && idP !== "AZUREAD"))+ return { orgUsername, orgId: undefined };const existingOrg = await prisma.team.findFirst({where: {organizationSettings: {@@ -270,10 +282,26 @@ export const CalComCredentialsProvider = CredentialsProvider({name: "Cal.com",type: "credentials",credentials: {- email: { label: "Email Address", type: "email", placeholder: "[email protected]" },- password: { label: "Password", type: "password", placeholder: "Your super secure password" },- totpCode: { label: "Two-factor Code", type: "input", placeholder: "Code from authenticator app" },- backupCode: { label: "Backup Code", type: "input", placeholder: "Two-factor backup code" },+ email: {+ label: "Email Address",+ type: "email",+ placeholder: "[email protected]",+ },+ password: {+ label: "Password",+ type: "password",+ placeholder: "Your super secure password",+ },+ totpCode: {+ label: "Two-factor Code",+ type: "input",+ placeholder: "Code from authenticator app",+ },+ backupCode: {+ label: "Backup Code",+ type: "input",+ placeholder: "Two-factor backup code",+ },},authorize: authorizeCredentials,});@@ -470,6 +498,32 @@ if (isSAMLLoginEnabled) {);}+if (OUTLOOK_LOGIN_ENABLED && OUTLOOK_CLIENT_ID && OUTLOOK_CLIENT_SECRET) {+ providers.push(+ AzureADProvider({+ clientId: OUTLOOK_CLIENT_ID,+ clientSecret: OUTLOOK_CLIENT_SECRET,+ allowDangerousEmailAccountLinking: true,+ authorization: {+ params: {+ scope: ["openid", "profile", "email", ...MICROSOFT_CALENDAR_SCOPES].join(" "),+ prompt: "consent",+ },+ },+ // Azure AD returns base64-encoded picture data (~9KB) that bloats the JWT cookie.+ // we exclude it here and fetch the profile photo separately via Microsoft Graph API.+ profile(profile) {+ return {+ id: profile.sub,+ name: profile.name,+ email: profile.email,+ image: null,+ };+ },+ })+ );+}+providers.push(EmailProvider({type: "email",@@ -485,16 +539,6 @@ function isNumber(n: string) {const calcomAdapter = CalComAdapter(prisma);-const mapIdentityProvider = (providerName: string) => {- switch (providerName) {- case "saml-idp":- case "saml":- return IdentityProvider.SAML;- default:- return IdentityProvider.GOOGLE;- }-};-export const getOptions = ({getDubId,getTrackingData,@@ -505,7 +549,6 @@ export const getOptions = ({getTrackingData: () => TrackingData;}): AuthOptions => ({// eslint-disable-next-line @typescript-eslint/ban-ts-comment- // @ts-ignoreadapter: calcomAdapter,session: {strategy: "jwt",@@ -627,7 +670,7 @@ export const getOptions = ({orgRole = membership?.role;}- return {+ const autoMergeJwt = {...existingUserWithoutTeamsField,...token,profileId: profile.id,@@ -650,6 +693,7 @@ export const getOptions = ({}: null,} as JWT;+ return autoMergeJwt;};if (!user) {return await autoMergeIdentities();@@ -693,9 +737,19 @@ export const getOptions = ({if (account.type === "oauth") {log.debug("callbacks:jwt:accountType:oauth", safeStringify({ account }));if (!account.provider || !account.providerAccountId) {- return { ...token, upId: user.profile?.upId ?? token.upId ?? null } as JWT;+ return {+ ...token,+ upId: user.profile?.upId ?? token.upId ?? null,+ } as JWT;+ }+ const idP = getIdentityProvider(account.provider);++ if (!idP) {+ log.warn("callbacks:jwt:accountType:oauth - unknown provider, falling back to auto-merge", {+ provider: account.provider,+ });+ return await autoMergeIdentities();}- const idP = account.provider === "saml" ? IdentityProvider.SAML : IdentityProvider.GOOGLE;const existingUser = await prisma.user.findFirst({where: {@@ -773,9 +827,81 @@ export const getOptions = ({}await updateProfilePhotoGoogle(oAuth2Client, Number(user.id));}++ // Installing Outlook Calendar by default for Microsoft/Azure AD sign-in+ // Note: offline_access is requested but not returned in scope list by Microsoft+ const microsoftCalendarScopesToCheck = MICROSOFT_CALENDAR_SCOPES.filter(+ (scope) => scope !== "offline_access"+ );+ if (+ account.provider === "azure-ad" &&+ !(await CredentialRepository.findFirstByAppIdAndUserId({+ userId: Number(user.id),+ appId: "office365-calendar",+ })) &&+ microsoftCalendarScopesToCheck.every((scope) => grantedScopes.includes(scope))+ ) {+ const credentialKey = {+ access_token: account.access_token,+ refresh_token: account.refresh_token,+ email: user.email,+ // convert seconds to milliseconds — OAuthManager compares expiry_date against Date.now()+ expiry_date: account.expires_at ? account.expires_at * 1000 : undefined,+ };++ const outlookCredentialData = buildCredentialCreateData({+ userId: Number(user.id),+ key: credentialKey,+ appId: "office365-calendar",+ type: "office365_calendar",+ });+ const outlookCredential = await CredentialRepository.create(outlookCredentialData);++ // Fetch default calendar from Microsoft Graph API+ try {+ const calendarResponse = await fetch(+ "https://graph.microsoft.com/v1.0/me/calendars?$select=id,isDefaultCalendar",+ {+ headers: {+ Authorization: `Bearer ${account.access_token}`,+ "Content-Type": "application/json",+ },+ }+ );++ if (calendarResponse.ok) {+ const calendarData = await calendarResponse.json();+ const defaultCalendar = calendarData.value?.find(+ (cal: { isDefaultCalendar?: boolean }) => cal.isDefaultCalendar+ );++ if (defaultCalendar?.id) {+ await prisma.selectedCalendar.create({+ data: {+ userId: Number(user.id),+ integration: "office365_calendar",+ externalId: defaultCalendar.id,+ credentialId: outlookCredential.id,+ },+ });+ }+ }+ } catch (error) {+ log.error("Failed to fetch default calendar for Microsoft sign-in", error);+ }++ // Update profile photo for Microsoft/Azure AD sign-in+ if (account.access_token) {+ await updateProfilePhotoMicrosoft(account.access_token, Number(user.id));+ }+ } else if (account.provider === "azure-ad" && account.access_token) {+ // Update profile photo even if calendar wasn't installed+ await updateProfilePhotoMicrosoft(account.access_token, Number(user.id));+ }+const allProfiles = await ProfileRepository.findAllProfilesForUserIncludingMovedUser(existingUser);const { upId } = determineProfile({ profiles: allProfiles, token });- log.debug("callbacks:jwt:accountType:oauth:existingUser", safeStringify({ existingUser, upId }));+ log.debug("callbacks:jwt:accountType:oauth:existingUser", safeStringify({ userId: existingUser.id, upId }));return {...token,upId,@@ -783,9 +909,10 @@ export const getOptions = ({name: existingUser.name,username: existingUser.username,email: existingUser.email,+ avatarUrl: existingUser.avatarUrl,role: existingUser.role,- impersonatedBy: token.impersonatedBy,belongsToActiveTeam: token?.belongsToActiveTeam as boolean,+ impersonatedBy: token.impersonatedBy,org: token?.org,orgAwareUsername: token.orgAwareUsername,locale: existingUser.locale,@@ -798,7 +925,10 @@ export const getOptions = ({log.warn("callbacks:jwt - unknown account type",- safeStringify({ accountType: account.type, accountProvider: account.provider })+ safeStringify({+ accountType: account.type,+ accountProvider: account.provider,+ }));return token;},@@ -828,18 +958,14 @@ export const getOptions = ({};return calendsoSession;},- async signIn(params): Promise<boolean | string> {- const {- /**- * Available when Credentials provider is used - Has the value returned by authorize callback- */- user,- /**- * Available when Credentials provider is used - Has the value submitted as the body of the HTTP POST submission- */- profile,- account,- } = params;+ async signIn(params: {+ user: User | AdapterUser;+ account: Account | null;+ profile?: Profile;+ email?: { verificationRequest?: boolean };+ credentials?: Record<string, unknown>;+ }): Promise<boolean | string> {+ const { user, account, profile } = params;log.debug("callbacks:signin", safeStringify(params));@@ -876,7 +1002,9 @@ export const getOptions = ({}}if (!user.email) {- log.warn("callbacks:signIn - user email is missing", { provider: account?.provider });+ log.warn("callbacks:signIn - user email is missing", {+ provider: account?.provider,+ });return false;}@@ -888,12 +1016,38 @@ export const getOptions = ({return false;}if (account?.provider) {- const idP: IdentityProvider = mapIdentityProvider(account.provider);- // eslint-disable-next-line @typescript-eslint/ban-ts-comment- // @ts-ignore-error TODO validate email_verified key on profile- user.email_verified = user.email_verified || !!user.emailVerified || profile.email_verified;+ const idP = getIdentityProvider(account.provider);- if (!user.email_verified) {+ if (!idP) {+ log.warn("callbacks:signIn - unknown provider, rejecting login", {+ provider: account.provider,+ });+ return "/auth/error?error=unknown-provider";+ }+ // Use optional chaining for safety, especially with AdapterUser potentially having different structure initially.+ const isEmailVerified = user.emailVerified || (profile as ExtendedOAuthProfile)?.email_verified;++ // For Azure AD, check xms_edov (Email Domain Owner Verified) claim+ // xms_edov returns inconsistent types: boolean for work/school, string "1" for personal accounts+ const xmsEdov = (profile as ExtendedOAuthProfile)?.xms_edov;+ const isAzureEmailDomainVerified =+ xmsEdov === true || xmsEdov === "true" || xmsEdov === "1" || xmsEdov === 1;++ // Azure AD never sets email_verified in the token profile, so isEmailVerified is always+ // falsy for AZUREAD logins. Use isAzureEmailDomainVerified (xms_edov) as the equivalent+ // proof of ownership so the auto-merge path treats Azure AD the same as other verified IdPs.+ const isVerified =+ isEmailVerified || (idP === IdentityProvider.AZUREAD && isAzureEmailDomainVerified);++ if (idP === IdentityProvider.AZUREAD && !isAzureEmailDomainVerified) {+ log.error(+ "Azure AD email domain not verified (xms_edov claim)",+ safeStringify({ emailDomain: user.email?.split("@")[1], xmsEdov })+ );+ return "/auth/error?error=unverified-email";+ }++ if (!isEmailVerified && idP !== IdentityProvider.AZUREAD) {log.error("Attention: SAML/Google User email is not verified in the IdP", safeStringify({ user }));return "/auth/error?error=unverified-email";}@@ -986,7 +1140,10 @@ export const getOptions = ({});if (!userWithNewEmail) {- await prisma.user.update({ where: { id: existingUser.id }, data: { email: user.email } });+ await prisma.user.update({+ where: { id: existingUser.id },+ data: { email: user.email },+ });if (existingUser.twoFactorEnabled) {return loginWithTotp(existingUser.email);} else {@@ -1019,11 +1176,7 @@ export const getOptions = ({if (existingUserWithEmail) {// if self-hosted then we can allow auto-merge of identity providers if email is verified- if (- !hostedCal &&- existingUserWithEmail.emailVerified &&- existingUserWithEmail.identityProvider !== IdentityProvider.CAL- ) {+ if (!hostedCal && isVerified && existingUserWithEmail.identityProvider !== IdentityProvider.CAL) {// Verify SAML IdP is authoritative before auto-mergeif (idP === IdentityProvider.SAML) {const samlTenant = getSamlTenant();@@ -1083,10 +1236,12 @@ export const getOptions = ({}}- // User signs up with email/password and then tries to login with Google/SAML using the same email+ // User signs up with email/password and then tries to login with Google/SAML/AzureAD using the same emailif (existingUserWithEmail.identityProvider === IdentityProvider.CAL &&- (idP === IdentityProvider.GOOGLE || idP === IdentityProvider.SAML)+ (idP === IdentityProvider.GOOGLE ||+ idP === IdentityProvider.SAML ||+ idP === IdentityProvider.AZUREAD)) {// Prevent account pre-hijacking: block OAuth linking for unverified accountsif (!existingUserWithEmail.emailVerified) {@@ -1121,13 +1276,43 @@ export const getOptions = ({return `/auth/error?error=wrong-provider&provider=${existingUserWithEmail.identityProvider}`;} else if (existingUserWithEmail.identityProvider === IdentityProvider.GOOGLE &&- idP === IdentityProvider.SAML+ (idP === IdentityProvider.SAML || idP === IdentityProvider.AZUREAD)+ ) {+ // Verify SAML IdP is authoritative before converting account+ if (idP === IdentityProvider.SAML) {+ const samlTenant = getSamlTenant();+ const validation = await validateSamlAccountConversion(samlTenant, user.email, "Google→SAML");+ if (!validation.allowed) {+ return validation.errorUrl;+ }+ }++ await prisma.user.update({+ where: { email: existingUserWithEmail.email },+ // also update email to the IdP email+ data: {+ email: user.email.toLowerCase(),+ identityProvider: idP,+ identityProviderId: account.providerAccountId,+ },+ });++ if (existingUserWithEmail.twoFactorEnabled) {+ return loginWithTotp(existingUserWithEmail.email);+ } else {+ return true;+ }+ } else if (+ existingUserWithEmail.identityProvider === IdentityProvider.AZUREAD &&+ (idP === IdentityProvider.SAML || idP === IdentityProvider.GOOGLE)) {// Verify SAML IdP is authoritative before converting account- const samlTenant = getSamlTenant();- const validation = await validateSamlAccountConversion(samlTenant, user.email, "Google→SAML");- if (!validation.allowed) {- return validation.errorUrl;+ if (idP === IdentityProvider.SAML) {+ const samlTenant = getSamlTenant();+ const validation = await validateSamlAccountConversion(samlTenant, user.email, "AzureAD→SAML");+ if (!validation.allowed) {+ return validation.errorUrl;+ }}await prisma.user.update({@@ -1157,7 +1342,7 @@ export const getOptions = ({return `/auth/error?error=wrong-provider&provider=${existingUserWithEmail.identityProvider}`;}- // Associate with organization if enabled by flag and idP is Google (for now)+ // Associate with organization if enabled by flag and idP is Google or Azure ADconst { orgUsername, orgId } = await checkIfUserShouldBelongToOrg(idP, user.email);try {@@ -1170,14 +1355,18 @@ export const getOptions = ({emailVerified: new Date(Date.now()),name: user.name,...(user.image && { avatarUrl: user.image }),- email: user.email,+ email: user.email!,identityProvider: idP,identityProviderId: account.providerAccountId,...(orgId && {verified: true,organization: { connect: { id: orgId } },teams: {- create: { role: MembershipRole.MEMBER, accepted: true, team: { connect: { id: orgId } } },+ create: {+ role: MembershipRole.MEMBER,+ accepted: true,+ team: { connect: { id: orgId } },+ },},}),creationSource: CreationSource.WEBAPP,@@ -1190,6 +1379,11 @@ export const getOptions = ({);await calcomAdapter.linkAccount(linkAccountNewUserData);+ // Update profile photo for new Microsoft/Azure AD users+ if (account.provider === "azure-ad" && account.access_token) {+ await updateProfilePhotoMicrosoft(account.access_token, newUser.id);+ }+waitUntil((async () => {try {@@ -1225,7 +1419,7 @@ export const getOptions = ({})());- if (account.twoFactorEnabled) {+ if (newUser.twoFactorEnabled) {return loginWithTotp(newUser.email);} else {return true;@@ -1310,7 +1504,7 @@ const determineProfile = ({if (token.upId) {// Otherwise use what's in the token- return { profileId: token.profileId, upId: token.upId as string };+ return { id: token.profileId ?? null, upId: token.upId as string };}// If there is just one profile it has to be the one we want to log into.diff --git a/packages/features/auth/lib/outlook.test.ts b/packages/features/auth/lib/outlook.test.tsnew file mode 100644index 00000000000..b2fd52b25a8--- /dev/null+++ b/packages/features/auth/lib/outlook.test.ts@@ -0,0 +1,66 @@+import process from "node:process";+import { afterEach, describe, expect, it, vi } from "vitest";++describe("outlook", () => {+ const originalEnv = { ...process.env };++ afterEach(() => {+ // Restore original env completely+ for (const key of ["MS_GRAPH_CLIENT_ID", "MS_GRAPH_CLIENT_SECRET", "OUTLOOK_LOGIN_ENABLED"]) {+ if (originalEnv[key] === undefined) {+ delete process.env[key];+ } else {+ process.env[key] = originalEnv[key];+ }+ }+ vi.resetModules();+ });++ it("reads OUTLOOK_CLIENT_ID from MS_GRAPH_CLIENT_ID", async () => {+ process.env.MS_GRAPH_CLIENT_ID = "test-client-id";+ const { OUTLOOK_CLIENT_ID } = await import("./outlook");+ expect(OUTLOOK_CLIENT_ID).toBe("test-client-id");+ });++ it("reads OUTLOOK_CLIENT_SECRET from MS_GRAPH_CLIENT_SECRET", async () => {+ process.env.MS_GRAPH_CLIENT_SECRET = "test-secret";+ const { OUTLOOK_CLIENT_SECRET } = await import("./outlook");+ expect(OUTLOOK_CLIENT_SECRET).toBe("test-secret");+ });++ it("OUTLOOK_LOGIN_ENABLED is true only for exact string 'true'", async () => {+ process.env.OUTLOOK_LOGIN_ENABLED = "true";+ const mod = await import("./outlook");+ expect(mod.OUTLOOK_LOGIN_ENABLED).toBe(true);+ });++ it("OUTLOOK_LOGIN_ENABLED is false for other values", async () => {+ process.env.OUTLOOK_LOGIN_ENABLED = "1";+ const mod = await import("./outlook");+ expect(mod.OUTLOOK_LOGIN_ENABLED).toBe(false);+ });++ it("IS_OUTLOOK_LOGIN_ENABLED is true when all vars are set", async () => {+ process.env.MS_GRAPH_CLIENT_ID = "client-id";+ process.env.MS_GRAPH_CLIENT_SECRET = "client-secret";+ process.env.OUTLOOK_LOGIN_ENABLED = "true";+ const { IS_OUTLOOK_LOGIN_ENABLED } = await import("./outlook");+ expect(IS_OUTLOOK_LOGIN_ENABLED).toBe(true);+ });++ it("IS_OUTLOOK_LOGIN_ENABLED is false when client ID is missing", async () => {+ delete process.env.MS_GRAPH_CLIENT_ID;+ process.env.MS_GRAPH_CLIENT_SECRET = "client-secret";+ process.env.OUTLOOK_LOGIN_ENABLED = "true";+ const { IS_OUTLOOK_LOGIN_ENABLED } = await import("./outlook");+ expect(IS_OUTLOOK_LOGIN_ENABLED).toBe(false);+ });++ it("IS_OUTLOOK_LOGIN_ENABLED is false when client secret is missing", async () => {+ process.env.MS_GRAPH_CLIENT_ID = "client-id";+ delete process.env.MS_GRAPH_CLIENT_SECRET;+ process.env.OUTLOOK_LOGIN_ENABLED = "true";+ const { IS_OUTLOOK_LOGIN_ENABLED } = await import("./outlook");+ expect(IS_OUTLOOK_LOGIN_ENABLED).toBe(false);+ });+});diff --git a/packages/features/auth/lib/outlook.ts b/packages/features/auth/lib/outlook.tsnew file mode 100644index 00000000000..2f05bb2e631--- /dev/null+++ b/packages/features/auth/lib/outlook.ts@@ -0,0 +1,8 @@+export const OUTLOOK_CLIENT_ID = process.env.MS_GRAPH_CLIENT_ID;+export const OUTLOOK_CLIENT_SECRET = process.env.MS_GRAPH_CLIENT_SECRET;+export const OUTLOOK_LOGIN_ENABLED = process.env.OUTLOOK_LOGIN_ENABLED === "true";+export const IS_OUTLOOK_LOGIN_ENABLED = !!(+ OUTLOOK_CLIENT_ID &&+ OUTLOOK_CLIENT_SECRET &&+ process.env.OUTLOOK_LOGIN_ENABLED === "true"+);diff --git a/packages/lib/constants.ts b/packages/lib/constants.tsindex 84856a4bfe3..ccdf4513415 100644--- a/packages/lib/constants.ts+++ b/packages/lib/constants.ts@@ -276,3 +276,10 @@ export const IS_API_V2_E2E = process.env.IS_E2E === "true";export const ENABLE_ASYNC_TASKER =process.env.ENABLE_ASYNC_TASKER === "true" && !process.env.NEXT_PUBLIC_IS_E2E && !IS_API_V2_E2E;++export const MICROSOFT_CALENDAR_SCOPES = [+ "User.Read",+ "Calendars.Read",+ "Calendars.ReadWrite",+ "offline_access",+];diff --git a/packages/lib/server/avatar.test.ts b/packages/lib/server/avatar.test.tsnew file mode 100644index 00000000000..4e6c446bf2f--- /dev/null+++ b/packages/lib/server/avatar.test.ts@@ -0,0 +1,119 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockFindUnique = vi.fn();+const mockUpsert = vi.fn();+const mockUuidv4 = vi.fn();+const mockConvertSvgToPng = vi.fn();++vi.mock("uuid", () => ({+ v4: (...args: unknown[]) => mockUuidv4(...args),+}));++vi.mock("@calcom/prisma", () => ({+ prisma: {+ avatar: {+ findUnique: (...args: unknown[]) => mockFindUnique(...args),+ upsert: (...args: unknown[]) => mockUpsert(...args),+ },+ },+}));++vi.mock("./imageUtils", () => ({+ convertSvgToPng: (...args: unknown[]) => mockConvertSvgToPng(...args),+}));++import { uploadAvatar } from "./avatar";++describe("uploadAvatar", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockConvertSvgToPng.mockImplementation((data: string) => Promise.resolve(`processed_${data}`));+ mockUpsert.mockResolvedValue(undefined);+ mockUuidv4.mockReturnValue("generated-uuid-1234");+ });++ it("generates new objectKey via uuidv4 when no existing avatar", async () => {+ mockFindUnique.mockResolvedValue(null);++ const result = await uploadAvatar({ userId: 1, avatar: "image-data" });++ expect(mockUuidv4).toHaveBeenCalled();+ expect(result).toBe("/api/avatar/generated-uuid-1234.png");+ });++ it("reuses existing objectKey and does NOT call uuidv4", async () => {+ mockFindUnique.mockResolvedValue({ objectKey: "existing-key-5678" });++ const result = await uploadAvatar({ userId: 1, avatar: "image-data" });++ expect(mockUuidv4).not.toHaveBeenCalled();+ expect(result).toBe("/api/avatar/existing-key-5678.png");+ });++ it("includes objectKey in create clause but NOT in update clause", async () => {+ mockFindUnique.mockResolvedValue(null);++ await uploadAvatar({ userId: 1, avatar: "image-data" });++ expect(mockUpsert).toHaveBeenCalledWith(+ expect.objectContaining({+ create: expect.objectContaining({ objectKey: "generated-uuid-1234" }),+ update: expect.not.objectContaining({ objectKey: expect.anything() }),+ })+ );+ });++ it("returns /api/avatar/{objectKey}.png", async () => {+ mockFindUnique.mockResolvedValue({ objectKey: "my-key" });++ const result = await uploadAvatar({ userId: 5, avatar: "data" });++ expect(result).toBe("/api/avatar/my-key.png");+ });++ it("uses correct compound unique key for lookup and upsert", async () => {+ mockFindUnique.mockResolvedValue(null);++ await uploadAvatar({ userId: 42, avatar: "data" });++ const expectedWhere = {+ teamId_userId_isBanner: { teamId: 0, userId: 42, isBanner: false },+ };++ expect(mockFindUnique).toHaveBeenCalledWith(expect.objectContaining({ where: expectedWhere }));+ expect(mockUpsert).toHaveBeenCalledWith(expect.objectContaining({ where: expectedWhere }));+ });++ it("calls convertSvgToPng on input data", async () => {+ mockFindUnique.mockResolvedValue(null);++ await uploadAvatar({ userId: 1, avatar: "svg-data-here" });++ expect(mockConvertSvgToPng).toHaveBeenCalledWith("svg-data-here");+ });++ it("passes processed data to upsert create and update", async () => {+ mockFindUnique.mockResolvedValue(null);++ await uploadAvatar({ userId: 1, avatar: "raw-data" });++ expect(mockUpsert).toHaveBeenCalledWith(+ expect.objectContaining({+ create: expect.objectContaining({ data: "processed_raw-data" }),+ update: expect.objectContaining({ data: "processed_raw-data" }),+ })+ );+ });++ it("sets isBanner to false in create clause", async () => {+ mockFindUnique.mockResolvedValue(null);++ await uploadAvatar({ userId: 1, avatar: "data" });++ expect(mockUpsert).toHaveBeenCalledWith(+ expect.objectContaining({+ create: expect.objectContaining({ isBanner: false }),+ })+ );+ });+});diff --git a/packages/lib/server/avatar.ts b/packages/lib/server/avatar.tsindex 6f852320e99..1b743b00791 100644--- a/packages/lib/server/avatar.ts+++ b/packages/lib/server/avatar.ts@@ -5,9 +5,22 @@ import { prisma } from "@calcom/prisma";import { convertSvgToPng } from "./imageUtils";export const uploadAvatar = async ({ userId, avatar: data }: { userId: number; avatar: string }) => {- const objectKey = uuidv4();const processedData = await convertSvgToPng(data);+ // Check if avatar already exists to preserve the objectKey+ const existing = await prisma.avatar.findUnique({+ where: {+ teamId_userId_isBanner: {+ teamId: 0,+ userId,+ isBanner: false,+ },+ },+ select: { objectKey: true },+ });++ const objectKey = existing?.objectKey ?? uuidv4();+await prisma.avatar.upsert({where: {teamId_userId_isBanner: {@@ -24,7 +37,7 @@ export const uploadAvatar = async ({ userId, avatar: data }: { userId: number; a},update: {data: processedData,- objectKey,+ // Don't update objectKey - keep existing to preserve URLs},});diff --git a/packages/lib/server/updateUserAvatarUrl.test.ts b/packages/lib/server/updateUserAvatarUrl.test.tsnew file mode 100644index 00000000000..8fc2d8590bf--- /dev/null+++ b/packages/lib/server/updateUserAvatarUrl.test.ts@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockUpdateMany = vi.fn();++vi.mock("@calcom/prisma", () => ({+ default: {+ user: {+ updateMany: (...args: unknown[]) => mockUpdateMany(...args),+ },+ },+}));++import { updateUserAvatarUrl } from "./updateUserAvatarUrl";++describe("updateUserAvatarUrl", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockUpdateMany.mockResolvedValue({ count: 1 });+ });++ it("calls updateMany with correct where clause requiring null avatarUrl", async () => {+ await updateUserAvatarUrl({ id: 42, avatarUrl: "/api/avatar/abc.png" });++ expect(mockUpdateMany).toHaveBeenCalledWith({+ where: {+ id: 42,+ avatarUrl: { equals: null },+ },+ data: { avatarUrl: "/api/avatar/abc.png" },+ });+ });++ it("passes avatarUrl unchanged", async () => {+ const url = "https://example.com/photo.jpg";+ await updateUserAvatarUrl({ id: 1, avatarUrl: url });++ expect(mockUpdateMany).toHaveBeenCalledWith(+ expect.objectContaining({+ data: { avatarUrl: url },+ })+ );+ });++ it("returns undefined (void)", async () => {+ const result = await updateUserAvatarUrl({ id: 1, avatarUrl: "/test.png" });+ expect(result).toBeUndefined();+ });++ it("propagates prisma errors", async () => {+ mockUpdateMany.mockRejectedValue(new Error("DB connection failed"));++ await expect(updateUserAvatarUrl({ id: 1, avatarUrl: "/test.png" })).rejects.toThrow(+ "DB connection failed"+ );+ });++ it("uses the provided user id in the where clause", async () => {+ await updateUserAvatarUrl({ id: 999, avatarUrl: "/photo.png" });++ expect(mockUpdateMany).toHaveBeenCalledWith(+ expect.objectContaining({+ where: expect.objectContaining({ id: 999 }),+ })+ );+ });+});diff --git a/packages/lib/server/updateUserAvatarUrl.ts b/packages/lib/server/updateUserAvatarUrl.tsnew file mode 100644index 00000000000..7e5693beace--- /dev/null+++ b/packages/lib/server/updateUserAvatarUrl.ts@@ -0,0 +1,11 @@+import prisma from "@calcom/prisma";++export const updateUserAvatarUrl = async ({ id, avatarUrl }: { id: number; avatarUrl: string }) => {+ await prisma.user.updateMany({+ where: {+ id,+ avatarUrl: { equals: null },+ },+ data: { avatarUrl },+ });+};diff --git a/packages/prisma/migrations/20250413115818_add_azure/migration.sql b/packages/prisma/migrations/20250413115818_add_azure/migration.sqlnew file mode 100644index 00000000000..30046fd807f--- /dev/null+++ b/packages/prisma/migrations/20250413115818_add_azure/migration.sql@@ -0,0 +1,2 @@+-- AlterEnum+ALTER TYPE "IdentityProvider" ADD VALUE 'AZUREAD';diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prismaindex 1e8930156a7..230c00df8ab 100644--- a/packages/prisma/schema.prisma+++ b/packages/prisma/schema.prisma@@ -349,6 +349,7 @@ enum IdentityProvider {CALSAML+ AZUREAD}model DestinationCalendar {diff --git a/packages/trpc/server/routers/viewer/me/get.handler.test.ts b/packages/trpc/server/routers/viewer/me/get.handler.test.tsnew file mode 100644index 00000000000..2652b4cd36e--- /dev/null+++ b/packages/trpc/server/routers/viewer/me/get.handler.test.ts@@ -0,0 +1,233 @@+import { IdentityProvider } from "@calcom/prisma/enums";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { TrpcSessionUser } from "../../../types";++const {+ mockFindAllProfilesForUserIncludingMovedUser,+ mockEnrichUserWithTheProfile,+ mockFindUnique,+ mockFindMany,+ mockGetTeamIdsWithPermission,+ MockUserRepository,+ MockPermissionCheckService,+} = vi.hoisted(() => {+ const mockFindAllProfilesForUserIncludingMovedUser = vi.fn();+ const mockEnrichUserWithTheProfile = vi.fn();+ const mockFindUnique = vi.fn();+ const mockFindMany = vi.fn();+ const mockGetTeamIdsWithPermission = vi.fn();++ class MockUserRepository {+ enrichUserWithTheProfile = (...args: unknown[]) => mockEnrichUserWithTheProfile(...args);+ }++ class MockPermissionCheckService {+ getTeamIdsWithPermission = (...args: unknown[]) => mockGetTeamIdsWithPermission(...args);+ }++ return {+ mockFindAllProfilesForUserIncludingMovedUser,+ mockEnrichUserWithTheProfile,+ mockFindUnique,+ mockFindMany,+ mockGetTeamIdsWithPermission,+ MockUserRepository,+ MockPermissionCheckService,+ };+});++vi.mock("@calcom/features/profile/repositories/ProfileRepository", () => ({+ ProfileRepository: {+ findAllProfilesForUserIncludingMovedUser: (...args: unknown[]) =>+ mockFindAllProfilesForUserIncludingMovedUser(...args),+ buildPersonalProfileFromUser: vi.fn(() => ({ upId: "usr_1" })),+ },+}));++vi.mock("@calcom/features/users/repositories/UserRepository", () => ({+ UserRepository: MockUserRepository,+}));++vi.mock("@calcom/features/pbac/services/permission-check.service", () => ({+ PermissionCheckService: MockPermissionCheckService,+}));++vi.mock("@calcom/lib/getAvatarUrl", () => ({+ getUserAvatarUrl: vi.fn(() => "https://avatar.example.com/1"),+}));++vi.mock("@calcom/prisma", () => ({+ default: {+ secondaryEmail: {+ findMany: (...args: unknown[]) => mockFindMany(...args),+ },+ account: {+ findUnique: (...args: unknown[]) => mockFindUnique(...args),+ },+ user: {+ findUnique: vi.fn(),+ },+ },+}));++import { getHandler } from "./get.handler";++describe("getHandler - identity provider email lookup", () => {+ const baseUser = {+ id: 1,+ name: "Test User",+ email: "[email protected]",+ username: "testuser",+ emailVerified: new Date(),+ bufferTime: 0,+ locale: "en",+ timeFormat: 12,+ timeZone: "UTC",+ avatar: null,+ avatarUrl: null,+ createdDate: new Date(),+ trialEndsAt: null,+ defaultScheduleId: null,+ completedOnboarding: true,+ twoFactorEnabled: false,+ disableImpersonation: false,+ brandColor: "#000000",+ darkBrandColor: "#ffffff",+ bio: null,+ weekStart: "Monday",+ theme: null,+ appTheme: null,+ hideBranding: false,+ metadata: null,+ defaultBookerLayouts: null,+ allowDynamicBooking: true,+ allowSEOIndexing: true,+ receiveMonthlyDigestEmail: true,+ requiresBookerEmailVerification: false,+ role: "USER",+ organization: null,+ teams: [],+ };++ function createCtx(overrides: Partial<typeof baseUser> = {}) {+ return {+ user: { ...baseUser, ...overrides } as unknown as NonNullable<TrpcSessionUser>,+ session: { upId: "usr_1" } as any,+ };+ }++ beforeEach(() => {+ vi.clearAllMocks();++ mockFindAllProfilesForUserIncludingMovedUser.mockResolvedValue([]);+ mockEnrichUserWithTheProfile.mockImplementation(({ user }) => ({+ ...user,+ profile: null,+ }));+ mockFindMany.mockResolvedValue([]);+ mockGetTeamIdsWithPermission.mockResolvedValue([]);+ mockFindUnique.mockResolvedValue(null);+ });++ it("maps AZUREAD identity provider to 'azure-ad' in account lookup", async () => {+ const ctx = createCtx({+ identityProvider: IdentityProvider.AZUREAD,+ identityProviderId: "azure-provider-id-123",+ } as any);+ mockEnrichUserWithTheProfile.mockImplementation(({ user }) => ({+ ...user,+ identityProvider: IdentityProvider.AZUREAD,+ identityProviderId: "azure-provider-id-123",+ profile: null,+ }));+ mockFindUnique.mockResolvedValue({ providerEmail: "[email protected]" });++ const result = await getHandler({ ctx, input: {} });++ expect(mockFindUnique).toHaveBeenCalledWith(+ expect.objectContaining({+ where: {+ provider_providerAccountId: {+ provider: "azure-ad",+ providerAccountId: "azure-provider-id-123",+ },+ },+ })+ );+ expect(result.identityProviderEmail).toBe("[email protected]");+ });++ it("maps GOOGLE identity provider to 'google' in account lookup", async () => {+ const ctx = createCtx({+ identityProvider: IdentityProvider.GOOGLE,+ identityProviderId: "google-id-456",+ } as any);+ mockEnrichUserWithTheProfile.mockImplementation(({ user }) => ({+ ...user,+ identityProvider: IdentityProvider.GOOGLE,+ identityProviderId: "google-id-456",+ profile: null,+ }));+ mockFindUnique.mockResolvedValue({ providerEmail: "[email protected]" });++ const result = await getHandler({ ctx, input: {} });++ expect(mockFindUnique).toHaveBeenCalledWith(+ expect.objectContaining({+ where: {+ provider_providerAccountId: {+ provider: "google",+ providerAccountId: "google-id-456",+ },+ },+ })+ );+ expect(result.identityProviderEmail).toBe("[email protected]");+ });++ it("maps CAL identity provider to 'cal' in account lookup", async () => {+ const ctx = createCtx({+ identityProvider: IdentityProvider.CAL,+ identityProviderId: "cal-id-789",+ } as any);+ mockEnrichUserWithTheProfile.mockImplementation(({ user }) => ({+ ...user,+ identityProvider: IdentityProvider.CAL,+ identityProviderId: "cal-id-789",+ profile: null,+ }));+ mockFindUnique.mockResolvedValue(null);++ const result = await getHandler({ ctx, input: {} });++ expect(mockFindUnique).toHaveBeenCalledWith(+ expect.objectContaining({+ where: {+ provider_providerAccountId: {+ provider: "cal",+ providerAccountId: "cal-id-789",+ },+ },+ })+ );+ expect(result.identityProviderEmail).toBe("");+ });++ it("returns empty string when no account found", async () => {+ const ctx = createCtx({+ identityProvider: IdentityProvider.AZUREAD,+ identityProviderId: "nonexistent-id",+ } as any);+ mockEnrichUserWithTheProfile.mockImplementation(({ user }) => ({+ ...user,+ identityProvider: IdentityProvider.AZUREAD,+ identityProviderId: "nonexistent-id",+ profile: null,+ }));+ mockFindUnique.mockResolvedValue(null);++ const result = await getHandler({ ctx, input: {} });++ expect(result.identityProviderEmail).toBe("");+ });+});diff --git a/packages/trpc/server/routers/viewer/me/get.handler.ts b/packages/trpc/server/routers/viewer/me/get.handler.tsindex 0029ca0a2e7..9bfafd08920 100644--- a/packages/trpc/server/routers/viewer/me/get.handler.ts+++ b/packages/trpc/server/routers/viewer/me/get.handler.ts@@ -61,7 +61,10 @@ export const getHandler = async ({ ctx, input }: MeOptions) => {const account = await prisma.account.findUnique({where: {provider_providerAccountId: {- provider: user.identityProvider.toLocaleLowerCase(),+ provider:+ user.identityProvider === IdentityProvider.AZUREAD+ ? "azure-ad"+ : user.identityProvider.toLowerCase(),providerAccountId: user.identityProviderId,},},diff --git a/turbo.json b/turbo.jsonindex cf7697f8e4a..5e6b9e2708f 100644--- a/turbo.json+++ b/turbo.json@@ -252,6 +252,7 @@"CALCOM_ADMIN_API_KEY","NEXT_PUBLIC_SINGLE_ORG_MODE_ENABLED","CALCOM_SERVICE_ACCOUNT_ENCRYPTION_KEY",+ "OUTLOOK_LOGIN_ENABLED","CAL_VIDEO_RECORDING_TOKEN_SECRET","ORGANIZER_EMAIL_EXEMPT_DOMAINS","SLOTS_CACHE_TTL",