Files
zyt/admin/live-readonly/user.ts
T

107 lines
3.8 KiB
TypeScript

import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import request, { clearSession, getSessionMeta, setAllowedResources } from './transport'
import { projectResources } from './resources.mjs'
import { buildNavigation } from './navigation.mjs'
interface MenuNode {
id: string
title: string
icon: string
children?: MenuNode[]
}
interface MenuEntry extends MenuNode {
breadcrumbs: string[]
officialHref: string | null
liveKey: string | null
external?: boolean
query?: Record<string, string>
}
function asSidebar(node: MenuNode, entries: Record<string, MenuEntry>): RouteRecordRaw {
return {
path: `/nav/${node.id}`,
name: node.id,
meta: {
title: node.title,
icon: node.icon,
query: JSON.stringify(entries[node.id]?.query || {})
},
...(node.children?.length
? { children: node.children.map((n) => asSidebar(n, entries)) }
: {})
} as RouteRecordRaw
}
// The sidebar is the account's actual tree. Only the independent capability set can enable API calls.
export default defineStore('liveReadUser', {
state: () => ({
ready: false,
syncing: false,
token: '',
userInfo: {} as Record<string, unknown>,
perms: [] as string[],
keys: [] as string[],
routes: [] as RouteRecordRaw[],
entries: {} as Record<string, MenuEntry>,
firstId: null as string | null,
menuVersion: 0
}),
actions: {
forget() {
this.$reset()
clearSession()
},
async syncMenu() {
if (this.syncing) return
this.syncing = true
try {
const self = await request.get({ url: '/auth.admin/mySelf' })
if (
!getSessionMeta().authenticated ||
!self?.user ||
!/^[1-9]\d*$/.test(String(self.user.id)) ||
![0, '0', false].includes(self.user.disable) ||
String(self.user.is_paw) !== '1' ||
![0, '0', false].includes(self.user.need_bind_work_wechat) ||
!Array.isArray(self.menu) ||
!Array.isArray(self.permissions)
)
throw Error('请先在正式后台完成账号验证。')
const { keys, perms } = projectResources(self)
const nav = buildNavigation(self.menu, keys)
setAllowedResources(keys)
const entries = Object.fromEntries(nav.entries.map((e: MenuEntry) => [e.id, e]))
this.$patch({
userInfo: { name: String(self.user.name || '当前账号') },
perms,
keys,
routes: nav.tree.map((n: MenuNode) => asSidebar(n, entries)),
firstId: nav.firstId,
ready: true,
menuVersion: this.menuVersion + 1
})
// Replace, never merge: revoked menu IDs must disappear on refresh.
this.entries = entries
} catch (e) {
this.forget()
throw e
} finally {
this.syncing = false
}
},
async login(form: { account: string; password: string }) {
this.forget()
try {
await request.post({
url: '/login/account',
params: { account: form.account, password: form.password, terminal: 1 }
})
await this.syncMenu()
return { is_paw: 1, need_bind_work_wechat: false }
} catch (e) {
this.forget()
throw e
}
}
}
})