forked from xhgit/webup-cloud
76 lines
2.0 KiB
TypeScript
76 lines
2.0 KiB
TypeScript
import { defineStore } from "pinia";
|
|
import { ref } from "vue";
|
|
import { api } from "./api";
|
|
import { themeTokens, type Palettes } from "./extensions";
|
|
export type User = {
|
|
id: string;
|
|
email: string;
|
|
displayName: string;
|
|
status: string;
|
|
roles: string[];
|
|
permissions: string[];
|
|
};
|
|
export const useSession = defineStore("session", () => {
|
|
const user = ref<User | null>(null);
|
|
const settings = ref<Record<string, string>>({});
|
|
const palettes = ref<Palettes>({});
|
|
async function refreshTheme() {
|
|
const theme = await api<{ palettes?: Palettes }>(
|
|
"/public/extensions/theme",
|
|
);
|
|
palettes.value = theme.palettes ?? {};
|
|
}
|
|
function themeStyle(mode: "light" | "dark", landing = false) {
|
|
const palette = palettes.value[mode];
|
|
const style: Record<string, string> = {};
|
|
for (const [token, property] of Object.entries(themeTokens)) {
|
|
const value = palette?.[token as keyof typeof themeTokens];
|
|
if (value && /^#[0-9a-f]{6}$/i.test(value)) {
|
|
style[property] = value;
|
|
if (landing) style[`--landing-${token}`] = value;
|
|
}
|
|
}
|
|
return style;
|
|
}
|
|
async function load() {
|
|
user.value = await api<User>("/me");
|
|
}
|
|
async function brand() {
|
|
settings.value = await api("/public/settings");
|
|
document.title =
|
|
(settings.value.englishName || settings.value.siteName) +
|
|
" · " +
|
|
(settings.value.tagline || "控制台");
|
|
if (settings.value.faviconUrl) {
|
|
let link = document.querySelector<HTMLLinkElement>('link[rel="icon"]');
|
|
if (!link) {
|
|
link = document.createElement("link");
|
|
link.rel = "icon";
|
|
document.head.appendChild(link);
|
|
}
|
|
link.href = settings.value.faviconUrl;
|
|
}
|
|
}
|
|
function clear() {
|
|
sessionStorage.removeItem("session");
|
|
user.value = null;
|
|
}
|
|
async function logout() {
|
|
try {
|
|
await api("/auth/logout", { method: "POST" });
|
|
} finally {
|
|
clear();
|
|
}
|
|
}
|
|
return {
|
|
user,
|
|
settings,
|
|
load,
|
|
brand,
|
|
clear,
|
|
logout,
|
|
refreshTheme,
|
|
themeStyle,
|
|
};
|
|
});
|