working leantime widget 39

This commit is contained in:
Alma 2025-04-12 14:36:35 +02:00
parent cd7ff20e03
commit b4cfe735ed

View File

@ -27,13 +27,22 @@ declare module "next-auth" {
} }
} }
function getRequiredEnvVar(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
export const authOptions: NextAuthOptions = { export const authOptions: NextAuthOptions = {
providers: [ providers: [
KeycloakProvider({ KeycloakProvider({
clientId: process.env.KEYCLOAK_CLIENT_ID!, clientId: getRequiredEnvVar("KEYCLOAK_CLIENT_ID"),
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!, clientSecret: getRequiredEnvVar("KEYCLOAK_CLIENT_SECRET"),
issuer: process.env.KEYCLOAK_ISSUER!, issuer: getRequiredEnvVar("KEYCLOAK_ISSUER"),
profile(profile) { profile(profile) {
console.log("Keycloak profile:", profile);
return { return {
id: profile.sub, id: profile.sub,
name: profile.name ?? profile.preferred_username, name: profile.name ?? profile.preferred_username,
@ -48,6 +57,10 @@ export const authOptions: NextAuthOptions = {
], ],
callbacks: { callbacks: {
async jwt({ token, account, profile }) { async jwt({ token, account, profile }) {
console.log("JWT callback - token:", token);
console.log("JWT callback - account:", account);
console.log("JWT callback - profile:", profile);
if (account && profile) { if (account && profile) {
token.accessToken = account.access_token; token.accessToken = account.access_token;
token.refreshToken = account.refresh_token; token.refreshToken = account.refresh_token;
@ -66,21 +79,10 @@ export const authOptions: NextAuthOptions = {
try { try {
// Token has expired, try to refresh it // Token has expired, try to refresh it
function isNonEmptyString(value: string | undefined): value is string { const clientId = getRequiredEnvVar("KEYCLOAK_CLIENT_ID");
return typeof value === 'string' && value.length > 0; const clientSecret = getRequiredEnvVar("KEYCLOAK_CLIENT_SECRET");
}
const clientId = process.env.KEYCLOAK_CLIENT_ID;
const clientSecret = process.env.KEYCLOAK_CLIENT_SECRET;
if (!isNonEmptyString(clientId) || !isNonEmptyString(clientSecret)) {
throw new Error("Missing required environment variables for token refresh");
}
// After the type guard check, we can safely assert these as strings
const validClientId = clientId as string;
const validClientSecret = clientSecret as string;
console.log("Attempting to refresh token...");
const response = await fetch( const response = await fetch(
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`, `${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`,
{ {
@ -90,14 +92,15 @@ export const authOptions: NextAuthOptions = {
}, },
body: new URLSearchParams({ body: new URLSearchParams({
grant_type: "refresh_token", grant_type: "refresh_token",
client_id: validClientId, client_id: clientId,
client_secret: validClientSecret, client_secret: clientSecret,
refresh_token: token.refreshToken as string, refresh_token: token.refreshToken as string,
}), }),
} }
); );
const tokens = await response.json(); const tokens = await response.json();
console.log("Token refresh response:", tokens);
if (!response.ok) { if (!response.ok) {
console.error("Token refresh failed:", tokens); console.error("Token refresh failed:", tokens);
@ -122,7 +125,11 @@ export const authOptions: NextAuthOptions = {
}, },
async session({ session, token }) { async session({ session, token }) {
console.log("Session callback - session:", session);
console.log("Session callback - token:", token);
if (token.error) { if (token.error) {
console.error("Token error detected:", token.error);
// Force sign out if there was a refresh error // Force sign out if there was a refresh error
throw new Error("RefreshAccessTokenError"); throw new Error("RefreshAccessTokenError");
} }
@ -141,6 +148,7 @@ export const authOptions: NextAuthOptions = {
}, },
events: { events: {
async signOut({ token }) { async signOut({ token }) {
console.log("Sign out event - token:", token);
if (token.refreshToken) { if (token.refreshToken) {
try { try {
await fetch( await fetch(
@ -151,8 +159,8 @@ export const authOptions: NextAuthOptions = {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
}, },
body: new URLSearchParams({ body: new URLSearchParams({
client_id: process.env.KEYCLOAK_CLIENT_ID!, client_id: getRequiredEnvVar("KEYCLOAK_CLIENT_ID"),
client_secret: process.env.KEYCLOAK_CLIENT_SECRET!, client_secret: getRequiredEnvVar("KEYCLOAK_CLIENT_SECRET"),
refresh_token: token.refreshToken as string, refresh_token: token.refreshToken as string,
}), }),
} }
@ -163,6 +171,7 @@ export const authOptions: NextAuthOptions = {
} }
}, },
}, },
debug: true, // Enable debug logging
}; };
const handler = NextAuth(authOptions); const handler = NextAuth(authOptions);