widget chat 15

This commit is contained in:
Alma 2025-04-11 12:04:58 +02:00
parent 8d896cbd6e
commit 89d57cb093
2 changed files with 87 additions and 123 deletions

View File

@ -81,39 +81,36 @@ export const authOptions: NextAuthOptions = {
], ],
callbacks: { callbacks: {
async jwt({ token, account, profile }) { async jwt({ token, account, profile }) {
console.log('JWT callback called with:', { token, account, profile });
if (account && profile) { if (account && profile) {
// First set the basic token properties // Find or create a token for this user
const newToken = { const tokenName = `keycloak-${token.username}`;
...token, let personalToken: string | null = null;
accessToken: account.access_token || '', let rocketChatUserId: string | null = null;
refreshToken: account.refresh_token || '',
accessTokenExpires: account.expires_at! * 1000,
role: (profile as any).groups
?.filter((role: string) =>
!role.startsWith('default-roles-') &&
!['offline_access', 'uma_authorization'].includes(role)
) ?? [],
username: (profile as any).preferred_username ?? profile.email?.split('@')[0] ?? '',
first_name: (profile as any).given_name ?? '',
last_name: (profile as any).family_name ?? '',
rocketChatToken: '',
rocketChatUserId: '',
};
try { // First, get the user's Rocket.Chat ID
console.log('Attempting to get personal access tokens for user:', newToken.username); const userInfoResponse = await fetch(`https://parole.slm-lab.net/api/v1/users.info?username=${token.username}`, {
// First, let's verify the admin token is working
const verifyTokenResponse = await fetch('https://parole.slm-lab.net/api/v1/me', {
headers: { headers: {
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!, 'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
'X-User-Id': process.env.ROCKET_CHAT_USER_ID!, 'X-User-Id': process.env.ROCKET_CHAT_USER_ID!,
}, },
}); });
if (!verifyTokenResponse.ok) { if (!userInfoResponse.ok) {
console.error('Admin token verification failed'); console.error('Failed to get user info from Rocket.Chat');
return newToken; return token;
}
const userInfo = await userInfoResponse.json();
console.log('User info from Rocket.Chat:', userInfo);
if (userInfo.user && userInfo.user._id) {
rocketChatUserId = userInfo.user._id;
console.log('Found user ID:', rocketChatUserId);
} else {
console.error('No user ID found in Rocket.Chat response');
return token;
} }
// Get user's personal access tokens using admin credentials // Get user's personal access tokens using admin credentials
@ -128,41 +125,12 @@ export const authOptions: NextAuthOptions = {
if (!tokensResponse.ok) { if (!tokensResponse.ok) {
console.error('Failed to get personal access tokens'); console.error('Failed to get personal access tokens');
return newToken; return token;
} }
const tokensData = await tokensResponse.json(); const tokensData = await tokensResponse.json();
console.log('Parsed tokens data:', tokensData); console.log('Parsed tokens data:', tokensData);
// Find or create a token for this user
const tokenName = `keycloak-${newToken.username}`;
let personalToken: string | null = null;
let rocketChatUserId: string | null = null;
// First, get the user's Rocket.Chat ID
const userInfoResponse = await fetch(`https://parole.slm-lab.net/api/v1/users.info?username=${newToken.username}`, {
headers: {
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
'X-User-Id': process.env.ROCKET_CHAT_USER_ID!,
},
});
if (!userInfoResponse.ok) {
console.error('Failed to get user info from Rocket.Chat');
return newToken;
}
const userInfo = await userInfoResponse.json();
console.log('User info from Rocket.Chat:', userInfo);
if (userInfo.user && userInfo.user._id) {
rocketChatUserId = userInfo.user._id;
console.log('Found user ID:', rocketChatUserId);
} else {
console.error('No user ID found in Rocket.Chat response');
return newToken;
}
if (tokensData.tokens && tokensData.tokens.length > 0) { if (tokensData.tokens && tokensData.tokens.length > 0) {
// Use existing token // Use existing token
const existingToken = tokensData.tokens.find((t: any) => t.name === tokenName); const existingToken = tokensData.tokens.find((t: any) => t.name === tokenName);
@ -194,7 +162,7 @@ export const authOptions: NextAuthOptions = {
personalToken = createTokenData.token; personalToken = createTokenData.token;
} else { } else {
console.error('Failed to create personal access token'); console.error('Failed to create personal access token');
return newToken; return token;
} }
} }
@ -204,17 +172,13 @@ export const authOptions: NextAuthOptions = {
userId: rocketChatUserId userId: rocketChatUserId
}); });
return { return {
...newToken, ...token,
rocketChatToken: personalToken, rocketChatToken: personalToken,
rocketChatUserId: rocketChatUserId, rocketChatUserId: rocketChatUserId,
}; };
} }
return newToken; return token;
} catch (error) {
console.error('Error in Rocket.Chat authentication:', error);
return newToken;
}
} }
// Return previous token if not expired // Return previous token if not expired

View File

@ -12,8 +12,8 @@ declare module "next-auth" {
} & DefaultSession["user"]; } & DefaultSession["user"];
accessToken: string; accessToken: string;
refreshToken: string; refreshToken: string;
rocketChatToken: string; rocketChatToken: string | null;
rocketChatUserId: string; rocketChatUserId: string | null;
error?: string; error?: string;
} }
@ -25,8 +25,8 @@ declare module "next-auth" {
last_name: string; last_name: string;
username: string; username: string;
role: string[]; role: string[];
rocketChatToken: string; rocketChatToken: string | null;
rocketChatUserId: string; rocketChatUserId: string | null;
error?: string; error?: string;
} }