管理后台初始化,登录,团队管理,报价单管理 完成

This commit is contained in:
‘Liammcl’
2024-12-15 17:39:58 +08:00
commit 5882bf9548
91 changed files with 16260 additions and 0 deletions

View File

@@ -0,0 +1,153 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import { supabase } from '@/config/supabase';
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const navigate = useNavigate();
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
// 监听认证状态变化
useEffect(() => {
// 获取初始会话状态
const initSession = async () => {
try {
const { data: { session } } = await supabase.auth.getSession();
setUser(session?.user ?? null);
} catch (error) {
console.error('Error getting session:', error);
} finally {
setLoading(false);
}
};
initSession();
// 订阅认证状态变化
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
setUser(session?.user ?? null);
});
return () => {
subscription?.unsubscribe();
};
}, []);
// 邮箱密码登录
const login = async (email, password) => {
try {
setLoading(true);
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
throw error;
}
setUser(data.user);
return data;
} catch (error) {
message.error(error.message || '登录失败');
throw error;
} finally {
setLoading(false);
}
};
// Google 登录
const signInWithGoogle = async () => {
try {
setLoading(true);
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
});
if (error) {
throw error;
}
return data;
} catch (error) {
message.error(error.message || 'Google 登录失败');
throw error;
} finally {
setLoading(false);
}
};
// 注册
const register = async (email, password) => {
try {
setLoading(true);
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: `${window.location.origin}/auth/callback`,
},
});
if (error) {
throw error;
}
message.success('注册成功!请查收验证邮件。');
return data;
} catch (error) {
message.error(error.message || '注册失败');
throw error;
} finally {
setLoading(false);
}
};
// 登出
const logout = async () => {
try {
setLoading(true);
const { error } = await supabase.auth.signOut({
scope: 'local'
});
if (error) {
throw error;
}
setUser(null);
message.success('已成功登出');
navigate('/login', { replace: true });
} catch (error) {
message.error(error.message || '登出失败');
throw error;
} finally {
setLoading(false);
}
};
const value = {
user,
loading,
login,
logout,
register,
signInWithGoogle,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};