Files
NixMsg/web/src/stores/auth.ts
T

37 lines
889 B
TypeScript

import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { fetchMe, login as apiLogin, logout as apiLogout } from "@/api/admin";
export const useAuthStore = defineStore("auth", () => {
const username = ref<string | null>(null);
const ready = ref(false);
const isLoggedIn = computed(() => username.value != null);
async function hydrate() {
try {
const me = await fetchMe(true);
username.value = me.username;
} catch {
username.value = null;
} finally {
ready.value = true;
}
}
async function login(user: string, password: string) {
const res = await apiLogin(user, password);
username.value = res.username;
}
async function logout() {
try {
await apiLogout();
} finally {
username.value = null;
}
}
return { username, ready, isLoggedIn, hydrate, login, logout };
});