feat(auth): add env variable for oidc-name-attribute-overwrite (#1850)
This commit is contained in:
@@ -1,18 +1,10 @@
|
||||
import type { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
|
||||
import type { OIDCConfig } from "next-auth/providers";
|
||||
import type { OIDCConfig } from "@auth/core/providers";
|
||||
import type { Profile } from "@auth/core/types";
|
||||
|
||||
import { env } from "../../env.mjs";
|
||||
import { createRedirectUri } from "../../redirect";
|
||||
|
||||
interface Profile {
|
||||
sub: string;
|
||||
name: string;
|
||||
email: string;
|
||||
groups: string[];
|
||||
preferred_username: string;
|
||||
email_verified: boolean;
|
||||
}
|
||||
|
||||
export const OidcProvider = (headers: ReadonlyHeaders | null): OIDCConfig<Profile> => ({
|
||||
id: "oidc",
|
||||
name: env.AUTH_OIDC_CLIENT_NAME,
|
||||
@@ -28,12 +20,28 @@ export const OidcProvider = (headers: ReadonlyHeaders | null): OIDCConfig<Profil
|
||||
},
|
||||
},
|
||||
profile(profile) {
|
||||
if (!profile.sub) {
|
||||
throw new Error(`OIDC provider did not return a sub property='${Object.keys(profile).join(",")}'`);
|
||||
}
|
||||
const name = extractProfileName(profile);
|
||||
if (!name) {
|
||||
throw new Error(`OIDC provider did not return a name properties='${Object.keys(profile).join(",")}'`);
|
||||
}
|
||||
|
||||
return {
|
||||
id: profile.sub,
|
||||
// Use the name as the username if the preferred_username is an email address
|
||||
name: profile.preferred_username.includes("@") ? profile.name : profile.preferred_username,
|
||||
name,
|
||||
email: profile.email,
|
||||
provider: "oidc",
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const extractProfileName = (profile: Profile) => {
|
||||
if (!env.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE) {
|
||||
// Use the name as the username if the preferred_username is an email address
|
||||
return profile.preferred_username?.includes("@") ? profile.name : profile.preferred_username;
|
||||
}
|
||||
|
||||
return profile[env.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE as keyof typeof profile] as string;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user