widget chat 16
This commit is contained in:
parent
89d57cb093
commit
3b6b149d41
@ -84,13 +84,8 @@ export const authOptions: NextAuthOptions = {
|
|||||||
console.log('JWT callback called with:', { token, account, profile });
|
console.log('JWT callback called with:', { token, account, profile });
|
||||||
|
|
||||||
if (account && profile) {
|
if (account && profile) {
|
||||||
// Find or create a token for this user
|
|
||||||
const tokenName = `keycloak-${token.username}`;
|
|
||||||
let personalToken: string | null = null;
|
|
||||||
let rocketChatUserId: string | null = null;
|
|
||||||
|
|
||||||
// First, get the user's Rocket.Chat ID
|
// First, get the user's Rocket.Chat ID
|
||||||
const userInfoResponse = await fetch(`https://parole.slm-lab.net/api/v1/users.info?username=${token.username}`, {
|
const userInfoResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.info?username=${token.username}`, {
|
||||||
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!,
|
||||||
@ -105,16 +100,16 @@ export const authOptions: NextAuthOptions = {
|
|||||||
const userInfo = await userInfoResponse.json();
|
const userInfo = await userInfoResponse.json();
|
||||||
console.log('User info from Rocket.Chat:', userInfo);
|
console.log('User info from Rocket.Chat:', userInfo);
|
||||||
|
|
||||||
if (userInfo.user && userInfo.user._id) {
|
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');
|
console.error('No user ID found in Rocket.Chat response');
|
||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get user's personal access tokens using admin credentials
|
const rocketChatUserId = userInfo.user._id;
|
||||||
const tokensResponse = await fetch('https://parole.slm-lab.net/api/v1/users.getPersonalAccessTokens', {
|
console.log('Found user ID:', rocketChatUserId);
|
||||||
|
|
||||||
|
// Get user's personal access tokens
|
||||||
|
const tokensResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.getPersonalAccessTokens`, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
|
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
|
||||||
@ -131,8 +126,10 @@ export const authOptions: NextAuthOptions = {
|
|||||||
const tokensData = await tokensResponse.json();
|
const tokensData = await tokensResponse.json();
|
||||||
console.log('Parsed tokens data:', tokensData);
|
console.log('Parsed tokens data:', tokensData);
|
||||||
|
|
||||||
|
let personalToken = null;
|
||||||
|
const tokenName = `keycloak-${token.username}`;
|
||||||
|
|
||||||
if (tokensData.tokens && tokensData.tokens.length > 0) {
|
if (tokensData.tokens && tokensData.tokens.length > 0) {
|
||||||
// Use existing token
|
|
||||||
const existingToken = tokensData.tokens.find((t: any) => t.name === tokenName);
|
const existingToken = tokensData.tokens.find((t: any) => t.name === tokenName);
|
||||||
if (existingToken) {
|
if (existingToken) {
|
||||||
console.log('Found existing token:', existingToken);
|
console.log('Found existing token:', existingToken);
|
||||||
@ -142,8 +139,7 @@ export const authOptions: NextAuthOptions = {
|
|||||||
|
|
||||||
if (!personalToken) {
|
if (!personalToken) {
|
||||||
console.log('Creating new personal access token');
|
console.log('Creating new personal access token');
|
||||||
// Create new token
|
const createTokenResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.generatePersonalAccessToken`, {
|
||||||
const createTokenResponse = await fetch('https://parole.slm-lab.net/api/v1/users.generatePersonalAccessToken', {
|
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
|
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
|
||||||
|
|||||||
@ -2,162 +2,108 @@ 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";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(request: Request) {
|
||||||
try {
|
const session = await getServerSession(authOptions);
|
||||||
const session = await getServerSession(authOptions);
|
|
||||||
if (!session) {
|
|
||||||
console.error('No session found');
|
|
||||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Session data:', {
|
if (!session) {
|
||||||
|
console.error('No session found');
|
||||||
|
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
|
||||||
|
status: 401,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Session data:', {
|
||||||
|
hasToken: !!session.rocketChatToken,
|
||||||
|
hasUserId: !!session.rocketChatUserId,
|
||||||
|
tokenLength: session.rocketChatToken?.length,
|
||||||
|
userIdLength: session.rocketChatUserId?.length,
|
||||||
|
username: session.user?.username
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!session.rocketChatToken || !session.rocketChatUserId) {
|
||||||
|
console.error('Missing Rocket.Chat credentials in session:', {
|
||||||
hasToken: !!session.rocketChatToken,
|
hasToken: !!session.rocketChatToken,
|
||||||
hasUserId: !!session.rocketChatUserId,
|
hasUserId: !!session.rocketChatUserId,
|
||||||
tokenLength: session.rocketChatToken?.length,
|
username: session.user?.username
|
||||||
userIdLength: session.rocketChatUserId?.length
|
});
|
||||||
|
return new Response(JSON.stringify({ error: 'Missing Rocket.Chat credentials' }), {
|
||||||
|
status: 401,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Get user's subscriptions
|
||||||
|
const subscriptionsResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/subscriptions.get`, {
|
||||||
|
headers: {
|
||||||
|
'X-Auth-Token': session.rocketChatToken,
|
||||||
|
'X-User-Id': session.rocketChatUserId,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get the user's Rocket.Chat token from their session
|
|
||||||
const rocketChatToken = session.rocketChatToken;
|
|
||||||
const rocketChatUserId = session.rocketChatUserId;
|
|
||||||
|
|
||||||
if (!rocketChatToken || !rocketChatUserId) {
|
|
||||||
console.error('Missing Rocket.Chat credentials in session:', {
|
|
||||||
hasToken: !!rocketChatToken,
|
|
||||||
hasUserId: !!rocketChatUserId,
|
|
||||||
session: session
|
|
||||||
});
|
|
||||||
return NextResponse.json({ error: "User not authenticated with Rocket.Chat" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the user's subscriptions (rooms they are in)
|
|
||||||
const subscriptionsResponse = await fetch(
|
|
||||||
'https://parole.slm-lab.net/api/v1/subscriptions.get',
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'X-Auth-Token': rocketChatToken,
|
|
||||||
'X-User-Id': rocketChatUserId,
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!subscriptionsResponse.ok) {
|
if (!subscriptionsResponse.ok) {
|
||||||
console.error('Rocket.Chat subscriptions error:', {
|
console.error('Failed to get subscriptions:', {
|
||||||
status: subscriptionsResponse.status,
|
status: subscriptionsResponse.status,
|
||||||
statusText: subscriptionsResponse.statusText,
|
statusText: subscriptionsResponse.statusText,
|
||||||
response: await subscriptionsResponse.text().catch(() => 'Could not get response text')
|
username: session.user?.username
|
||||||
|
});
|
||||||
|
return new Response(JSON.stringify({ error: 'Failed to get subscriptions' }), {
|
||||||
|
status: subscriptionsResponse.status,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
});
|
});
|
||||||
return NextResponse.json(
|
|
||||||
{ error: "Failed to fetch subscriptions" },
|
|
||||||
{ status: subscriptionsResponse.status }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const subscriptions = await subscriptionsResponse.json();
|
const subscriptionsData = await subscriptionsResponse.json();
|
||||||
console.log('Subscriptions response:', subscriptions);
|
console.log('Subscriptions response:', subscriptionsData);
|
||||||
|
|
||||||
if (!subscriptions.update || subscriptions.update.length === 0) {
|
const messages: any[] = [];
|
||||||
console.log('No subscriptions found');
|
|
||||||
return NextResponse.json({ messages: [] });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the last message from each room
|
for (const subscription of subscriptionsData.update) {
|
||||||
const messages = await Promise.all(
|
console.log(`Fetching messages for room ${subscription.name} using endpoint ${subscription.t === 'c' ? 'channels.messages' : 'im.messages'}`);
|
||||||
subscriptions.update.map(async (subscription: any) => {
|
|
||||||
try {
|
|
||||||
if (!subscription.rid) {
|
|
||||||
console.log('No room ID found for subscription:', subscription);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Choose the appropriate endpoint based on room type
|
const endpoint = subscription.t === 'c' ? 'channels.messages' : 'im.messages';
|
||||||
const endpoint = subscription.t === 'd'
|
const roomId = subscription.t === 'c' ? subscription.name : subscription.rid;
|
||||||
? 'im.messages'
|
|
||||||
: subscription.t === 'c'
|
|
||||||
? 'channels.messages'
|
|
||||||
: 'groups.messages';
|
|
||||||
|
|
||||||
console.log(`Fetching messages for room ${subscription.name} using endpoint ${endpoint}`);
|
const messagesResponse = await fetch(
|
||||||
|
`${process.env.ROCKET_CHAT_URL}/api/v1/${endpoint}?roomId=${roomId}`,
|
||||||
// Get the most recent messages from the room using the user's personal access token
|
{
|
||||||
const messagesResponse = await fetch(
|
headers: {
|
||||||
`https://parole.slm-lab.net/api/v1/${endpoint}?roomId=${subscription.rid}&count=1`,
|
'X-Auth-Token': session.rocketChatToken,
|
||||||
{
|
'X-User-Id': session.rocketChatUserId,
|
||||||
headers: {
|
},
|
||||||
'X-Auth-Token': rocketChatToken,
|
|
||||||
'X-User-Id': rocketChatUserId,
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!messagesResponse.ok) {
|
|
||||||
console.error('Failed to fetch messages:', {
|
|
||||||
roomId: subscription.rid,
|
|
||||||
endpoint,
|
|
||||||
status: messagesResponse.status,
|
|
||||||
response: await messagesResponse.text().catch(() => 'Could not get response text')
|
|
||||||
});
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const messagesData = await messagesResponse.json();
|
|
||||||
console.log(`Messages response for ${subscription.name}:`, {
|
|
||||||
count: messagesData.messages?.length,
|
|
||||||
success: messagesData.success
|
|
||||||
});
|
|
||||||
|
|
||||||
if (messagesData.messages && messagesData.messages.length > 0) {
|
|
||||||
const message = messagesData.messages[0];
|
|
||||||
|
|
||||||
// For direct messages, check if the room ID contains the user's ID
|
|
||||||
if (subscription.t === 'd') {
|
|
||||||
// Extract the other user's ID from the room ID
|
|
||||||
const roomIdParts = subscription.rid.split(rocketChatUserId);
|
|
||||||
const otherUserId = roomIdParts[0] || roomIdParts[1];
|
|
||||||
|
|
||||||
// Only include messages where the user is either the sender or the recipient
|
|
||||||
if (message.u._id === rocketChatUserId || message.u._id === otherUserId) {
|
|
||||||
return {
|
|
||||||
...message,
|
|
||||||
roomName: subscription.fname || subscription.name || 'Direct Message',
|
|
||||||
roomType: subscription.t,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// For channels and groups, only include messages where the user is the sender
|
|
||||||
if (message.u._id === rocketChatUserId) {
|
|
||||||
return {
|
|
||||||
...message,
|
|
||||||
roomName: subscription.fname || subscription.name || 'Direct Message',
|
|
||||||
roomType: subscription.t,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('No messages found for room:', subscription.rid);
|
|
||||||
return null;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error processing room:', subscription.rid, error);
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
})
|
);
|
||||||
);
|
|
||||||
|
|
||||||
// Filter out any null messages and sort by timestamp
|
if (!messagesResponse.ok) {
|
||||||
const validMessages = messages
|
console.error(`Failed to get messages for room ${subscription.name}:`, {
|
||||||
.filter((msg): msg is NonNullable<typeof msg> => msg !== null)
|
status: messagesResponse.status,
|
||||||
.sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime());
|
statusText: messagesResponse.statusText,
|
||||||
|
username: session.user?.username
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
console.log('Found messages:', validMessages.length);
|
const messagesData = await messagesResponse.json();
|
||||||
return NextResponse.json({ messages: validMessages });
|
console.log(`Messages response for ${subscription.name}:`, messagesData);
|
||||||
|
|
||||||
|
if (messagesData.messages && messagesData.messages.length > 0) {
|
||||||
|
messages.push(...messagesData.messages);
|
||||||
|
} else {
|
||||||
|
console.log(`No messages found for room: ${roomId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Found messages:', messages.length);
|
||||||
|
return new Response(JSON.stringify({ messages }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching messages:', error);
|
console.error('Error fetching messages:', error);
|
||||||
return NextResponse.json(
|
return new Response(JSON.stringify({ error: 'Internal server error' }), {
|
||||||
{ error: "Internal server error" },
|
status: 500,
|
||||||
{ status: 500 }
|
headers: { 'Content-Type': 'application/json' },
|
||||||
);
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Loading…
Reference in New Issue
Block a user