BookSystem/frontend/src/modules/admin/stores/auth.ts

54 lines
1.1 KiB
TypeScript

import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { http } from "@/modules/admin/api/http";
export type UserProfile = {
id: number;
username: string;
nickname: string;
email?: string | null;
phone?: string | null;
role_id: number;
};
export const useAuthStore = defineStore("auth", () => {
const token = ref<string>(localStorage.getItem("access_token") || "");
const user = ref<UserProfile | null>(null);
const isAuthenticated = computed(() => Boolean(token.value));
function setToken(t: string) {
token.value = t;
if (t) {
localStorage.setItem("access_token", t);
} else {
localStorage.removeItem("access_token");
}
}
async function fetchProfile() {
const { data } = await http.get<UserProfile>("/users/me");
user.value = data;
return data;
}
async function logout() {
try {
await http.post("/users/logout");
} catch {
/* ignore */
}
user.value = null;
setToken("");
}
return {
token,
user,
isAuthenticated,
setToken,
fetchProfile,
logout,
};
});