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:
parent
0f7fee21e0
commit
47919e48c2
1 changed files with 18 additions and 1 deletions
|
|
@ -6,6 +6,7 @@ import {
|
||||||
type DefaultSession,
|
type DefaultSession,
|
||||||
} from "next-auth";
|
} from "next-auth";
|
||||||
import KeycloakProvider from "next-auth/providers/keycloak";
|
import KeycloakProvider from "next-auth/providers/keycloak";
|
||||||
|
import { type AdapterAccount } from "next-auth/adapters";
|
||||||
import { type JWT } from "next-auth/jwt";
|
import { type JWT } from "next-auth/jwt";
|
||||||
import { env } from "~/env.mjs";
|
import { env } from "~/env.mjs";
|
||||||
import { prisma } from "~/server/db";
|
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.
|
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
|
||||||
*
|
*
|
||||||
|
|
@ -72,7 +89,7 @@ export const authOptions: NextAuthOptions = {
|
||||||
return token
|
return token
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
adapter: PrismaAdapter(prisma),
|
adapter: adapter,
|
||||||
providers: [
|
providers: [
|
||||||
KeycloakProvider({
|
KeycloakProvider({
|
||||||
clientId: env.KEYCLOAK_CLIENT_ID,
|
clientId: env.KEYCLOAK_CLIENT_ID,
|
||||||
|
|
|
||||||
Reference in a new issue