File size: 1,466 Bytes
d3f86d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { json } from '@sveltejs/kit';

export async function POST({ request }) {
  try {
    const { code } = await request.json();
    console.log('Received OAuth code:', code);
    
    // Forward request to backend
    console.log('Forwarding to backend at http://localhost:7860/api/auth/token');
    const response = await fetch('http://localhost:7860/api/auth/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ code }),
    });
    
    console.log('Backend response status:', response.status);
    
    if (!response.ok) {
      const errorText = await response.text();
      console.error('Backend error response:', errorText);
      throw new Error(`Backend error (${response.status}): ${errorText}`);
    }
    
    const tokenData = await response.json();
    console.log('Successfully received token data');
    return json(tokenData);
    
  } catch (error) {
    console.error('OAuth token exchange error:', error);
    
    // Check if it's a network error (backend not running)
    if (error.message.includes('fetch') || error.code === 'ECONNREFUSED') {
      return json(
        { error: 'Backend server is not running. Please start the backend with: cd backend && python -m hfstudio.cli --dev' },
        { status: 503 }
      );
    }
    
    return json(
      { error: `Failed to exchange authorization code: ${error.message}` },
      { status: 500 }
    );
  }
}