feat: basic support for Keycloak (OIDC)

This commit is contained in:
Tomáš Hruška
2023-11-09 11:41:08 +01:00
parent 518b94b1f4
commit 946eed3773
8 changed files with 122 additions and 10 deletions
+36 -3
View File
@@ -9,10 +9,16 @@ import { Adapter } from "next-auth/adapters";
import sendVerificationRequest from "@/lib/api/sendVerificationRequest";
import { Provider } from "next-auth/providers";
import verifySubscription from "@/lib/api/verifySubscription";
import KeycloakProvider from 'next-auth/providers/keycloak';
const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
const keycloakEnabled =
!!process.env.NEXT_PUBLIC_KEYCLOAK_ENABLED;
const adapter = PrismaAdapter(prisma);
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const providers: Provider[] = [
@@ -59,7 +65,7 @@ const providers: Provider[] = [
}),
];
if (emailEnabled)
if (emailEnabled) {
providers.push(
EmailProvider({
server: process.env.EMAIL_SERVER,
@@ -70,9 +76,36 @@ if (emailEnabled)
},
})
);
}
if (keycloakEnabled) {
providers.push(
KeycloakProvider({
id: 'keycloak',
name: 'Keycloak',
clientId: process.env.KEYCLOAK_CLIENT_ID!,
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,
issuer: process.env.KEYCLOAK_ISSUER,
profile: (profile) => {
return {
id: profile.sub,
username: profile.preferred_username,
name: profile.name ?? profile.preferred_username,
email: profile.email,
image: profile.picture,
};
},
}),
);
const _linkAccount = adapter.linkAccount;
adapter.linkAccount = (account) => {
const { 'not-before-policy': _, refresh_expires_in, ...data } = account;
return _linkAccount ? _linkAccount(data) : undefined;
};
}
export const authOptions: AuthOptions = {
adapter: PrismaAdapter(prisma) as Adapter,
adapter: adapter as Adapter,
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, // 30 days
@@ -85,7 +118,7 @@ export const authOptions: AuthOptions = {
callbacks: {
async jwt({ token, trigger, user }) {
token.sub = token.sub ? Number(token.sub) : undefined;
if (trigger === "signIn") token.id = user?.id as number;
if (trigger === "signIn" || trigger === "signUp") token.id = user?.id as number;
return token;
},