widget parole 3

This commit is contained in:
Alma 2025-04-13 00:12:49 +02:00
parent 5a5dc7990a
commit a29f81286e
3 changed files with 46 additions and 47 deletions

View File

@ -14,6 +14,8 @@ declare module "next-auth" {
role: string[]; role: string[];
}; };
accessToken: string; accessToken: string;
rocketChatToken: string | null;
rocketChatUserId: string | null;
} }
interface JWT { interface JWT {
@ -24,6 +26,8 @@ declare module "next-auth" {
username: string; username: string;
first_name: string; first_name: string;
last_name: string; last_name: string;
rocketChatToken: string | null;
rocketChatUserId: string | null;
} }
} }
@ -68,7 +72,6 @@ export const authOptions: NextAuthOptions = {
token.username = (profile as any).preferred_username ?? profile.email?.split('@')[0] ?? ''; token.username = (profile as any).preferred_username ?? profile.email?.split('@')[0] ?? '';
token.first_name = (profile as any).given_name ?? ''; token.first_name = (profile as any).given_name ?? '';
token.last_name = (profile as any).family_name ?? ''; token.last_name = (profile as any).family_name ?? '';
return token;
} }
// Return previous token if not expired // Return previous token if not expired
@ -110,6 +113,8 @@ export const authOptions: NextAuthOptions = {
accessToken: tokens.access_token, accessToken: tokens.access_token,
refreshToken: tokens.refresh_token ?? token.refreshToken, refreshToken: tokens.refresh_token ?? token.refreshToken,
accessTokenExpires: Date.now() + tokens.expires_in * 1000, accessTokenExpires: Date.now() + tokens.expires_in * 1000,
rocketChatToken: token.rocketChatToken || null,
rocketChatUserId: token.rocketChatUserId || null,
}; };
} catch (error) { } catch (error) {
console.error("Error refreshing token for user:", token.sub); console.error("Error refreshing token for user:", token.sub);
@ -118,6 +123,8 @@ export const authOptions: NextAuthOptions = {
return { return {
...token, ...token,
error: "RefreshAccessTokenError", error: "RefreshAccessTokenError",
rocketChatToken: null,
rocketChatUserId: null,
}; };
} }
}, },
@ -140,6 +147,11 @@ export const authOptions: NextAuthOptions = {
username: token.username ?? '', username: token.username ?? '',
role: token.role ?? [], role: token.role ?? [],
}; };
// Add Rocket.Chat credentials to session
session.rocketChatToken = token.rocketChatToken || null;
session.rocketChatUserId = token.rocketChatUserId || null;
return session; return session;
}, },
}, },

View File

@ -2,30 +2,34 @@ import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
// Helper function to create/refresh token // Helper function to get user token using admin credentials
async function ensureValidToken(baseUrl: string, userId: string, currentToken: string | null) { async function getUserToken(baseUrl: string) {
try { try {
// Try to create a new token // Step 1: Use admin token to authenticate
const tokenResponse = await fetch(`${baseUrl}/api/v1/users.createToken`, { const adminHeaders = {
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
'X-User-Id': process.env.ROCKET_CHAT_USER_ID!,
'Content-Type': 'application/json'
};
// Step 2: Create user token using admin credentials
const createTokenResponse = await fetch(`${baseUrl}/api/v1/users.createToken`, {
method: 'POST', method: 'POST',
headers: { headers: adminHeaders
'X-Auth-Token': currentToken || '',
'X-User-Id': userId,
},
}); });
if (tokenResponse.ok) { if (!createTokenResponse.ok) {
const tokenData = await tokenResponse.json(); console.error('Failed to create user token:', createTokenResponse.status);
return { return null;
token: tokenData.data.authToken,
userId: tokenData.data.userId,
};
} }
console.error('Failed to create/refresh token:', tokenResponse.status); const tokenData = await createTokenResponse.json();
return null; return {
authToken: tokenData.data.authToken,
userId: tokenData.data.userId
};
} catch (error) { } catch (error) {
console.error('Error creating/refreshing token:', error); console.error('Error getting user token:', error);
return null; return null;
} }
} }
@ -71,25 +75,20 @@ export async function GET(request: Request) {
}); });
} }
// Ensure we have valid token // Step 1 & 2: Get user token using admin credentials
const tokenInfo = await ensureValidToken( const userToken = await getUserToken(baseUrl);
baseUrl, if (!userToken) {
session.rocketChatUserId || '', return new Response(JSON.stringify({ error: 'Failed to create user token' }), {
session.rocketChatToken || null
);
if (!tokenInfo) {
return new Response(JSON.stringify({ error: 'Failed to authenticate with Rocket.Chat' }), {
status: 401, status: 401,
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
}); });
} }
// Get user's subscriptions with new token // Step 3: Use the user token to fetch subscriptions
const subscriptionsResponse = await fetch(`${baseUrl}/api/v1/subscriptions.get`, { const subscriptionsResponse = await fetch(`${baseUrl}/api/v1/subscriptions.get`, {
headers: { headers: {
'X-Auth-Token': tokenInfo.token, 'X-Auth-Token': userToken.authToken,
'X-User-Id': tokenInfo.userId, 'X-User-Id': userToken.userId,
}, },
}); });
@ -102,13 +101,11 @@ export async function GET(request: Request) {
} }
const subscriptionsData = await subscriptionsResponse.json(); const subscriptionsData = await subscriptionsResponse.json();
const userSubscriptions = subscriptionsData.update.filter((subscription: any) => const userSubscriptions = subscriptionsData.update;
subscription.t === 'd' ? subscription.rid.includes(tokenInfo.userId) : true
);
const messages: any[] = []; const messages: any[] = [];
const processedRooms = new Set(); const processedRooms = new Set();
// Step 3: Use the same user token to fetch messages
for (const subscription of userSubscriptions) { for (const subscription of userSubscriptions) {
if (messages.length >= 6 || processedRooms.has(subscription.rid)) continue; if (messages.length >= 6 || processedRooms.has(subscription.rid)) continue;
processedRooms.add(subscription.rid); processedRooms.add(subscription.rid);
@ -118,8 +115,8 @@ export async function GET(request: Request) {
`${baseUrl}/api/v1/chat.getMessage`, { `${baseUrl}/api/v1/chat.getMessage`, {
method: 'POST', method: 'POST',
headers: { headers: {
'X-Auth-Token': tokenInfo.token, 'X-Auth-Token': userToken.authToken,
'X-User-Id': tokenInfo.userId, 'X-User-Id': userToken.userId,
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({

View File

@ -34,16 +34,11 @@ export function Parole() {
if (isRefresh) { if (isRefresh) {
setRefreshing(true); setRefreshing(true);
} }
const response = await fetch('/api/rocket-chat/messages', { const response = await fetch('/api/rocket-chat/messages', {
cache: 'no-store', cache: 'no-store',
next: { revalidate: 0 }, next: { revalidate: 0 },
}); });
if (response.status === 401) {
// Handle authentication error
setError('Session expired. Please sign in again.');
return;
}
if (!response.ok) { if (!response.ok) {
const errorData = await response.json(); const errorData = await response.json();
@ -62,11 +57,6 @@ export function Parole() {
console.error('Error fetching messages:', err); console.error('Error fetching messages:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch messages'; const errorMessage = err instanceof Error ? err.message : 'Failed to fetch messages';
setError(errorMessage); setError(errorMessage);
// Clear polling if we have an authentication error
if (errorMessage.includes('Session expired')) {
return;
}
} finally { } finally {
setLoading(false); setLoading(false);
setRefreshing(false); setRefreshing(false);