feat: Implement the ability to login via multiple means when signed up via google/non-cal providers (#14082)
Co-authored-by: zomars <[email protected]>
This commit is contained in:
1 parent
e30b41a85a
commit
4565c3311c
21 files changed
+270
-120
No files matched your search
@@ -51,6 +51,7 @@ export async function getUserFromSession(ctx: TRPCContextInner, session: Maybe<S
|
||||
twoFactorEnabled: true,
|
||||
disableImpersonation: true,
|
||||
identityProvider: true,
|
||||
identityProviderId: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
away: true,
|
||||
|
||||
@@ -4,16 +4,20 @@ import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import type { TMeInputSchema } from "./me.schema";
|
||||
|
||||
type MeOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
session: Session;
|
||||
};
|
||||
input: TMeInputSchema;
|
||||
};
|
||||
|
||||
export const meHandler = async ({ ctx }: MeOptions) => {
|
||||
export const meHandler = async ({ ctx, input }: MeOptions) => {
|
||||
const crypto = await import("crypto");
|
||||
|
||||
const { user: sessionUser, session } = ctx;
|
||||
@@ -38,6 +42,35 @@ export const meHandler = async ({ ctx }: MeOptions) => {
|
||||
},
|
||||
});
|
||||
|
||||
let passwordAdded = false;
|
||||
if (user.identityProvider !== IdentityProvider.CAL && input?.includePasswordAdded) {
|
||||
const userWithPassword = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
select: {
|
||||
password: true,
|
||||
},
|
||||
});
|
||||
if (userWithPassword?.password?.hash) {
|
||||
passwordAdded = true;
|
||||
}
|
||||
}
|
||||
|
||||
let identityProviderEmail = "";
|
||||
if (user.identityProviderId) {
|
||||
const account = await prisma.account.findUnique({
|
||||
where: {
|
||||
provider_providerAccountId: {
|
||||
provider: user.identityProvider.toLocaleLowerCase(),
|
||||
providerAccountId: user.identityProviderId,
|
||||
},
|
||||
},
|
||||
select: { providerEmail: true },
|
||||
});
|
||||
identityProviderEmail = account?.providerEmail || "";
|
||||
}
|
||||
|
||||
// Destructuring here only makes it more illegible
|
||||
// pick only the part we want to expose in the API
|
||||
return {
|
||||
@@ -61,6 +94,7 @@ export const meHandler = async ({ ctx }: MeOptions) => {
|
||||
twoFactorEnabled: user.twoFactorEnabled,
|
||||
disableImpersonation: user.disableImpersonation,
|
||||
identityProvider: user.identityProvider,
|
||||
identityProviderEmail,
|
||||
brandColor: user.brandColor,
|
||||
darkBrandColor: user.darkBrandColor,
|
||||
away: user.away,
|
||||
@@ -80,5 +114,6 @@ export const meHandler = async ({ ctx }: MeOptions) => {
|
||||
profile: user.profile ?? null,
|
||||
profiles: allUserEnrichedProfiles,
|
||||
secondaryEmails,
|
||||
...(passwordAdded ? { passwordAdded } : {}),
|
||||
};
|
||||
};
|
||||
@@ -1 +1,9 @@
|
||||
export {};
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZMeInputSchema = z
|
||||
.object({
|
||||
includePasswordAdded: z.boolean().optional(),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export type TMeInputSchema = z.infer<typeof ZMeInputSchema>;
|
||||
@@ -1,7 +1,8 @@
|
||||
import authedProcedure from "../../../procedures/authedProcedure";
|
||||
import { ZMeInputSchema } from "../me.schema";
|
||||
|
||||
export const me = authedProcedure.query(async ({ ctx }) => {
|
||||
export const me = authedProcedure.input(ZMeInputSchema).query(async ({ ctx, input }) => {
|
||||
const handler = (await import("../me.handler")).meHandler;
|
||||
|
||||
return handler({ ctx });
|
||||
return handler({ ctx, input });
|
||||
});
|
||||
@@ -6,7 +6,6 @@ import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import stripe from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { getPremiumMonthlyPlanPriceId } from "@calcom/app-store/stripepayment/lib/utils";
|
||||
import { passwordResetRequest } from "@calcom/features/auth/lib/passwordResetRequest";
|
||||
import { sendChangeOfEmailVerification } from "@calcom/features/auth/lib/verifyEmail";
|
||||
import { getFeatureFlag } from "@calcom/features/flags/server/utils";
|
||||
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
|
||||
@@ -73,6 +72,9 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
const secondaryEmails = input?.secondaryEmails || [];
|
||||
delete input.secondaryEmails;
|
||||
|
||||
const unlinkConnectedAccount = input?.unlinkConnectedAccount || false;
|
||||
delete input.unlinkConnectedAccount;
|
||||
|
||||
const data: Prisma.UserUpdateInput = {
|
||||
...input,
|
||||
// DO NOT OVERWRITE AVATAR.
|
||||
@@ -81,9 +83,6 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
secondaryEmails: undefined,
|
||||
};
|
||||
|
||||
// some actions can invalidate a user session.
|
||||
let signOutUser = false;
|
||||
let passwordReset = false;
|
||||
let isPremiumUsername = false;
|
||||
|
||||
const layoutError = validateBookerLayouts(input?.metadata?.defaultBookerLayouts || null);
|
||||
@@ -142,11 +141,6 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
}
|
||||
const hasEmailBeenChanged = data.email && user.email !== data.email;
|
||||
|
||||
// check if we are changing email and identity provider is not CAL
|
||||
const hasEmailChangedOnNonCalProvider =
|
||||
hasEmailBeenChanged && user.identityProvider !== IdentityProvider.CAL;
|
||||
const hasEmailChangedOnCalProvider = hasEmailBeenChanged && user.identityProvider === IdentityProvider.CAL;
|
||||
|
||||
let secondaryEmail:
|
||||
| {
|
||||
id: number;
|
||||
@@ -166,7 +160,7 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
emailVerified: true,
|
||||
},
|
||||
});
|
||||
if (emailVerification && hasEmailChangedOnCalProvider) {
|
||||
if (emailVerification) {
|
||||
if (secondaryEmail?.emailVerified) {
|
||||
data.emailVerified = secondaryEmail.emailVerified;
|
||||
} else {
|
||||
@@ -186,7 +180,17 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
}
|
||||
}
|
||||
|
||||
if (hasEmailChangedOnNonCalProvider) {
|
||||
if (unlinkConnectedAccount) {
|
||||
// Unlink the account
|
||||
const CalComAdapter = (await import("@calcom/features/auth/lib/next-auth-custom-adapter")).default;
|
||||
const calcomAdapter = CalComAdapter(prisma);
|
||||
// If it fails to delete, don't stop because the users login data might not be present
|
||||
try {
|
||||
await calcomAdapter.unlinkAccount({
|
||||
provider: user.identityProvider.toLocaleLowerCase(),
|
||||
providerAccountId: user.identityProviderId || "",
|
||||
});
|
||||
} catch {}
|
||||
// Only validate if we're changing email
|
||||
data.identityProvider = IdentityProvider.CAL;
|
||||
data.identityProviderId = null;
|
||||
@@ -297,14 +301,6 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
});
|
||||
}
|
||||
|
||||
if (hasEmailChangedOnNonCalProvider) {
|
||||
// Because the email has changed, we are now attempting to use the CAL provider-
|
||||
// which has no password yet. We have to send the reset password email.
|
||||
await passwordResetRequest(updatedUser);
|
||||
signOutUser = true;
|
||||
passwordReset = true;
|
||||
}
|
||||
|
||||
// Sync Services
|
||||
await syncServicesUpdateWebUser(updatedUser);
|
||||
|
||||
@@ -320,7 +316,7 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
});
|
||||
}
|
||||
|
||||
if (updatedUser && hasEmailChangedOnCalProvider) {
|
||||
if (updatedUser) {
|
||||
// Skip sending verification email when user tries to change his primary email to a verified secondary email
|
||||
if (secondaryEmail?.emailVerified) {
|
||||
secondaryEmails.push({
|
||||
@@ -398,12 +394,7 @@ export const updateProfileHandler = async ({ ctx, input }: UpdateProfileOptions)
|
||||
|
||||
return {
|
||||
...input,
|
||||
email:
|
||||
emailVerification && hasEmailChangedOnCalProvider && !secondaryEmail?.emailVerified
|
||||
? user.email
|
||||
: input.email,
|
||||
signOutUser,
|
||||
passwordReset,
|
||||
email: emailVerification && !secondaryEmail?.emailVerified ? user.email : input.email,
|
||||
avatarUrl: updatedUser.avatarUrl,
|
||||
hasEmailBeenChanged,
|
||||
sendEmailVerification: emailVerification && !secondaryEmail?.emailVerified,
|
||||
|
||||
@@ -38,6 +38,7 @@ export const ZUpdateProfileInputSchema = z.object({
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
unlinkConnectedAccount: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type TUpdateProfileInputSchema = z.infer<typeof ZUpdateProfileInputSchema>;
|
||||
@@ -15,6 +15,7 @@ type AuthRouterHandlerCache = {
|
||||
resendVerifyEmail?: typeof import("./resendVerifyEmail.handler").resendVerifyEmail;
|
||||
sendVerifyEmailCode?: typeof import("./sendVerifyEmailCode.handler").sendVerifyEmailCodeHandler;
|
||||
resendVerifySecondaryEmail?: typeof import("./resendVerifyEmail.handler").resendVerifyEmail;
|
||||
createAccountPassword?: typeof import("./createAccountPassword.handler").createAccountPasswordHandler;
|
||||
};
|
||||
|
||||
const UNSTABLE_HANDLER_CACHE: AuthRouterHandlerCache = {};
|
||||
@@ -107,4 +108,21 @@ export const authRouter = router({
|
||||
ctx,
|
||||
});
|
||||
}),
|
||||
|
||||
createAccountPassword: authedProcedure.mutation(async ({ ctx }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.createAccountPassword) {
|
||||
UNSTABLE_HANDLER_CACHE.createAccountPassword = await import("./createAccountPassword.handler").then(
|
||||
(mod) => mod.createAccountPasswordHandler
|
||||
);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.createAccountPassword) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.createAccountPassword({
|
||||
ctx,
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -22,7 +22,17 @@ export const changePasswordHandler = async ({ input, ctx }: ChangePasswordOption
|
||||
const { user } = ctx;
|
||||
|
||||
if (user.identityProvider !== IdentityProvider.CAL) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "THIRD_PARTY_IDENTITY_PROVIDER_ENABLED" });
|
||||
const userWithPassword = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
select: {
|
||||
password: true,
|
||||
},
|
||||
});
|
||||
if (!userWithPassword?.password?.hash) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "THIRD_PARTY_IDENTITY_PROVIDER_ENABLED" });
|
||||
}
|
||||
}
|
||||
|
||||
const currentPasswordQuery = await prisma.userPassword.findFirst({
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { passwordResetRequest } from "@calcom/features/auth/lib/passwordResetRequest";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider } from "@calcom/prisma/enums";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TrpcSessionUser } from "../../../trpc";
|
||||
|
||||
type CreateAccountPasswordOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
};
|
||||
|
||||
export const createAccountPasswordHandler = async ({ ctx }: CreateAccountPasswordOptions) => {
|
||||
const { user } = ctx;
|
||||
|
||||
const isCal = user.identityProvider === IdentityProvider.CAL;
|
||||
if (isCal) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "cannot_create_account_password_cal_provider" });
|
||||
}
|
||||
|
||||
const userWithPassword = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
select: {
|
||||
password: true,
|
||||
},
|
||||
});
|
||||
if (!isCal && userWithPassword?.password?.hash) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "cannot_create_account_password_already_existing" });
|
||||
}
|
||||
|
||||
await passwordResetRequest(user);
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
Reference in new issue
Block a user