diff --git a/src/server/auth.ts b/src/server/auth.ts index b1d7f7a..fb0d6f3 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -6,6 +6,7 @@ import { type DefaultSession, } from "next-auth"; import KeycloakProvider from "next-auth/providers/keycloak"; +import { type AdapterAccount } from "next-auth/adapters"; import { type JWT } from "next-auth/jwt"; import { env } from "~/env.mjs"; import { prisma } from "~/server/db"; @@ -43,6 +44,22 @@ declare module 'next-auth/jwt' { } } +const adapter = PrismaAdapter(prisma); +const originLinkAccount = adapter.linkAccount; + +/** + * This method override handles Keycloak response with fields we are not expecting, + * as a part of the response and we have no database fields for them, + * which caused error on writing data to database. + * + * @see https://stackoverflow.com/questions/69910570/prisma-with-next-auth-user-creation-fails-cause-of-keycloaks-api-response-key + */ +adapter.linkAccount = (account: AdapterAccount) => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { 'not-before-policy': _, refresh_expires_in, ...data } = account; + return originLinkAccount(data); +} + /** * Options for NextAuth.js used to configure adapters, providers, callbacks, etc. * @@ -72,7 +89,7 @@ export const authOptions: NextAuthOptions = { return token }, }, - adapter: PrismaAdapter(prisma), + adapter: adapter, providers: [ KeycloakProvider({ clientId: env.KEYCLOAK_CLIENT_ID,