fix alot of things

This commit is contained in:
NotII
2025-03-14 16:48:08 +00:00
parent c15e8119c7
commit 87a58a6736
17 changed files with 79 additions and 3102 deletions

View File

@@ -1,71 +0,0 @@
'use client';
// Helper function to verify authentication with the local API
export async function verifyAuth(token: string) {
try {
let authEndpoint;
const torMode = process.env.NEXT_PUBLIC_TOR_MODE === 'true';
// Check if we're running in a browser environment
if (typeof window !== 'undefined') {
// For Tor mode in browser, prefer relative URLs
if (torMode) {
authEndpoint = '/api/auth/me';
console.log(`Tor mode: Using relative URL for auth endpoint: ${authEndpoint}`);
} else {
// Use the current origin in regular browser environments
const origin = window.location.origin;
authEndpoint = new URL('/api/auth/me', origin).toString();
console.log(`Using browser origin for auth endpoint: ${authEndpoint}`);
}
} else {
// For SSR or when window is not available (e.g. in Docker container)
// For Tor mode, always use relative URLs
if (torMode) {
authEndpoint = '/api/auth/me';
console.log(`Tor mode SSR: Using relative URL for auth endpoint: ${authEndpoint}`);
}
// Use the environment variable if available
else if (process.env.SERVER_API_URL) {
// If SERVER_API_URL already includes /auth/me, don't append it again
if (process.env.SERVER_API_URL.includes('/auth/me')) {
authEndpoint = process.env.SERVER_API_URL;
} else {
// Otherwise append the endpoint to the base URL
authEndpoint = `${process.env.SERVER_API_URL}/auth/me`;
}
console.log(`Using SERVER_API_URL for auth endpoint: ${authEndpoint}`);
} else {
// Fallback for local development
const protocol = (process.env.USE_HTTPS === 'false') ? 'http' : 'https';
const port = process.env.INTERNAL_API_PORT || '3000';
authEndpoint = `${protocol}://localhost:${port}/api/auth/me`;
console.log(`Using fallback for auth endpoint: ${authEndpoint}`);
}
}
console.log(`Verifying authentication with endpoint: ${authEndpoint}`);
const response = await fetch(authEndpoint, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
// Prevent caching of auth requests
cache: 'no-store'
});
if (!response.ok) {
console.error(`Auth verification failed: ${response.status}`);
return false;
}
return await response.json();
} catch (error) {
console.error("Authentication verification failed:", error);
console.error("Error details:", error instanceof Error ? error.message : 'Unknown error');
return false;
}
}

View File

