feat: enable microsoft sign ups (#28080)

* fix: trigger lingo.dev by removing duplicate value

* under progress

* wow this worked

* migrate schema

* fix types

* fix import for google login

* Add onboarding tests for Azure (Microsoft sign up)

* add comments back

* fix failing test

* fix: update Outlook login configuration and improve type safety in authentication adapter

- Set OUTLOOK_LOGIN_ENABLED to false in .env.example
- Refactor getServerSideProps to directly use samlTenantID and samlProductID
- Update linkAccount method in next-auth-custom-adapter for better type handling
- Remove redundant comment in next-auth-options related to Azure AD email verification

* remove log

* remove debug log from signin callback in next-auth options

* fixup

* chore: standardize naming

* chore: add primary calendar for outlook, verify email and auto link org for outlook

* chore: helper fns

* chore: implement cubic feedback

* cleanup

* chore: implement cubic feedback again

* WIP design#

* feat: login design

* fix: map identity provider names correctly

* 32px of mt

* fix: login UI

* fix: type check

* fix: fix type check again

* chore: update OAuth login tests

* fixup

* fix: bad import

* chore: update tests

* fixup

* fix: locales test

* chore: implement PR feedback and fix minor issues

* fix: revert token spreading change

* fix: merge conflicts

* chore: revert signup view changes

* fixup: bring back reverted changes because of merge conflicts

* fix: disable email input when microsoft sign in is in progress

* chore: implement cubic feedback

* cleanup: unused variables

* fix: address Cubic AI review feedback (confidence >= 9/10)

- Remove userId (PII) from log payloads in updateProfilePhotoMicrosoft.ts
- Replace text selectors with data-testid in locale.e2e.ts and oauth-provider.e2e.ts
- Restore callbackUrl redirect parameter in signup link in login-view.tsx
- Add data-testid='login-subtitle' to login page subtitle element

Co-Authored-By: unknown <>

* fix: use empty alt for decorative icon images in login view

MicrosoftIcon and GoogleIcon are decorative (adjacent to text labels),
so they should have empty alt attributes per accessibility best practices.

Co-Authored-By: unknown <>

* chore: implement cubic feedback

* cleanup

* fixup

* chore: implement PR feedback

* chore: implement feedback

* fix: address PR review feedback - type safety and centralize constants

- Replace non-null assertions (!) with proper null checks for OUTLOOK_CLIENT_ID/SECRET
- Replace `as any` casting with `Record<string, unknown>` for OAuth profile claims
- Remove non-null assertion on account.access_token by adding conditional check
- Centralize Outlook env constants in @calcom/lib/constants alongside MICROSOFT_CALENDAR_SCOPES
- Add explanatory comment for getNextAuthProviderName usage in get.handler.ts

Co-Authored-By: unknown <>

* Revert "fix: address PR review feedback - type safety and centralize constants"

This reverts commit 91ace141e6a28a23deea5897f7f9d6ad80319d84.

* chore: implement feedback

* chore: cleanup

* chore: implement feedback

* fix: merge conflicts

* fix: revert formatting-only changes in packages/lib/constants.ts

Co-Authored-By: unknown <>

* fix: revert IdentityProvider enum location change in schema.prisma

Co-Authored-By: unknown <>

* chore: implement more PR feedback

* fix: restore database-derived profileId from determineProfile in OAuth JWT

The profileId regression was identified by Cubic AI (confidence 9/10).

Previously, determineProfile's returned id was used to set profileId in the
JWT via 'profileResult.id ?? token.profileId ?? null'. A recent refactor
changed this to 'token.profileId ?? null', which drops the database-derived
profile ID. On first OAuth login (or when profile switcher is disabled),
token.profileId is likely null, so profileId would incorrectly be set to
null even though determineProfile returned a valid profile with an id.

This commit restores the correct priority chain:
  visitorProfileId ?? token.profileId ?? null

Co-Authored-By: bot_apk <[email protected]>

* refactor: revert pure formatting and import reordering changes

Co-Authored-By: [email protected] <[email protected]>

* fix: normalize determineProfile return type to use consistent 'id' field

The determineProfile function returned a union type where one branch used
'id' and the other used 'profileId'. This caused TS2339 when destructuring
'id' from the result. Normalize the token.upId branch to also return 'id'
(mapped from token.profileId) so the return type is consistent.

Co-Authored-By: bot_apk <[email protected]>

* chore: add tests

* reveret: profileId changes should be in a separate PR

* fix: avoid logging entire existingUser object in OAuth JWT callback

Revert to logging only { userId, upId } instead of the full existingUser
object, which contains PII (email, name, identity provider details).
This restores the previous safe logging pattern.

Co-Authored-By: bot_apk <[email protected]>

* chore: remove profileId related tests

---------

Co-authored-by: amrit <[email protected]>
Co-authored-by: Devanshu Sharma <[email protected]>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Sean Brydon <[email protected]>
Co-authored-by: bot_apk <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-03-05 16:47:40 +05:30
1 parent b7340f7151
commit e2add3f2c9
31 files changed
+2602 -347

No files matched your search

@@ -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();
});
});
});
@@ -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;
};
File diff suppressed because it is too large. Load diff
+276 -82
View File
@@ -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/UserReposito
import { 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 here
const 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-ignore
adapter: 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-merge
if (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 email
if (
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 accounts
if (!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
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, "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
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 AD
const { 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.
@@ -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);
});
});
+8
View File
@@ -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"
);