| | |
| | | |
| | | export const useAuthStore = defineStore("auth", () => { |
| | | const token = ref<string | null>(localStorage.getItem("satoken")); |
| | | const userId = ref<number | null>(parseUserId(localStorage.getItem("userId"))); |
| | | const displayName = ref<string | null>(localStorage.getItem("displayName")); |
| | | const avatarUrl = ref<string | null>(localStorage.getItem("avatarUrl")); |
| | | const permissions = ref<string[]>(parsePermissions(localStorage.getItem("permissions"))); |
| | | |
| | | function setSession(t: string, name: string, avatar?: string | null, perms?: string[]) { |
| | | function setSession(t: string, name: string, avatar?: string | null, perms?: string[], uid?: number | null) { |
| | | token.value = t; |
| | | userId.value = typeof uid === "number" && Number.isFinite(uid) ? uid : null; |
| | | displayName.value = name; |
| | | avatarUrl.value = avatar || null; |
| | | permissions.value = Array.isArray(perms) ? [...new Set(perms.filter(Boolean))] : []; |
| | | localStorage.setItem("satoken", t); |
| | | if (userId.value != null) { |
| | | localStorage.setItem("userId", String(userId.value)); |
| | | } else { |
| | | localStorage.removeItem("userId"); |
| | | } |
| | | localStorage.setItem("displayName", name); |
| | | localStorage.setItem("permissions", JSON.stringify(permissions.value)); |
| | | if (avatar) { |
| | |
| | | |
| | | function clear() { |
| | | token.value = null; |
| | | userId.value = null; |
| | | displayName.value = null; |
| | | avatarUrl.value = null; |
| | | permissions.value = []; |
| | | localStorage.removeItem("satoken"); |
| | | localStorage.removeItem("userId"); |
| | | localStorage.removeItem("displayName"); |
| | | localStorage.removeItem("avatarUrl"); |
| | | localStorage.removeItem("permissions"); |
| | | } |
| | | |
| | | return { token, displayName, avatarUrl, permissions, setSession, hasPermission, hasAnyPermission, clear }; |
| | | return { token, userId, displayName, avatarUrl, permissions, setSession, hasPermission, hasAnyPermission, clear }; |
| | | }); |
| | | |
| | | function parseUserId(raw: string | null) { |
| | | if (!raw) return null; |
| | | const value = Number(raw); |
| | | return Number.isFinite(value) ? value : null; |
| | | } |