Refactor AuthContext into smaller files

Refactors the AuthContext.tsx file into smaller, more manageable files to improve code organization and maintainability. The functionality remains the same.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-15 06:57:27 +00:00
parent ad597b281d
commit fd34c62170
13 changed files with 244 additions and 228 deletions

View File

@@ -0,0 +1,78 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import { supabase } from '@/lib/supabase';
import { Session, User } from '@supabase/supabase-js';
import { toast } from '@/hooks/useToast.wrapper';
import { AuthContextType } from './types';
import * as authActions from './authActions';
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [session, setSession] = useState<Session | null>(null);
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// 현재 세션 체크
const getSession = async () => {
try {
const { data, error } = await supabase.auth.getSession();
if (error) {
console.error('세션 로딩 중 오류:', error);
toast({
title: '세션 로드 오류',
description: '사용자 세션을 불러오는 중 문제가 발생했습니다.',
variant: 'destructive',
});
} else {
setSession(data.session);
setUser(data.session?.user ?? null);
}
} catch (error) {
console.error('세션 확인 중 예외 발생:', error);
} finally {
setLoading(false);
}
};
getSession();
// auth 상태 변경 리스너
const { data: { subscription } } = supabase.auth.onAuthStateChange(
async (event, session) => {
console.log('Supabase auth 이벤트:', event);
setSession(session);
setUser(session?.user ?? null);
setLoading(false);
}
);
// 리스너 정리
return () => {
subscription.unsubscribe();
};
}, []);
// 인증 작업 메서드들
const value: AuthContextType = {
session,
user,
loading,
signIn: authActions.signIn,
signUp: authActions.signUp,
signOut: authActions.signOut,
resetPassword: authActions.resetPassword,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth는 AuthProvider 내부에서 사용해야 합니다');
}
return context;
};

View File

@@ -0,0 +1,134 @@
import { supabase } from '@/lib/supabase';
import { toast } from '@/hooks/useToast.wrapper';
export const signIn = async (email: string, password: string) => {
try {
const { error } = await supabase.auth.signInWithPassword({ email, password });
if (error) {
console.error('로그인 오류:', error);
toast({
title: '로그인 실패',
description: error.message,
variant: 'destructive',
});
return { error };
}
toast({
title: '로그인 성공',
description: '환영합니다!',
});
return { error: null };
} catch (error: any) {
console.error('로그인 중 예외 발생:', error);
toast({
title: '로그인 오류',
description: '예상치 못한 오류가 발생했습니다.',
variant: 'destructive',
});
return { error };
}
};
export const signUp = async (email: string, password: string, username: string) => {
try {
// Supabase 인증으로 사용자 생성
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
username,
},
},
});
if (error) {
console.error('회원가입 오류:', error);
toast({
title: '회원가입 실패',
description: error.message,
variant: 'destructive',
});
return { error, user: null };
}
toast({
title: '회원가입 성공',
description: '이메일 확인 후 로그인해주세요.',
});
return { error: null, user: data.user };
} catch (error: any) {
console.error('회원가입 중 예외 발생:', error);
toast({
title: '회원가입 오류',
description: '예상치 못한 오류가 발생했습니다.',
variant: 'destructive',
});
return { error, user: null };
}
};
export const signOut = async () => {
try {
const { error } = await supabase.auth.signOut();
if (error) {
console.error('로그아웃 오류:', error);
toast({
title: '로그아웃 실패',
description: error.message,
variant: 'destructive',
});
return { error };
}
toast({
title: '로그아웃 성공',
description: '다음에 또 만나요!',
});
return { error: null };
} catch (error: any) {
console.error('로그아웃 중 예외 발생:', error);
toast({
title: '로그아웃 오류',
description: '예상치 못한 오류가 발생했습니다.',
variant: 'destructive',
});
return { error };
}
};
export const resetPassword = async (email: string) => {
try {
const { error } = await supabase.auth.resetPasswordForEmail(email, {
redirectTo: window.location.origin + '/reset-password',
});
if (error) {
console.error('비밀번호 재설정 오류:', error);
toast({
title: '비밀번호 재설정 실패',
description: error.message,
variant: 'destructive',
});
return { error };
}
toast({
title: '비밀번호 재설정 이메일 전송됨',
description: '이메일을 확인하여 비밀번호를 재설정해주세요.',
});
return { error: null };
} catch (error: any) {
console.error('비밀번호 재설정 중 예외 발생:', error);
toast({
title: '비밀번호 재설정 오류',
description: '예상치 못한 오류가 발생했습니다.',
variant: 'destructive',
});
return { error };
}
};

View File

@@ -0,0 +1,3 @@
export { AuthProvider, useAuth } from './AuthProvider';
export type { AuthContextType } from './types';

View File

@@ -0,0 +1,12 @@
import { Session, User } from '@supabase/supabase-js';
export type AuthContextType = {
session: Session | null;
user: User | null;
loading: boolean;
signIn: (email: string, password: string) => Promise<{ error: any }>;
signUp: (email: string, password: string, username: string) => Promise<{ error: any, user: any }>;
signOut: () => Promise<void>;
resetPassword: (email: string) => Promise<{ error: any }>;
};