Files
gemory/src/auth/auth.ts
T
2026-06-28 22:14:29 +02:00

74 lines
1.8 KiB
TypeScript

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<string | null>(null);
const characters = ref<CharacterResponse[]>([]);
const isAuthenticated = ref(false);
const clear = () => {
setAccessToken(null);
userId.value = null;
characters.value = [];
isAuthenticated.value = false;
}
const refresh = async (): Promise<boolean> => {
const token = await refreshAccessToken();
if (!token) {
clear();
return false;
}
isAuthenticated.value = true;
return true;
}
const fetch = async (): Promise<void> => {
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<void> => {
await addCharacterRequest();
window.location.assign(mammonLoginUrl);
}
const logout = async (): Promise<void> => {
try {
await postLogout();
} finally {
clear();
}
}
const bootstrap = async (): Promise<void> => {
setOnAuthExpired(() => {
clear();
login();
});
if (await refresh()) {
await fetch().catch(() => {});
}
}
return {userId, characters, isAuthenticated, refresh, fetch, login, addCharacter, logout, bootstrap};
})