Investigate Supabase connection issues

Investigate REST API and database connection failures despite successful authentication.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-15 12:28:18 +00:00
parent 6de30b681a
commit ae1db90d87
4 changed files with 207 additions and 28 deletions

View File

@@ -1,9 +1,10 @@
import React, { useState } from 'react';
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";
import { RefreshCw, Info } from "lucide-react";
import { toast } from "@/hooks/useToast.wrapper";
import { testSupabaseConnection } from '@/lib/supabase';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
interface TestResult {
url: string;
@@ -14,11 +15,13 @@ interface TestResult {
auth: boolean;
database: boolean;
errors: string[];
debugInfo?: any;
}
const SupabaseConnectionTest: React.FC = () => {
const [testResults, setTestResults] = useState<TestResult | null>(null);
const [isTesting, setIsTesting] = useState(false);
const [showDebug, setShowDebug] = useState(false);
const runConnectionTest = async () => {
setIsTesting(true);
@@ -107,6 +110,59 @@ const SupabaseConnectionTest: React.FC = () => {
))}
</div>
)}
{/* 디버그 정보 섹션 추가 */}
{testResults.debugInfo && (
<Collapsible
open={showDebug}
onOpenChange={setShowDebug}
className="border border-gray-200 rounded-md mt-4"
>
<div className="flex items-center justify-between px-4 py-2 bg-gray-50">
<h4 className="text-sm font-medium"> </h4>
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0">
<Info className="h-4 w-4" />
<span className="sr-only">
{showDebug ? '진단 정보 숨기기' : '진단 정보 표시'}
</span>
</Button>
</CollapsibleTrigger>
</div>
<CollapsibleContent className="px-4 py-2 text-xs">
<div className="space-y-2">
<div>
<span className="font-medium">Supabase URL:</span>
<div className="mt-1 bg-gray-100 p-1 rounded break-all">
{testResults.url}
</div>
</div>
<div>
<span className="font-medium"> :</span>
<div className="mt-1 text-green-600">
{testResults.client ? '성공' : '실패'}
</div>
</div>
<div>
<span className="font-medium"> :</span>
<div className="mt-1 bg-gray-100 p-1 rounded break-all">
{testResults.debugInfo.browserInfo}
</div>
</div>
<div>
<span className="font-medium"> :</span>
<div className="mt-1">
{new Date(testResults.debugInfo.timestamp).toLocaleString()}
</div>
</div>
</div>
</CollapsibleContent>
</Collapsible>
)}
</div>
)}
</div>

View File

