130 lines
4.2 KiB
TypeScript
130 lines
4.2 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth/next';
|
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
|
import { getToken } from 'next-auth/jwt';
|
|
|
|
// Helper function to get user token using admin credentials
|
|
async function getUserTokenForRocketChat(email: string) {
|
|
try {
|
|
const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0];
|
|
|
|
if (!baseUrl) {
|
|
console.error('Failed to get Rocket.Chat base URL');
|
|
return null;
|
|
}
|
|
|
|
console.log(`Authenticating with Rocket.Chat at ${baseUrl} for user ${email}`);
|
|
|
|
// Admin headers for Rocket.Chat API
|
|
const adminHeaders = {
|
|
'X-Auth-Token': process.env.ROCKET_CHAT_TOKEN!,
|
|
'X-User-Id': process.env.ROCKET_CHAT_USER_ID!,
|
|
'Content-Type': 'application/json'
|
|
};
|
|
|
|
// Get the username from email
|
|
const username = email.split('@')[0];
|
|
console.log(`Derived username: ${username}`);
|
|
|
|
// Get all users to find the current user
|
|
const usersResponse = await fetch(`${baseUrl}/api/v1/users.list`, {
|
|
method: 'GET',
|
|
headers: adminHeaders
|
|
});
|
|
|
|
if (!usersResponse.ok) {
|
|
console.error(`Failed to get users list: ${usersResponse.status}`);
|
|
return null;
|
|
}
|
|
|
|
const usersData = await usersResponse.json();
|
|
console.log(`Retrieved ${usersData.users?.length || 0} users from Rocket.Chat`);
|
|
|
|
// Find the current user in the list - FIX: properly check email address
|
|
const currentUser = usersData.users.find((user: any) => {
|
|
// Check username match
|
|
if (user.username === username) {
|
|
return true;
|
|
}
|
|
|
|
// Check email match in emails array
|
|
if (user.emails && Array.isArray(user.emails)) {
|
|
return user.emails.some((emailObj: any) => emailObj.address === email);
|
|
}
|
|
|
|
return false;
|
|
});
|
|
|
|
if (!currentUser) {
|
|
console.error(`User not found in Rocket.Chat users list with username ${username} or email ${email}`);
|
|
// Try to log some users for debugging
|
|
const someUsers = usersData.users.slice(0, 3).map((u: any) => ({
|
|
username: u.username,
|
|
emails: u.emails,
|
|
name: u.name
|
|
}));
|
|
console.log('Sample users:', JSON.stringify(someUsers));
|
|
return null;
|
|
}
|
|
|
|
console.log(`Found user in Rocket.Chat: ${currentUser.username} (${currentUser._id})`);
|
|
|
|
// Create a token for the current user
|
|
const createTokenResponse = await fetch(`${baseUrl}/api/v1/users.createToken`, {
|
|
method: 'POST',
|
|
headers: adminHeaders,
|
|
body: JSON.stringify({
|
|
userId: currentUser._id
|
|
})
|
|
});
|
|
|
|
if (!createTokenResponse.ok) {
|
|
console.error(`Failed to create user token: ${createTokenResponse.status}`);
|
|
const errorText = await createTokenResponse.text();
|
|
console.error(`Error details: ${errorText}`);
|
|
return null;
|
|
}
|
|
|
|
const tokenData = await createTokenResponse.json();
|
|
console.log('Successfully created Rocket.Chat token');
|
|
|
|
return {
|
|
authToken: tokenData.data.authToken,
|
|
userId: currentUser._id
|
|
};
|
|
} catch (error) {
|
|
console.error('Error getting user token for Rocket.Chat:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
// Get the current user session
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session?.user?.email) {
|
|
return NextResponse.json({ error: 'User not authenticated' }, { status: 401 });
|
|
}
|
|
|
|
const userEmail = session.user.email;
|
|
console.log(`Processing Rocket.Chat login for user ${userEmail}`);
|
|
|
|
// Get a token for Rocket.Chat
|
|
const rocketChatTokens = await getUserTokenForRocketChat(userEmail);
|
|
|
|
if (!rocketChatTokens) {
|
|
return NextResponse.json({ error: 'Failed to obtain Rocket.Chat tokens' }, { status: 500 });
|
|
}
|
|
|
|
// Return the tokens to the client
|
|
return NextResponse.json({
|
|
success: true,
|
|
rocketChatToken: rocketChatTokens.authToken,
|
|
rocketChatUserId: rocketChatTokens.userId
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in Rocket.Chat login API:', error);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|