From 47919e48c266b009cc179d795b0be61cff08d200 Mon Sep 17 00:00:00 2001 From: Vojtech Mares Date: Mon, 4 Sep 2023 08:51:42 +0200 Subject: [PATCH] fix(nextauth): drop custom Keycloak fields before saving in DB Keycloak response has more fields than we expect, therefore we cannot save the response, this commit removes the extra fields and allowsus to save to DB without an issue or a schema change (which is widely proposed on the internet, but I did not want to implement that) --- src/server/auth.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) 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,