@@ -1,5 +1,6 @@
import React from 'react';
import { AlertCircle } from 'lucide-react';
const SupabaseHelpSection: React.FC = () => {
return (
@@ -17,12 +18,35 @@ const SupabaseHelpSection: React.FC = () => {
<strong>Anon Key</strong>: Supabase API anon/public .
</li>
<li>
<strong>CORS </strong>: HTTP URL에 . HTTPS가 URL에 .
<strong>CORS </strong>: HTTP URL에 .
HTTPS가 URL에 .
</li>
<li className="text-amber-500 font-medium">
HTTPS URL을 . HTTP URL을 CORS .
</li>
</ul>
{/* 오류 해결 팁 추가 */}
<div className="mt-6 border-t pt-4">
<h3 className="flex items-center text-sm font-semibold mb-2">
<AlertCircle className="h-4 w-4 mr-1 text-amber-500" />
<span> </span>
</h3>
<ul className="list-disc pl-5 text-xs text-gray-500 space-y-2">
<li>
<strong>REST API </strong>: CORS . Supabase CORS .
</li>
<li>
<strong> , API </strong>: CORS . CORS .
</li>
<li>
<strong> </strong>: Supabase , .
</li>
<li>
<strong>HTTPS </strong>: HTTP , HTTPS Supabase URL이 .
</li>
</ul>
</div>
</div>
);
};

View File

@@ -9,7 +9,14 @@ export const getSupabaseUrl = () => {
if (useProxy) {
// CORS 프록시 URL로 변환 (URL 구조 개선)
const cleanUrl = storedUrl.trim();
return `https://corsproxy.io/?${encodeURIComponent(cleanUrl)}`;
// URL에 이미 프로토콜이 포함되어 있는지 확인
const hasProtocol = cleanUrl.startsWith('http://') || cleanUrl.startsWith('https://');
const urlForProxy = hasProtocol ? cleanUrl : `http://${cleanUrl}`;
// 프록시 URL 생성 시 더 정확한 인코딩
const proxyUrl = `https://corsproxy.io/?${encodeURIComponent(urlForProxy)}`;
console.log('CORS 프록시 URL 생성:', proxyUrl);
return proxyUrl;
}
return storedUrl;
}
@@ -43,8 +50,13 @@ export const configureSupabase = (url: string, key: string, useProxy: boolean =
// URL 정리 (앞뒤 공백 제거)
const cleanUrl = url.trim();
// URL에 프로토콜이 없는 경우 http:// 추가
const normalizedUrl = (cleanUrl.startsWith('http://') || cleanUrl.startsWith('https://'))
? cleanUrl
: `http://${cleanUrl}`;
// 로컬 스토리지에 설정 저장
localStorage.setItem('supabase_url', cleanUrl);
localStorage.setItem('supabase_url', normalizedUrl);
localStorage.setItem('supabase_key', key);
localStorage.setItem('use_cors_proxy', useProxy.toString());

View File

@@ -27,43 +27,130 @@ export const testSupabaseLogin = async (email: string, password: string) => {
// API 테스트 도우미 함수
export const testSupabaseConnection = async () => {
const originalUrl = getOriginalSupabaseUrl();
const proxyUrl = getSupabaseUrl();
const usingProxy = isCorsProxyEnabled();
const supabaseKey = getSupabaseKey();
const results = {
url: getOriginalSupabaseUrl(), // 원본 URL
proxyUrl: getSupabaseUrl(), // 프록시 적용된 URL
usingProxy: isCorsProxyEnabled(), // 프록시 사용 여부
url: originalUrl, // 원본 URL
proxyUrl: proxyUrl, // 프록시 적용된 URL
usingProxy: usingProxy, // 프록시 사용 여부
client: !!supabase,
restApi: false,
auth: false,
database: false,
errors: [] as string[]
errors: [] as string[],
debugInfo: {
originalUrl,
proxyUrl,
usingProxy,
keyLength: supabaseKey.length,
browserInfo: navigator.userAgent,
timestamp: new Date().toISOString()
}
};
console.log('연결 테스트 시작 - 설정 정보:', {
originalUrl,
proxyUrl,
usingProxy
});
try {
// 1. REST API 접근 테스트
// 1. REST API 접근 테스트 - 다양한 URL 형식 시도
try {
console.log('REST API 테스트 시작...');
// 정확한 REST API 엔드포인트 구성
const apiUrl = results.proxyUrl.endsWith('/')
? `${results.proxyUrl}rest/v1/`
: `${results.proxyUrl}/rest/v1/`;
console.log('REST API 테스트 URL:', apiUrl);
// 여러 형태의 REST API 엔드포인트 URL 구성 시도
let apiUrl = '';
let response = null;
let errorBody = '';
const response = await fetch(apiUrl, {
// 1번째 시도: 기본 URL + /rest/v1/
apiUrl = proxyUrl.endsWith('/')
? `${proxyUrl}rest/v1/`
: `${proxyUrl}/rest/v1/`;
console.log('REST API 테스트 URL (시도 1):', apiUrl);
try {
response = await fetch(apiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'apikey': getSupabaseKey(),
'apikey': supabaseKey,
},
});
results.restApi = response.ok;
if (!response.ok) {
const errorBody = await response.text();
results.errors.push(`REST API 오류(${response.status} ${response.statusText}): ${errorBody || '응답 없음'}`);
console.error('REST API 테스트 실패:', response.status, errorBody);
if (response.ok) {
results.restApi = true;
console.log('REST API 테스트 성공 (시도 1)');
} else {
console.log('REST API 테스트 성공');
errorBody = await response.text();
console.warn(`REST API 테스트 실패 (시도 1) - 상태: ${response.status}, 오류: ${errorBody}`);
// 2번째 시도: corsproxy.io URL 직접 구성
if (usingProxy) {
const directProxyUrl = `https://corsproxy.io/?${encodeURIComponent(`${originalUrl}/rest/v1/`)}`;
console.log('REST API 테스트 URL (시도 2 - 직접 프록시):', directProxyUrl);
try {
response = await fetch(directProxyUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'apikey': supabaseKey,
},
});
if (response.ok) {
results.restApi = true;
console.log('REST API 테스트 성공 (시도 2)');
} else {
const error2 = await response.text();
console.warn(`REST API 테스트 실패 (시도 2) - 상태: ${response.status}, 오류: ${error2}`);
results.errors.push(`REST API 오류(${response.status}): ${error2 || errorBody || '응답 없음'}`);
}
} catch (innerErr: any) {
console.error('REST API 테스트 시도 2 예외:', innerErr);
results.errors.push(`REST API 예외 (시도 2): ${innerErr.message || '알 수 없는 오류'}`);
}
} else {
results.errors.push(`REST API 오류(${response.status}): ${errorBody || '응답 없음'}`);
}
}
} catch (outerErr: any) {
console.error('REST API 테스트 시도 1 예외:', outerErr);
results.errors.push(`REST API 예외 (시도 1): ${outerErr.message || '알 수 없는 오류'}`);
// 백업 시도
if (usingProxy) {
try {
// 백업 프록시 시도: 다른 CORS 프록시 서비스 사용
const backupProxyUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(`${originalUrl}/rest/v1/`)}`;
console.log('REST API 테스트 URL (백업 프록시):', backupProxyUrl);
response = await fetch(backupProxyUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'apikey': supabaseKey,
},
});
if (response.ok) {
results.restApi = true;
console.log('REST API 테스트 성공 (백업 프록시)');
results.debugInfo.backupProxySuccess = true;
} else {
const backupError = await response.text();
console.warn(`REST API 테스트 실패 (백업 프록시) - 상태: ${response.status}, 오류: ${backupError}`);
}
} catch (backupErr: any) {
console.error('REST API 백업 프록시 예외:', backupErr);
}
}
}
} catch (err: any) {
results.errors.push(`REST API 예외: ${err.message || '알 수 없는 오류'}`);