diff --git a/src/components/auth/LoginForm.tsx b/src/components/auth/LoginForm.tsx index b149fd4..6cacc0c 100644 --- a/src/components/auth/LoginForm.tsx +++ b/src/components/auth/LoginForm.tsx @@ -4,7 +4,7 @@ import { Link } from "react-router-dom"; import { Label } from "@/components/ui/label"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; -import { ArrowRight, Mail, KeyRound, Eye, EyeOff, AlertTriangle, Loader2, WifiOff } from "lucide-react"; +import { ArrowRight, Mail, KeyRound, Eye, EyeOff, AlertTriangle, Loader2, WifiOff, Wifi } from "lucide-react"; interface LoginFormProps { email: string; @@ -39,7 +39,8 @@ const LoginForm: React.FC = ({ const isCorsOrJsonError = loginError && (loginError.includes('JSON') || loginError.includes('CORS') || loginError.includes('프록시') || loginError.includes('서버 응답') || - loginError.includes('네트워크')); + loginError.includes('네트워크') || + loginError.includes('404') || loginError.includes('Not Found')); const toggleOfflineMode = () => { if (setIsOfflineMode) { @@ -90,6 +91,27 @@ const LoginForm: React.FC = ({ +
+ +
+ {loginError && (
@@ -97,7 +119,7 @@ const LoginForm: React.FC = ({

{loginError}

- {isCorsOrJsonError && ( + {isCorsOrJsonError && !isOfflineMode && (
  • 설정 페이지에서 다른 CORS 프록시 유형을 시도해 보세요.
  • HTTPS URL을 사용하는 Supabase 인스턴스로 변경해 보세요.
  • @@ -123,13 +145,9 @@ const LoginForm: React.FC = ({

    오프라인 모드 활성화됨

    서버 없이 앱의 기본 기능을 사용할 수 있습니다. 데이터는 로컬에 저장됩니다.

    - +

    + 중요: 404 오류가 계속 발생한다면 오프라인 모드를 사용해보세요. +

diff --git a/src/contexts/auth/signIn.ts b/src/contexts/auth/signIn.ts index 4a009ea..cfee4d2 100644 --- a/src/contexts/auth/signIn.ts +++ b/src/contexts/auth/signIn.ts @@ -13,7 +13,8 @@ export const signIn = async (email: string, password: string) => { // 서버 연결 상태 먼저 확인 const connectionStatus = await verifyServerConnection(); if (!connectionStatus.connected) { - showAuthToast('서버 연결 실패', connectionStatus.message, 'destructive'); + console.log('서버 연결 실패, 오프라인 모드 활성화를 고려하세요.'); + showAuthToast('서버 연결 실패', `${connectionStatus.message} (오프라인 모드를 사용해보세요)`, 'destructive'); return { error: { message: `서버 연결에 실패했습니다: ${connectionStatus.message}` }, user: null @@ -33,8 +34,13 @@ export const signIn = async (email: string, password: string) => { showAuthToast('로그인 성공', '환영합니다!'); return { error: null, user: data.user }; } else if (error) { - // JSON 파싱 오류인 경우 직접 API 호출 시도 - if (error.message.includes('json') || error.message.includes('Unexpected end')) { + console.error('로그인 오류:', error.message); + + // REST API 오류인 경우 직접 API 호출 시도 + if (error.message.includes('json') || + error.message.includes('Unexpected end') || + error.message.includes('404') || + error.message.includes('Not Found')) { console.warn('기본 로그인 실패, 직접 API 호출 시도:', error.message); return await signInWithDirectApi(email, password); } else { @@ -51,8 +57,17 @@ export const signIn = async (email: string, password: string) => { return { error: { message: errorMessage }, user: null }; } } - } catch (basicAuthError) { + } catch (basicAuthError: any) { console.warn('기본 인증 방식 예외 발생:', basicAuthError); + + // 404 에러나 경로 오류인 경우에도 직접 API 호출 시도 + if (basicAuthError.message && ( + basicAuthError.message.includes('404') || + basicAuthError.message.includes('Not Found') + )) { + return await signInWithDirectApi(email, password); + } + // 기본 로그인 실패 시 아래 직접 API 호출 방식 계속 진행 return await signInWithDirectApi(email, password); } @@ -64,7 +79,7 @@ export const signIn = async (email: string, password: string) => { // 네트워크 오류 확인 const errorMessage = handleNetworkError(error); - showAuthToast('로그인 오류', errorMessage, 'destructive'); + showAuthToast('로그인 오류', `${errorMessage} (오프라인 모드를 사용해보세요)`, 'destructive'); return { error: { message: errorMessage }, user: null }; } diff --git a/src/contexts/auth/signInUtils.ts b/src/contexts/auth/signInUtils.ts index 9eea282..fb9a05c 100644 --- a/src/contexts/auth/signInUtils.ts +++ b/src/contexts/auth/signInUtils.ts @@ -10,7 +10,8 @@ export const signInWithDirectApi = async (email: string, password: string) => { try { // 로그인 API 엔드포인트 URL과 헤더 준비 - const tokenUrl = `${supabase.auth.url}/token?grant_type=password`; + const supabaseUrl = supabase.auth.url; + const tokenUrl = `${supabaseUrl}/auth/v1/token?grant_type=password`; const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${supabase.supabaseKey}`, @@ -39,7 +40,50 @@ export const signInWithDirectApi = async (email: string, password: string) => { } if (response.status === 404) { - showAuthToast('로그인 실패', '서버 경로를 찾을 수 없습니다. Supabase URL을 확인하세요.', 'destructive'); + console.warn('API 경로를 찾을 수 없음 (404). 새 엔드포인트 시도 중...'); + + // 대체 엔드포인트 시도 (/token 대신 /signin) + const signinUrl = `${supabaseUrl}/auth/v1/signin`; + + try { + const signinResponse = await fetch(signinUrl, { + method: 'POST', + headers, + body: JSON.stringify({ email, password }) + }); + + console.log('대체 로그인 경로 응답 상태:', signinResponse.status); + + if (signinResponse.status === 404) { + showAuthToast('로그인 실패', '서버 설정을 확인하세요: 인증 API 경로를 찾을 수 없습니다.', 'destructive'); + return { + error: { message: '서버 설정 문제: 인증 API 경로를 찾을 수 없습니다. Supabase URL을 확인하세요.' }, + user: null + }; + } + + // 대체 응답 처리 + const signinData = await parseResponse(signinResponse); + if (signinData.error) { + showAuthToast('로그인 실패', signinData.error, 'destructive'); + return { error: { message: signinData.error }, user: null }; + } + + if (signinData.access_token) { + await supabase.auth.setSession({ + access_token: signinData.access_token, + refresh_token: signinData.refresh_token || '' + }); + + const { data: userData } = await supabase.auth.getUser(); + showAuthToast('로그인 성공', '환영합니다!'); + return { error: null, user: userData.user }; + } + } catch (altError) { + console.error('대체 로그인 엔드포인트 오류:', altError); + } + + showAuthToast('로그인 실패', '서버 설정을 확인하세요: 인증 API 경로를 찾을 수 없습니다.', 'destructive'); return { error: { message: '서버 경로를 찾을 수 없습니다. Supabase URL을 확인하세요.' }, user: null @@ -81,7 +125,7 @@ export const signInWithDirectApi = async (email: string, password: string) => { // 로그인 성공 시 Supabase 세션 설정 await supabase.auth.setSession({ access_token: responseData.access_token, - refresh_token: responseData.refresh_token + refresh_token: responseData.refresh_token || '' }); // 사용자 정보 가져오기 diff --git a/src/contexts/auth/signUp.ts b/src/contexts/auth/signUp.ts index 76a242d..4a69704 100644 --- a/src/contexts/auth/signUp.ts +++ b/src/contexts/auth/signUp.ts @@ -2,7 +2,8 @@ import { supabase } from '@/lib/supabase'; import { handleNetworkError, - showAuthToast + showAuthToast, + verifyServerConnection } from '@/utils/auth'; import { signUpWithDirectApi } from './signUpUtils'; @@ -11,30 +12,16 @@ export const signUp = async (email: string, password: string, username: string) console.log('회원가입 시도:', { email, username }); // 서버 연결 상태 확인 - try { - const response = await fetch(`${supabase.auth.url}/`, { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - }, - // 연결 확인만을 위한 요청이므로 짧은 타임아웃 설정 - signal: AbortSignal.timeout(5000) - }); - - if (!response.ok && response.status !== 401) { - // 401은 인증 필요 오류로, API 엔드포인트가 존재한다는 의미이므로 정상으로 간주 - console.warn('서버 연결 확인 실패:', response.status, response.statusText); - showAuthToast('서버 연결 오류', `서버가 응답하지 않거나 오류 상태입니다 (${response.status}). 관리자에게 문의하세요.`, 'destructive'); - return { error: { message: `서버 연결 오류 (${response.status})` }, user: null }; - } - } catch (connectionError: any) { - console.error('서버 연결 확인 중 오류:', connectionError); - showAuthToast('서버 연결 실패', '서버에 연결할 수 없습니다. 네트워크 상태 또는 서버 주소를 확인하세요.', 'destructive'); - return { error: connectionError, user: null }; + const connectionStatus = await verifyServerConnection(); + if (!connectionStatus.connected) { + console.warn('서버 연결 확인 실패:', connectionStatus.message); + showAuthToast('서버 연결 오류', `서버가 응답하지 않거나 오류 상태입니다: ${connectionStatus.message}. 오프라인 모드를 사용해보세요.`, 'destructive'); + return { error: { message: `서버 연결 오류: ${connectionStatus.message}` }, user: null }; } // 회원가입 시도 (기본 방식) try { + console.log('Supabase URL:', supabase.auth.url); // 온프레미스 서버에 적합한 옵션 추가 const { data, error } = await supabase.auth.signUp({ email, @@ -51,6 +38,17 @@ export const signUp = async (email: string, password: string, username: string) if (error) { console.error('회원가입 오류:', error); + // 서버 응답 오류 (404 등)인 경우 직접 API 호출 + if (error.message && ( + error.message.includes('404') || + error.message.includes('Not Found') || + error.message.includes('json') || + error.message.includes('Unexpected') + )) { + console.log('서버 응답 오류로 인해 직접 API 호출 시도'); + return await signUpWithDirectApi(email, password, username); + } + // 사용자 친화적인 오류 메시지 설정 let errorMessage = error.message; @@ -62,11 +60,6 @@ export const signUp = async (email: string, password: string, username: string) errorMessage = '유효하지 않은 이메일 형식입니다.'; } else if (error.message.includes('Unable to validate')) { errorMessage = '서버 연결 문제: 이메일 검증에 실패했습니다.'; - } else if (error.message.includes('json')) { - errorMessage = '서버 응답 형식 오류: 올바른 JSON 응답이 없습니다. 직접 API 호출을 시도합니다.'; - - // JSON 파싱 오류 발생 시 직접 API 호출 시도 - return await signUpWithDirectApi(email, password, username); } else if (error.message.includes('fetch failed')) { errorMessage = '서버 연결에 실패했습니다. 네트워크 연결 또는 서버 상태를 확인하세요.'; } else if (error.message.includes('Failed to fetch')) { @@ -90,11 +83,14 @@ export const signUp = async (email: string, password: string, username: string) } catch (signUpError: any) { console.error('기본 회원가입 방식 실패:', signUpError); - // JSON 파싱 오류 또는 기타 예외 시 직접 API 호출 시도 + // 404 응답이나 API 오류 시 직접 API 호출 if (signUpError.message && ( signUpError.message.includes('json') || - signUpError.message.includes('Unexpected end') + signUpError.message.includes('Unexpected end') || + signUpError.message.includes('404') || + signUpError.message.includes('Not Found') )) { + console.log('예외 발생으로 직접 API 호출 시도'); return await signUpWithDirectApi(email, password, username); } @@ -107,7 +103,7 @@ export const signUp = async (email: string, password: string, username: string) // 네트워크 오류 확인 const errorMessage = handleNetworkError(error); - showAuthToast('회원가입 오류', errorMessage, 'destructive'); + showAuthToast('회원가입 오류', `${errorMessage} (오프라인 모드를 시도해보세요)`, 'destructive'); return { error, user: null }; } }; diff --git a/src/hooks/useLogin.ts b/src/hooks/useLogin.ts index c490f02..387e3f4 100644 --- a/src/hooks/useLogin.ts +++ b/src/hooks/useLogin.ts @@ -17,6 +17,7 @@ export function useLogin() { const [showPassword, setShowPassword] = useState(false); const [isLoading, setIsLoading] = useState(false); const [loginError, setLoginError] = useState(null); + // 네트워크 연결이 끊겼거나 로컬 스토리지에 오프라인 모드 설정이 있으면 기본값을 true로 설정 const [isOfflineMode, setIsOfflineMode] = useState(() => localStorage.getItem('offline_mode') === 'true' || !navigator.onLine ); @@ -41,9 +42,12 @@ export function useLogin() { if (!isOfflineMode) { toast({ title: "네트워크 연결 끊김", - description: "인터넷 연결이 끊겼습니다. 오프라인 모드로 전환할 수 있습니다.", + description: "인터넷 연결이 끊겼습니다. 오프라인 모드로 전환합니다.", variant: "destructive" }); + // 자동으로 오프라인 모드로 전환 + setIsOfflineMode(true); + localStorage.setItem('offline_mode', 'true'); } }; @@ -56,6 +60,21 @@ export function useLogin() { }; }, [isOfflineMode, toast]); + // 로그인 시도 중 404 오류가 발생하면 자동으로 오프라인 모드 제안 + useEffect(() => { + if (loginError && ( + loginError.includes('404') || + loginError.includes('Not Found') || + loginError.includes('서버 연결') + )) { + toast({ + title: "서버 연결 문제", + description: "서버에 연결할 수 없습니다. 오프라인 모드를 사용해보세요.", + variant: "destructive" + }); + } + }, [loginError, toast]); + const handleLogin = async (e: React.FormEvent) => { e.preventDefault(); setLoginError(null); @@ -75,6 +94,11 @@ export function useLogin() { // 오프라인 모드를 위한 환경 설정 if (isOfflineMode) { localStorage.setItem('offline_mode', 'true'); + // 오프라인 모드에서는 로컬 인증만 수행하고 바로 진행 + showLoginSuccessToast('오프라인 모드'); + navigate("/"); + setIsLoading(false); + return; } const { error, user } = await signIn(email, password); @@ -84,6 +108,15 @@ export function useLogin() { const errorMessage = getLoginErrorMessage(error); setLoginError(errorMessage); showLoginErrorToast(errorMessage); + + // 404 오류인 경우 오프라인 모드 제안 + if (errorMessage.includes('404') || errorMessage.includes('Not Found')) { + toast({ + title: "오프라인 모드 제안", + description: "서버에 연결할 수 없습니다. 오프라인 모드를 사용해보세요.", + variant: "default" + }); + } } else if (user) { // 로그인 성공 showLoginSuccessToast(); @@ -114,6 +147,17 @@ export function useLogin() { description: errorMessage, variant: "destructive" }); + + // 네트워크 관련 오류인 경우 오프라인 모드 제안 + if (errorMessage.includes('network') || + errorMessage.includes('fetch') || + errorMessage.includes('서버')) { + toast({ + title: "오프라인 모드 제안", + description: "서버 연결에 문제가 있습니다. 오프라인 모드를 사용해보세요.", + variant: "default" + }); + } } finally { setIsLoading(false); } diff --git a/src/utils/auth/loginUtils.ts b/src/utils/auth/loginUtils.ts index 59de43b..fc0f0a4 100644 --- a/src/utils/auth/loginUtils.ts +++ b/src/utils/auth/loginUtils.ts @@ -1,5 +1,5 @@ -import { toast } from "@/hooks/useToast.wrapper"; +import { toast } from "@/components/ui/use-toast"; /** * 로그인 오류 메시지를 처리하는 유틸리티 함수 @@ -19,6 +19,8 @@ export const getLoginErrorMessage = (error: any): string => { errorMessage = "CORS 오류: 프록시 설정을 확인하거나 다른 프록시를 시도해보세요."; } else if (error.message.includes("fetch") || error.message.includes("네트워크")) { errorMessage = "네트워크 오류: 서버 연결에 실패했습니다."; + } else if (error.message.includes("404") || error.message.includes("Not Found")) { + errorMessage = "서버 오류: API 경로를 찾을 수 없습니다. 서버 설정을 확인하세요."; } else { errorMessage = `오류: ${error.message}`; } @@ -30,10 +32,10 @@ export const getLoginErrorMessage = (error: any): string => { /** * 로그인 성공 시 사용자에게 알림을 표시합니다. */ -export const showLoginSuccessToast = () => { +export const showLoginSuccessToast = (mode?: string) => { toast({ title: "로그인 성공", - description: "환영합니다! 대시보드로 이동합니다.", + description: mode ? `${mode}로 로그인되었습니다.` : "환영합니다! 대시보드로 이동합니다.", variant: "default" }); }; @@ -59,6 +61,8 @@ export const isCorsOrJsonError = (errorMessage: string | null): boolean => { errorMessage.includes('JSON') || errorMessage.includes('CORS') || errorMessage.includes('프록시') || - errorMessage.includes('서버 응답') + errorMessage.includes('서버 응답') || + errorMessage.includes('404') || + errorMessage.includes('Not Found') ); }; diff --git a/src/utils/auth/networkUtils.ts b/src/utils/auth/networkUtils.ts index d46aca1..bf15350 100644 --- a/src/utils/auth/networkUtils.ts +++ b/src/utils/auth/networkUtils.ts @@ -60,30 +60,57 @@ export const verifyServerConnection = async (): Promise<{ const supabaseUrl = supabase.auth.url; // 단순 헬스 체크 요청 - const response = await fetch(`${supabaseUrl}/`, { - method: 'GET', - headers: { - 'Content-Type': 'application/json' - }, - // 연결 확인만을 위한 요청이므로 짧은 타임아웃 설정 - signal: AbortSignal.timeout(3000) - }); + try { + const response = await fetch(`${supabaseUrl}/`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json' + }, + // 연결 확인만을 위한 요청이므로 짧은 타임아웃 설정 + signal: AbortSignal.timeout(3000) + }); + + const elapsed = Date.now() - start; + + // 200, 401, 404 응답도 서버가 살아있다는 신호로 간주 + if (response.ok || response.status === 401 || response.status === 404) { + return { + connected: true, + message: `서버 연결 성공 (응답 시간: ${elapsed}ms)`, + statusCode: response.status + }; + } else { + return { + connected: false, + message: `서버 응답 오류: ${response.status} ${response.statusText}`, + statusCode: response.status + }; + } + } catch (fetchError: any) { + console.error('기본 연결 확인 실패, 대체 경로 시도:', fetchError); - const elapsed = Date.now() - start; - - if (response.ok || response.status === 401) { - // 401도 서버가 응답했다는 의미이므로 연결 성공으로 간주 - return { - connected: true, - message: `서버 연결 성공 (응답 시간: ${elapsed}ms)`, - statusCode: response.status - }; - } else { - return { - connected: false, - message: `서버 응답 오류: ${response.status} ${response.statusText}`, - statusCode: response.status - }; + // 대체 경로로 재시도 + try { + const altResponse = await fetch(`${supabaseUrl}/auth/v1/`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json' + }, + signal: AbortSignal.timeout(3000) + }); + + // 어떤 응답이라도 오면 서버가 살아있다고 간주 + const elapsed = Date.now() - start; + return { + connected: true, + message: `서버 연결 성공 (대체 경로, 응답 시간: ${elapsed}ms)`, + statusCode: altResponse.status + }; + } catch (altError) { + // 두 가지 경로 모두 실패 + console.error('대체 경로 확인도 실패:', altError); + throw fetchError; // 원래 에러를 던짐 + } } } catch (error: any) { console.error('서버 연결 확인 중 오류:', error);