Fix/login with provider (#2594)

This commit is contained in:
alannnc authored and GitHub committed 2022-04-26 15:12:08 +00:00
1 parent fa1b29a99f
commit c22b6ca670
5 files changed
+189 -5

No files matched your search

+30 -5
View File
@@ -18,6 +18,7 @@ import { serverConfig } from "@calcom/lib/serverConfig";
import ImpersonationProvider from "@ee/lib/impersonation/ImpersonationProvider";
import { ErrorCode, verifyPassword } from "@lib/auth";
import CalComAdapter from "@lib/auth/next-auth-custom-adapter";
import prisma from "@lib/prisma";
import { randomString } from "@lib/random";
import { hostedCal, isSAMLLoginEnabled, samlLoginUrl } from "@lib/saml";
@@ -185,9 +186,10 @@ if (true) {
})
);
}
const calcomAdapter = CalComAdapter(prisma);
export default NextAuth({
adapter: PrismaAdapter(prisma),
// @ts-ignore
adapter: calcomAdapter,
session: {
strategy: "jwt",
},
@@ -246,7 +248,6 @@ export default NextAuth({
if (account.provider === "saml") {
idP = IdentityProvider.SAML;
}
const existingUser = await prisma.user.findFirst({
where: {
AND: [
@@ -292,6 +293,7 @@ export default NextAuth({
},
async signIn(params) {
const { user, account, profile } = params;
if (account.provider === "email") {
return true;
}
@@ -323,10 +325,20 @@ export default NextAuth({
if (!user.email_verified) {
return "/auth/error?error=unverified-email";
}
// Only google oauth on this path
const provider = account.provider.toUpperCase() as IdentityProvider;
const existingUser = await prisma.user.findFirst({
include: {
accounts: {
where: {
provider: account.provider,
},
},
},
where: {
AND: [{ identityProvider: idP }, { identityProviderId: user.id as string }],
identityProvider: provider,
identityProviderId: account.providerAccountId,
},
});
@@ -334,6 +346,17 @@ export default NextAuth({
// In this case there's an existing user and their email address
// hasn't changed since they last logged in.
if (existingUser.email === user.email) {
try {
// If old user without Account entry we link their google account
if (existingUser.accounts.length === 0) {
const linkAccountWithUserData = { ...account, userId: existingUser.id };
await calcomAdapter.linkAccount(linkAccountWithUserData);
}
} catch (error) {
if (error instanceof Error) {
console.error("Error while linking account of already existing user");
}
}
return true;
}
@@ -394,7 +417,7 @@ export default NextAuth({
return "/auth/error?error=use-identity-login";
}
await prisma.user.create({
const newUser = await prisma.user.create({
data: {
// Slugify the incoming name and append a few random characters to
// prevent conflicts for users with the same name.
@@ -406,6 +429,8 @@ export default NextAuth({
identityProviderId: user.id as string,
},
});
const linkAccountNewUserData = { ...account, userId: newUser.id };
await calcomAdapter.linkAccount(linkAccountNewUserData);
return true;
}