feat(#5): use auth
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
return {userId, characters, isAuthenticated, refresh, fetch, login, addCharacter, logout, bootstrap};
|
||||
})
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './auth';
|
||||
export * from './token';
|
||||
@@ -0,0 +1,7 @@
|
||||
let accessToken: string | null = null;
|
||||
|
||||
export const getAccessToken = (): string | null => accessToken;
|
||||
|
||||
export const setAccessToken = (token: string | null): void => {
|
||||
accessToken = token;
|
||||
};
|
||||
Reference in New Issue
Block a user