66 lines
2.1 KiB
TypeScript
66 lines
2.1 KiB
TypeScript
import { api, type User, type LoginResponse } from '$lib/api/client';
|
|
import { queryClient } from '$lib/query/client';
|
|
import { clearPersistedQueue } from '$lib/player/persisted';
|
|
import { playQueue, closeQueueDrawer } from '$lib/player/store.svelte';
|
|
import { user, setUser } from './user.svelte';
|
|
|
|
// Re-export so existing `import { user } from '$lib/auth/store.svelte'`
|
|
// callers keep working. New code can import directly from auth/user.svelte.
|
|
export { user };
|
|
|
|
export async function bootstrap(): Promise<void> {
|
|
try {
|
|
setUser(await api.get<User>('/api/me'));
|
|
} catch {
|
|
setUser(null);
|
|
}
|
|
}
|
|
|
|
export async function login(username: string, password: string): Promise<void> {
|
|
const res = await api.post<LoginResponse>('/api/auth/login', { username, password });
|
|
setUser(res.user);
|
|
}
|
|
|
|
export async function register(opts: {
|
|
username: string;
|
|
password: string;
|
|
inviteToken?: string;
|
|
displayName?: string;
|
|
}): Promise<void> {
|
|
const body: Record<string, string> = {
|
|
username: opts.username,
|
|
password: opts.password,
|
|
};
|
|
if (opts.inviteToken) body.invite_token = opts.inviteToken;
|
|
if (opts.displayName) body.display_name = opts.displayName;
|
|
const res = await api.post<LoginResponse>('/api/auth/register', body);
|
|
setUser(res.user);
|
|
await bootstrap();
|
|
}
|
|
|
|
export async function forgotPassword(email: string): Promise<void> {
|
|
await api.post('/api/auth/forgot-password', { email });
|
|
}
|
|
|
|
export async function resetPassword(token: string, newPassword: string): Promise<void> {
|
|
await api.post('/api/auth/reset-password', { token, new_password: newPassword });
|
|
}
|
|
|
|
export async function logout(opts: { silent?: boolean } = {}): Promise<void> {
|
|
const userId = user.value?.id;
|
|
if (!opts.silent) {
|
|
try {
|
|
await api.post('/api/auth/logout', {});
|
|
} catch {
|
|
// best effort — server-side session may already be gone
|
|
}
|
|
}
|
|
setUser(null);
|
|
queryClient.clear();
|
|
// M7 #364: clear queue persistence + reset in-memory queue + close drawer
|
|
// so a subsequent login doesn't inherit the previous user's playback state.
|
|
if (userId) clearPersistedQueue(userId);
|
|
playQueue([]);
|
|
closeQueueDrawer();
|
|
}
|