2026-09-09 22:05:00 +08:00
|
|
|
import { defineStore } from 'pinia'
|
|
|
|
|
import { ref, computed } from 'vue'
|
|
|
|
|
import { post } from '@/api/client'
|
|
|
|
|
|
|
|
|
|
interface OperatorInfo {
|
|
|
|
|
operatorId: string
|
|
|
|
|
name: string
|
|
|
|
|
username: string
|
|
|
|
|
permissions: string[]
|
|
|
|
|
organizationId: string | null
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useAuthStore = defineStore('auth', () => {
|
|
|
|
|
const token = ref<string>(localStorage.getItem('accessToken') || '')
|
|
|
|
|
const operator = ref<OperatorInfo | null>(
|
|
|
|
|
JSON.parse(localStorage.getItem('operator') || 'null')
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const isLoggedIn = computed(() => !!token.value)
|
|
|
|
|
const permissions = computed(() => operator.value?.permissions || [])
|
|
|
|
|
|
|
|
|
|
async function login(username: string, password: string) {
|
|
|
|
|
const res: any = await post('/auth/operator/login', { username, password })
|
|
|
|
|
if (res.success) {
|
2026-09-10 10:58:43 +08:00
|
|
|
token.value = res.data.accessToken
|
2026-09-09 22:05:00 +08:00
|
|
|
operator.value = {
|
|
|
|
|
operatorId: res.data.operatorId,
|
|
|
|
|
name: res.data.name,
|
|
|
|
|
username: res.data.username,
|
|
|
|
|
permissions: res.data.permissions || [],
|
2026-09-10 10:58:43 +08:00
|
|
|
organizationId: res.data.organizationId ?? null,
|
2026-09-09 22:05:00 +08:00
|
|
|
}
|
2026-09-10 10:58:43 +08:00
|
|
|
localStorage.setItem('accessToken', res.data.accessToken)
|
2026-09-09 22:05:00 +08:00
|
|
|
localStorage.setItem('operator', JSON.stringify(operator.value))
|
|
|
|
|
return res.data
|
|
|
|
|
}
|
|
|
|
|
throw new Error(res.message || '登录失败')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function logout() {
|
|
|
|
|
token.value = ''
|
|
|
|
|
operator.value = null
|
|
|
|
|
localStorage.removeItem('accessToken')
|
|
|
|
|
localStorage.removeItem('operator')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { token, operator, isLoggedIn, permissions, login, logout }
|
|
|
|
|
})
|