fx-1 / src /contexts /AuthContext.tsx
felix-fx's picture
Initial commit from GitHub fx-1
6711fd5 verified
Raw History Blame Contribute Delete
3.56 kB
import React, { createContext, useContext, useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import type { User, Session } from '@supabase/supabase-js';
interface Profile {
id: string;
user_id: string;
username: string | null;
display_name: string | null;
avatar_url: string | null;
bio: string | null;
is_verified: boolean;
reputation: number;
total_uploads: number;
created_at: string;
}
interface AuthContextType {
user: User | null;
profile: Profile | null;
session: Session | null;
loading: boolean;
signUp: (email: string, password: string, metadata?: { username?: string; display_name?: string }) => Promise<{ error: any }>;
signIn: (email: string, password: string) => Promise<{ error: any }>;
signOut: () => Promise<void>;
refreshProfile: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [profile, setProfile] = useState<Profile | null>(null);
const [session, setSession] = useState<Session | null>(null);
const [loading, setLoading] = useState(true);
const fetchProfile = async (userId: string) => {
try {
const { data, error } = await supabase
.from('profiles')
.select('*')
.eq('user_id', userId)
.single();
if (!error && data) {
setProfile(data as unknown as Profile);
}
} catch (e) {
console.error('Error fetching profile:', e);
}
};
const refreshProfile = async () => {
if (user) {
await fetchProfile(user.id);
}
};
useEffect(() => {
const { data: { subscription } } = supabase.auth.onAuthStateChange(
async (event, session) => {
setSession(session);
setUser(session?.user ?? null);
if (session?.user) {
setTimeout(() => fetchProfile(session.user.id), 0);
} else {
setProfile(null);
}
setLoading(false);
}
);
supabase.auth.getSession().then(({ data: { session } }) => {
setSession(session);
setUser(session?.user ?? null);
if (session?.user) {
fetchProfile(session.user.id);
}
setLoading(false);
});
return () => subscription.unsubscribe();
}, []);
const signUp = async (email: string, password: string, metadata?: { username?: string; display_name?: string }) => {
const { error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
username: metadata?.username,
display_name: metadata?.display_name,
},
emailRedirectTo: window.location.origin,
},
});
return { error };
};
const signIn = async (email: string, password: string) => {
const { error } = await supabase.auth.signInWithPassword({ email, password });
return { error };
};
const signOut = async () => {
await supabase.auth.signOut();
setUser(null);
setProfile(null);
setSession(null);
};
return (
<AuthContext.Provider value={{
user,
profile,
session,
loading,
signUp,
signIn,
signOut,
refreshProfile,
}}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};