vbv/client/src/stores/user.ts

89 lines
2.3 KiB
TypeScript

import * as log from "loglevel";
import { bustItGetCache, itGetCached, itPost } from "@/fetchHelpers";
import { useAppStore } from "@/stores/app";
import { useCourseSessionsStore } from "@/stores/courseSessions";
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 UserState = {
first_name: string;
last_name: string;
email: string;
username: string;
avatar_url: string;
loggedIn: boolean;
};
const initialUserState: UserState = {
email: "",
first_name: "",
last_name: "",
username: "",
avatar_url: "",
loggedIn: false,
};
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() {
itPost("/api/core/logout/", {}).then((data) => {
Object.assign(this, initialUserState);
let redirectUrl;
if (logoutRedirectUrl !== "") {
redirectUrl = logoutRedirectUrl;
} else {
redirectUrl = "/";
}
window.location.href = redirectUrl;
});
},
fetchUser() {
const appStore = useAppStore();
itGetCached("/api/core/me/")
.then((data) => {
this.$state = data;
this.loggedIn = true;
appStore.userLoaded = true;
const courseSessionsStore = useCourseSessionsStore();
courseSessionsStore.loadCourseSessionsData();
})
.catch(() => {
this.loggedIn = false;
appStore.userLoaded = true;
});
},
},
});