'use client'; import { useEffect, useState } from 'react'; import { useSession } from 'next-auth/react'; export function RocketChatAuth() { const { data: session } = useSession(); const [isAuthenticated, setIsAuthenticated] = useState(false); const [error, setError] = useState(null); useEffect(() => { async function authenticateWithRocketChat() { if (!session?.user?.email) { setError('No user session available'); return; } try { console.log('Authenticating with Rocket.Chat for user:', session.user.email); // Call our API to get Rocket.Chat tokens const response = await fetch('/api/auth/rocket-login'); // Get the text response for debugging if there's an error const responseText = await response.text(); if (!response.ok) { console.error('Failed to authenticate with Rocket.Chat:', responseText); setError(`Failed to authenticate: ${response.status} ${response.statusText}`); return; } // Parse the JSON now that we've read the text const data = JSON.parse(responseText); if (data.rocketChatToken && data.rocketChatUserId) { console.log('Received tokens from API:', { hasToken: !!data.rocketChatToken, hasUserId: !!data.rocketChatUserId }); // Get the current hostname to set domain cookies properly const hostname = window.location.hostname; const domain = hostname.includes('localhost') ? 'localhost' : hostname; console.log(`Setting cookies for domain: ${domain}`); // Store tokens in cookies that can be accessed by the Rocket.Chat iframe document.cookie = `rc_token=${data.rocketChatToken}; path=/; domain=${domain}; SameSite=None; Secure`; document.cookie = `rc_uid=${data.rocketChatUserId}; path=/; domain=${domain}; SameSite=None; Secure`; // Also store in localStorage which Rocket.Chat might check localStorage.setItem('Meteor.loginToken', data.rocketChatToken); localStorage.setItem('Meteor.userId', data.rocketChatUserId); console.log('Successfully authenticated with Rocket.Chat'); setIsAuthenticated(true); setError(null); } else { setError('Received invalid response from authentication API'); console.error('Invalid response data:', data); } } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; console.error('Error authenticating with Rocket.Chat:', errorMessage); setError(`Error: ${errorMessage}`); } } authenticateWithRocketChat(); }, [session]); // This component doesn't render visible UI by default return error ? (
Authentication Error: {error}
) : null; } export default RocketChatAuth;