@@ -21,77 +21,65 @@ function getAuthToken(): string | null {
?.split('=')[1] || null;
}
/**
* Gets the API base URL for client-side fetch calls
*/
function getClientApiBaseUrl(): string {
// For client-side, we can access window.location if in browser
if (typeof window !== 'undefined') {
// Use the same origin (which includes the correct port)
return `${window.location.origin}/api`;
}
// Fallback when window is not available
// For development mode, use port 3001 to match our server
if (process.env.NODE_ENV === 'development') {
return 'http://localhost:3001/api';
}
// Default fallback - relative URL
return '/api';
}
export async function fetchClient<T>(
endpoint: string,
options: FetchOptions = {}
): Promise<T> {
const { method = 'GET', body, headers = {}, ...rest } = options;
// Get the base API URL from environment or fallback
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
// Ensure the endpoint starts with a slash
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
// For the specific case of internal-api.inboxi.ng - remove duplicate /api
let url;
if (apiUrl.includes('internal-api.inboxi.ng')) {
// Special case for internal-api.inboxi.ng
if (normalizedEndpoint.startsWith('/api/')) {
url = `${apiUrl}${normalizedEndpoint.substring(4)}`; // Remove the /api part
} else {
url = `${apiUrl}${normalizedEndpoint}`;
}
} else {
// Normal case for other environments
url = `${apiUrl}${normalizedEndpoint}`;
}
// Get auth token from cookies
const authToken = getAuthToken();
// Prepare headers with authentication if token exists
const requestHeaders: Record<string, string> = {
'Content-Type': 'application/json',
...(headers as Record<string, string>),
};
if (authToken) {
// Backend expects "Bearer TOKEN" format
requestHeaders['Authorization'] = `Bearer ${authToken}`;
console.log('Authorization header set to:', `Bearer ${authToken.substring(0, 10)}...`);
}
console.log('API Request:', {
url,
method,
hasAuthToken: !!authToken
});
const fetchOptions: RequestInit = {
method,
credentials: 'include',
headers: requestHeaders,
...rest,
};
if (body && method !== 'GET') {
fetchOptions.body = JSON.stringify(body);
}
try {
// Get the base API URL
const baseUrl = getClientApiBaseUrl();
// Ensure endpoint doesn't start with a slash if baseUrl ends with one
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// Ensure baseUrl ends with a slash if it doesn't already
const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
// Combine them for the final URL
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
// Get auth token from cookies
const authToken = getAuthToken();
// Prepare headers with authentication if token exists
const requestHeaders: Record<string, string> = {
'Content-Type': 'application/json',
...(headers as Record<string, string>),
};
if (authToken) {
// Backend expects "Bearer TOKEN" format
requestHeaders['Authorization'] = `Bearer ${authToken}`;
console.log('Authorization header set to:', `Bearer ${authToken.substring(0, 10)}...`);
}
console.log('API Request:', {
url,
method,
hasAuthToken: !!authToken
});
const fetchOptions: RequestInit = {
method,
credentials: 'include',
headers: requestHeaders,
...rest,
};
if (body && method !== 'GET') {
fetchOptions.body = JSON.stringify(body);
}
const response = await fetch(url, fetchOptions);
if (!response.ok) {
@@ -109,7 +97,6 @@ export async function fetchClient<T>(
return data;
} catch (error) {
console.error('API request failed:', error);
console.error('Error details:', error instanceof Error ? error.message : 'Unknown error');
// Only show toast if this is a client-side error (not during SSR)
if (typeof window !== 'undefined') {

View File

@@ -1,77 +1,6 @@
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
/**
* Gets the base URL for server API requests with proper fallbacks
*/
function getBaseUrl() {
// Check if we're running in Tor mode
const torMode = process.env.NEXT_PUBLIC_TOR_MODE === 'true';
// First check for the specific server API URL environment variable
if (process.env.SERVER_API_URL) {
console.log(`Using SERVER_API_URL: ${process.env.SERVER_API_URL}`);
// If we're in Tor mode and the SERVER_API_URL is set to a relative path, use it directly
if (torMode && process.env.SERVER_API_URL.startsWith('/')) {
return process.env.SERVER_API_URL;
}
return process.env.SERVER_API_URL;
}
// For server components, we normally would use environment variables
// But we need to be careful with how they're accessed
// Try to get the API URL from environment variables
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
// Check if we're running in a container/production environment
const inContainer = process.env.NODE_ENV === 'production';
// If in Tor mode, prefer relative URLs
if (torMode && apiUrl && apiUrl.startsWith('/')) {
return apiUrl;
}
// We need to get the host from somewhere to construct the URL
// In production, we can rely on the VERCEL_URL or similar
if (process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}/api`;
}
// If we have a configured API URL, use that
if (apiUrl) {
// If it's already an absolute URL, use it
if (apiUrl.startsWith('http')) {
return apiUrl;
}
// For container environments, use the internal port
const port = process.env.INTERNAL_API_PORT || '3000';
const protocol = (process.env.USE_HTTPS === 'false') ? 'http' : 'https';
// If in Tor mode, prefer relative URLs
if (torMode) {
return apiUrl.startsWith('/') ? apiUrl : `/${apiUrl}`;
}
// Otherwise, it's likely a relative path like /api
// Use localhost with the correct port for container environments
return `${protocol}://localhost:${port}${apiUrl.startsWith('/') ? apiUrl : `/${apiUrl}`}`;
}
// Last resort fallback - if in Tor mode, use a relative URL
if (torMode) {
return '/api';
}
// For regular container environments
const protocol = (process.env.USE_HTTPS === 'false') ? 'http' : 'https';
const port = process.env.INTERNAL_API_PORT || '3000';
return `${protocol}://localhost:${port}/api`;
}
/**
* Server-side fetch wrapper with authentication.
*/
@@ -85,52 +14,8 @@ export async function fetchServer<T = unknown>(
if (!authToken) redirect('/login');
try {
const baseUrl = getBaseUrl();
const torMode = process.env.NEXT_PUBLIC_TOR_MODE === 'true';
// Special handling for Tor mode
if (torMode) {
// For Tor, we need to be extra careful with URL construction
// Remove leading slash from endpoint if present
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// If baseUrl is a relative path (starts with /)
if (baseUrl.startsWith('/')) {
// Combine paths carefully to create a relative URL
const url = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}${normalizedEndpoint}`;
console.log(`Tor mode: Using relative URL for server fetch: ${url}`);
const res = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`,
...options.headers,
},
cache: 'no-store',
});
if (res.status === 401) redirect('/login');
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
return res.json();
}
}
// Regular URL construction for non-Tor environments
// Ensure endpoint doesn't start with a slash if baseUrl ends with one
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// Ensure baseUrl ends with a slash if it doesn't already
const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
// Combine them to get a complete URL
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
console.log(`Server fetch to: ${url}`);
const res = await fetch(url, {
console.log(`${endpoint}`)
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',

View File

@@ -1,32 +0,0 @@
/**
* Helper function to construct proper URLs for server components.
* In Next.js server components, relative URLs don't work in fetch() calls.
*/
export function getServerApiUrl(endpoint: string): string {
// Base API URL - use a hardcoded value for server components
// This must be an absolute URL with protocol and domain
const baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api';
// Ensure endpoint doesn't start with a slash if baseUrl ends with one
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// Ensure the baseUrl ends with a slash if it doesn't already
const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
// Combine them to get a complete URL
return `${normalizedBaseUrl}${normalizedEndpoint}`;
}
/**
* Helper to detect if code is running on server or client
*/
export function isServer(): boolean {
return typeof window === 'undefined';
}
/**
* Helper to detect if code is running in development mode
*/
export function isDevelopment(): boolean {
return process.env.NODE_ENV === 'development';
}