Files
ember-market-frontend/app/api/auth/check/route.ts
NotII 29ec1be68c Refactor API URLs and add environment config example
Replaces hardcoded production API URLs with localhost defaults for local development in both server and client code. Updates Dockerfile to require API URLs via deployment environment variables. Improves ChatTable to use a batch endpoint for chats and unread counts, with backward compatibility. Adds an env.example file to document required environment variables. Updates next.config.mjs to use environment variables for backend API rewrites and image domains.
2025-09-01 15:35:10 +01:00

94 lines
3.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
// This ensures this route is always handled at runtime and never prerendered
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
try {
// Check for Authorization in headers first, then fall back to cookies
let token = req.headers.get('Authorization')?.replace('Bearer ', '');
// If not in headers, check cookies
if (!token) {
token = req.cookies.get('Authorization')?.value;
console.log('Auth check: Token from cookies:', token ? `${token.substring(0, 10)}...` : 'none');
// Debug: List all cookies
const cookiesList = req.cookies.getAll();
console.log('Auth check: All cookies:', JSON.stringify(cookiesList.map(c => c.name)));
} else {
console.log('Auth check: Token from headers:', token.substring(0, 10) + '...');
}
if (!token) {
console.log('Auth check failed: No Authorization token found');
return NextResponse.json(
{ error: 'No authorization token found' },
{ status: 401 }
);
}
console.log('Auth check: Token found -', token.substring(0, 15) + '...');
const apiUrl = process.env.SERVER_API_URL || 'http://localhost:3001/api';
console.log(`Auth check: Calling external API: ${apiUrl}/auth/me`);
try {
const res = await fetch(`${apiUrl}/auth/me`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
cache: 'no-store'
});
console.log('Auth check: External API response status:', res.status);
if (!res.ok) {
try {
const errorData = await res.json();
console.log('Auth check failed:', {
status: res.status,
statusText: res.statusText,
body: errorData
});
} catch {
const errorText = await res.text().catch(() => 'No response body');
console.log('Auth check failed:', {
status: res.status,
statusText: res.statusText,
body: errorText
});
}
return NextResponse.json(
{ error: 'Authentication failed', details: res.statusText },
{ status: res.status }
);
}
const data = await res.json();
console.log('Auth check succeeded:', { userId: data._id || 'unknown' });
return NextResponse.json(data);
} catch (fetchError) {
console.error('Auth check network error:', fetchError);
return NextResponse.json(
{
error: 'Failed to connect to authentication service',
details: fetchError instanceof Error ? fetchError.message : String(fetchError)
},
{ status: 503 } // Service Unavailable
);
}
} catch (error) {
console.error('Auth check error:', error);
return NextResponse.json(
{
error: 'Failed to validate authentication',
details: error instanceof Error ? error.message : String(error)
},
{ status: 500 }
);
}
}