login with supabase working
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import { supabase } from '../supabase.js';
|
||||
|
||||
function createAuthStore() {
|
||||
const { subscribe, set, update } = writable({
|
||||
user: null,
|
||||
loading: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
function setSession(session) {
|
||||
const user = session?.user ?? null;
|
||||
set({
|
||||
user,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
subscribe,
|
||||
init: async () => {
|
||||
try {
|
||||
const { data: { session } } = await supabase.auth.getSession();
|
||||
setSession(session);
|
||||
} catch (e) {
|
||||
set({ user: null, loading: false, error: e?.message ?? 'Auth error' });
|
||||
}
|
||||
supabase.auth.onAuthStateChange((_event, session) => {
|
||||
setSession(session);
|
||||
});
|
||||
},
|
||||
login: async (email, password) => {
|
||||
update((s) => ({ ...s, error: null }));
|
||||
try {
|
||||
const { error } = await supabase.auth.signInWithPassword({ email, password });
|
||||
if (error) {
|
||||
update((s) => ({ ...s, error: error.message }));
|
||||
return false;
|
||||
}
|
||||
update((s) => ({ ...s, error: null }));
|
||||
return true;
|
||||
} catch (e) {
|
||||
update((s) => ({ ...s, error: e?.message ?? 'Login failed' }));
|
||||
return false;
|
||||
}
|
||||
},
|
||||
register: async (email, password) => {
|
||||
update((s) => ({ ...s, error: null }));
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signUp({ email, password });
|
||||
if (error) {
|
||||
update((s) => ({ ...s, error: error.message }));
|
||||
return { success: false };
|
||||
}
|
||||
update((s) => ({ ...s, error: null }));
|
||||
const needsConfirmation = data?.user && !data?.session;
|
||||
return { success: true, needsConfirmation, data };
|
||||
} catch (e) {
|
||||
update((s) => ({ ...s, error: e?.message ?? 'Registration failed' }));
|
||||
return { success: false };
|
||||
}
|
||||
},
|
||||
logout: async () => {
|
||||
await supabase.auth.signOut();
|
||||
set({ user: null, loading: false, error: null });
|
||||
},
|
||||
clearError: () => update((s) => ({ ...s, error: null })),
|
||||
};
|
||||
}
|
||||
|
||||
export const auth = createAuthStore();
|
||||
Reference in New Issue
Block a user