import {defineStore} from "pinia"; import {ref} from "vue"; import {CharacterResponse} from "@/generated/mammon"; import { addCharacter as addCharacterRequest, fetchMe, mammonLoginUrl, postLogout, refreshAccessToken, setOnAuthExpired } from "@/mammon"; import {setAccessToken} from "./token"; export const useAuthStore = defineStore('auth', () => { const userId = ref(null); const characters = ref([]); const isAuthenticated = ref(false); const clear = () => { setAccessToken(null); userId.value = null; characters.value = []; isAuthenticated.value = false; } const refresh = async (): Promise => { const token = await refreshAccessToken(); if (!token) { clear(); return false; } isAuthenticated.value = true; return true; } const fetch = async (): Promise => { const me = await fetchMe(); userId.value = me.userId; characters.value = me.characters; isAuthenticated.value = true; } const login = (): void => { window.location.assign(mammonLoginUrl); } const addCharacter = async (): Promise => { await addCharacterRequest(); window.location.assign(mammonLoginUrl); } const logout = async (): Promise => { try { await postLogout(); } finally { clear(); } } const bootstrap = async (): Promise => { setOnAuthExpired(() => { clear(); login(); }); if (await refresh()) { await fetch().catch(() => {}); } } return {userId, characters, isAuthenticated, refresh, fetch, login, addCharacter, logout, bootstrap}; })