1
0
Fork 0

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)
This commit is contained in:
Vojtěch Mareš 2023-09-04 08:51:42 +02:00
parent 0f7fee21e0
commit 47919e48c2
Signed by: vojtech.mares
GPG key ID: C6827B976F17240D

View file

@ -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,