71 lines
2.6 KiB
TypeScript
71 lines
2.6 KiB
TypeScript
'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;
|
|
}
|
|
}
|