vbv/client/src/stores/user.ts

102 lines
2.7 KiB
TypeScript

import log from "loglevel";
import { bustItGetCache, itGetCached, itPost } from "@/fetchHelpers";
import { loadLocaleMessages, setI18nLanguage } from "@/i18n";
import { useAppStore } from "@/stores/app";
import { defineStore } from "pinia";
const logoutRedirectUrl = import.meta.env.VITE_LOGOUT_REDIRECT || "/";
// typed state https://stackoverflow.com/questions/71012513/when-using-pinia-and-typescript-how-do-you-use-an-action-to-set-the-state
export type AvailableLanguages = "de" | "fr" | "it";
export type UserState = {
id: number;
first_name: string;
last_name: string;
email: string;
username: string;
avatar_url: string;
is_superuser: boolean;
course_session_experts: number[];
loggedIn: boolean;
language: AvailableLanguages;
};
const initialUserState: UserState = {
id: 0,
email: "",
first_name: "",
last_name: "",
username: "",
avatar_url: "",
is_superuser: false,
course_session_experts: [],
loggedIn: false,
language: "de",
};
async function setLocale(language: AvailableLanguages) {
await loadLocaleMessages(language);
setI18nLanguage(language);
}
export const useUserStore = defineStore({
id: "user",
state: () => initialUserState as UserState,
getters: {
getFullName(): string {
return `${this.first_name} ${this.last_name}`.trim();
},
},
actions: {
handleLogin(username: string, password: string, next = "/") {
if (username && password) {
itPost("/api/core/login/", {
username,
password,
})
.then((data) => {
this.$state = data;
this.loggedIn = true;
log.debug("bust cache");
bustItGetCache();
log.debug(`redirect to ${next}`);
window.location.href = next;
})
.catch(() => {
this.loggedIn = false;
alert("Login failed");
});
}
},
handleLogout() {
Object.assign(this, initialUserState);
itPost("/api/core/logout/", {}).then(() => {
let redirectUrl;
if (logoutRedirectUrl !== "") {
redirectUrl = logoutRedirectUrl;
} else {
redirectUrl = "/";
}
window.location.href = redirectUrl;
});
},
async fetchUser() {
const appStore = useAppStore();
const data = await itGetCached("/api/core/me/");
this.$state = data;
this.loggedIn = true;
appStore.userLoaded = true;
await setLocale(data.language);
},
async setUserLanguages(language: AvailableLanguages) {
await setLocale(language);
this.$state.language = language;
await itPost("/api/core/me/", { language }, { method: "PUT" });
},
},
});