Refactor: clients → companies schema v2
This commit is contained in:
Executable
+82
@@ -0,0 +1,82 @@
|
||||
import { createContext, useContext, useState, useEffect } from 'react';
|
||||
import { supabase } from '../lib/supabase';
|
||||
|
||||
const AuthContext = createContext(null);
|
||||
|
||||
export function AuthProvider({ children }) {
|
||||
const [currentUser, setCurrentUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchProfile = async (authUser) => {
|
||||
const { data } = await supabase
|
||||
.from('profiles')
|
||||
.select('*, company:companies(id, name, email)')
|
||||
.eq('id', authUser.id)
|
||||
.single();
|
||||
if (data) setCurrentUser({ ...data, email: authUser.email });
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => setLoading(false), 5000);
|
||||
|
||||
supabase.auth.getSession().then(async ({ data: { session } }) => {
|
||||
if (session?.user) await fetchProfile(session.user);
|
||||
clearTimeout(timeout);
|
||||
setLoading(false);
|
||||
}).catch(() => {
|
||||
clearTimeout(timeout);
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
const { data: { subscription } } = supabase.auth.onAuthStateChange(async (event, session) => {
|
||||
if (session?.user) {
|
||||
await fetchProfile(session.user);
|
||||
} else {
|
||||
setCurrentUser(null);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
subscription.unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const login = async (email, password) => {
|
||||
const { error } = await supabase.auth.signInWithPassword({ email, password });
|
||||
if (error) return { error: error.message };
|
||||
return {};
|
||||
};
|
||||
|
||||
const signup = async (email, password, name) => {
|
||||
const { error } = await supabase.auth.signUp({
|
||||
email,
|
||||
password,
|
||||
options: { data: { name, role: 'client' } },
|
||||
});
|
||||
if (error) return { error: error.message };
|
||||
return {};
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
await supabase.auth.signOut();
|
||||
setCurrentUser(null);
|
||||
};
|
||||
|
||||
if (loading) return (
|
||||
<div style={{
|
||||
minHeight: '100vh', background: '#111111',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
<img src="/fourge-logo.png" alt="Fourge Branding" style={{ width: 160, opacity: 0.6 }} />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ currentUser, login, signup, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useAuth = () => useContext(AuthContext);
|
||||
Reference in New Issue
Block a user