auth flow

This commit is contained in:
alma 2025-05-02 10:50:40 +02:00
parent 44f278b7ab
commit 97479aaa35
2 changed files with 150 additions and 3 deletions

View File

@ -0,0 +1,72 @@
import { NextResponse } from 'next/server';
export async function GET() {
try {
// Check if we have the required environment variables
const token = process.env.ROCKET_CHAT_TOKEN;
const userId = process.env.ROCKET_CHAT_USER_ID;
const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0];
if (!token || !userId) {
return NextResponse.json({
error: 'Missing Rocket.Chat admin credentials',
hasToken: !!token,
hasUserId: !!userId
}, { status: 500 });
}
if (!baseUrl) {
return NextResponse.json({
error: 'Missing Rocket.Chat base URL',
iframeUrl: process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL
}, { status: 500 });
}
// Test a simple API call to verify credentials
const adminHeaders = {
'X-Auth-Token': token,
'X-User-Id': userId,
'Content-Type': 'application/json'
};
// Get server info (public endpoint that still requires admin auth)
const infoResponse = await fetch(`${baseUrl}/api/v1/info`, {
method: 'GET',
headers: adminHeaders
});
if (!infoResponse.ok) {
return NextResponse.json({
error: 'Failed to connect to Rocket.Chat API',
status: infoResponse.status,
statusText: infoResponse.statusText,
baseUrl
}, { status: 500 });
}
const infoData = await infoResponse.json();
// Try to list users (needs admin permissions)
const usersResponse = await fetch(`${baseUrl}/api/v1/users.list?count=5`, {
method: 'GET',
headers: adminHeaders
});
const usersResult = await usersResponse.json();
return NextResponse.json({
success: true,
serverInfo: {
version: infoData.version,
serverRunning: infoData.success
},
usersCount: usersResult.users?.length || 0,
baseUrl
});
} catch (error) {
return NextResponse.json({
error: 'Error testing Rocket.Chat connection',
message: error instanceof Error ? error.message : 'Unknown error'
}, { status: 500 });
}
}

View File

@ -4,6 +4,65 @@ import { redirect } from "next/navigation";
import { ResponsiveIframe } from "@/app/components/responsive-iframe";
import RocketChatAuth from "@/app/components/rocket-auth";
// Function to get Rocket.Chat token for server-side authentication
async function getRocketChatTokensServer(email: string) {
try {
const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0];
if (!baseUrl) return null;
// 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];
// Get all users to find the current user
const usersResponse = await fetch(`${baseUrl}/api/v1/users.list`, {
method: 'GET',
headers: adminHeaders,
cache: 'no-store' // Don't cache this request
});
if (!usersResponse.ok) return null;
const usersData = await usersResponse.json();
// Find the current user in the list
const currentUser = usersData.users.find((user: any) =>
user.username === username ||
(user.emails && user.emails.some((emailObj: any) => emailObj.address === email))
);
if (!currentUser) return null;
// 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
}),
cache: 'no-store' // Don't cache this request
});
if (!createTokenResponse.ok) return null;
const tokenData = await createTokenResponse.json();
return {
token: tokenData.data.authToken,
userId: currentUser._id
};
} catch (error) {
console.error('Error getting server-side Rocket.Chat token:', error);
return null;
}
}
export default async function Page() {
const session = await getServerSession(authOptions);
@ -11,16 +70,32 @@ export default async function Page() {
redirect("/signin");
}
// Use the proxy URL instead of the direct service URL
const proxyUrl = `/api/proxy/parole`;
// Try to get Rocket.Chat tokens server-side
let rocketChatUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL || '';
if (session.user?.email) {
const rocketTokens = await getRocketChatTokensServer(session.user.email);
if (rocketTokens) {
// Add token to URL for direct authentication
// Note: This is only for development/testing - in production,
// consider more secure methods
const urlObj = new URL(rocketChatUrl);
urlObj.searchParams.set('resumeToken', rocketTokens.token);
urlObj.searchParams.set('rc_uid', rocketTokens.userId);
urlObj.searchParams.set('rc_token', rocketTokens.token);
rocketChatUrl = urlObj.toString();
}
}
return (
<main className="w-full h-screen bg-black">
{/* Keep RocketChatAuth for client-side backup authentication */}
<RocketChatAuth />
<div className="w-full h-full px-4 pt-12 pb-4">
<ResponsiveIframe
src={proxyUrl}
src={rocketChatUrl}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
/>
</div>