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:
Anwar Sadathandzomars authored and GitHub committed 2024-04-10 14:38:39 -07:00
1 parent e30b41a85a
commit 4565c3311c
21 files changed
+270 -120

No files matched your search

@@ -72,7 +72,6 @@ export default function CalComAdapter(prismaClient: PrismaClient) {
}
},
linkAccount: (data: Prisma.AccountCreateInput) => prismaClient.account.create({ data }),
// @NOTE: All methods below here are not being used but leaved if they are required
unlinkAccount: (provider_providerAccountId: Prisma.AccountProviderProviderAccountIdCompoundUniqueInput) =>
prismaClient.account.delete({ where: { provider_providerAccountId } }),
};
@@ -1,5 +1,4 @@
import type { Membership, Team, UserPermissionRole } from "@prisma/client";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import type { AuthOptions, Session } from "next-auth";
import type { JWT } from "next-auth/jwt";
import { encode } from "next-auth/jwt";
@@ -130,13 +129,10 @@ const providers: Provider[] = [
identifier: user.email,
});
if (user.identityProvider !== IdentityProvider.CAL && !credentials.totpCode) {
throw new Error(ErrorCode.ThirdPartyIdentityProviderEnabled);
}
if (!user.password?.hash && user.identityProvider == IdentityProvider.CAL) {
if (!user.password?.hash && user.identityProvider !== IdentityProvider.CAL && !credentials.totpCode) {
throw new Error(ErrorCode.IncorrectEmailPassword);
}
if (!user.password?.hash && user.identityProvider !== IdentityProvider.CAL && !credentials.totpCode) {
if (!user.password?.hash && user.identityProvider == IdentityProvider.CAL) {
throw new Error(ErrorCode.IncorrectEmailPassword);
}
@@ -725,7 +721,11 @@ export const AUTH_OPTIONS: AuthOptions = {
try {
// If old user without Account entry we link their google account
if (existingUser.accounts.length === 0) {
const linkAccountWithUserData = { ...account, userId: existingUser.id };
const linkAccountWithUserData = {
...account,
userId: existingUser.id,
providerEmail: user.email,
};
await calcomAdapter.linkAccount(linkAccountWithUserData);
}
} catch (error) {
@@ -824,7 +824,7 @@ export const AUTH_OPTIONS: AuthOptions = {
existingUserWithEmail.identityProvider === IdentityProvider.CAL &&
(idP === IdentityProvider.GOOGLE || idP === IdentityProvider.SAML)
) {
const updatedUser = await prisma.user.update({
await prisma.user.update({
where: { email: existingUserWithEmail.email },
// also update email to the IdP email
data: {
@@ -834,22 +834,6 @@ export const AUTH_OPTIONS: AuthOptions = {
},
});
// safely delete password from UserPassword table if it exists
try {
await prisma.userPassword.delete({
where: { userId: updatedUser.id },
});
} catch (err) {
if (
err instanceof PrismaClientKnownRequestError &&
(err.code === "P2025" || err.code === "P2016")
) {
log.warn("UserPassword not found for user", safeStringify(existingUserWithEmail));
} else {
log.warn("Could not delete UserPassword for user", safeStringify(existingUserWithEmail));
}
}
if (existingUserWithEmail.twoFactorEnabled) {
return loginWithTotp(existingUserWithEmail.email);
} else {
@@ -886,7 +870,7 @@ export const AUTH_OPTIONS: AuthOptions = {
},
});
const linkAccountNewUserData = { ...account, userId: newUser.id };
const linkAccountNewUserData = { ...account, userId: newUser.id, providerEmail: user.email };
await calcomAdapter.linkAccount(linkAccountNewUserData);
if (account.twoFactorEnabled) {
@@ -138,7 +138,7 @@ const organizationRequiredKeys = ["organization"];
const useTabs = () => {
const session = useSession();
const { data: user } = trpc.viewer.me.useQuery();
const { data: user } = trpc.viewer.me.useQuery({ includePasswordAdded: true });
const orgBranding = useOrgBranding();
const isAdmin = session.data?.user.role === UserPermissionRole.ADMIN;
@@ -153,7 +153,8 @@ const useTabs = () => {
} else if (
tab.href === "/settings/security" &&
user?.identityProvider === IdentityProvider.GOOGLE &&
!user?.twoFactorEnabled
!user?.twoFactorEnabled &&
!user?.passwordAdded
) {
tab.children = tab?.children?.filter(
(childTab) => childTab.href !== "/settings/security/two-factor-auth"
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Account" ADD COLUMN "providerEmail" TEXT;
+1
View File
@@ -754,6 +754,7 @@ model Account {
type String
provider String
providerAccountId String
providerEmail String?
refresh_token String? @db.Text
access_token String? @db.Text
expires_at Int?
@@ -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 {};