You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.2 KiB

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(async (_event, session) => {
if (session != null) {
setSession(session);
return;
}
const { data: { session: current } } = await supabase.auth.getSession();
setSession(current);
});
},
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();

Powered by TurnKey Linux.