UnisKB/ui/src/stores/modules/user.ts

106 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-10-19 10:18:45 +00:00
import { defineStore } from 'pinia'
2023-10-20 03:26:14 +00:00
import type { User } from '@/api/type/user'
2023-10-19 10:18:45 +00:00
import UserApi from '@/api/user'
2023-11-02 01:56:14 +00:00
export interface userStateTypes {
2023-11-30 10:50:42 +00:00
userType: number // 1 系统操作者 2 对话用户
2023-10-19 10:18:45 +00:00
userInfo: User | null
token: any
2024-03-21 08:26:03 +00:00
version?: string
accessToken?: string
2024-07-10 04:22:41 +00:00
XPACK_LICENSE_IS_VALID: false
isXPack: false
2023-10-19 10:18:45 +00:00
}
const useUserStore = defineStore({
id: 'user',
2023-11-02 01:56:14 +00:00
state: (): userStateTypes => ({
2023-11-30 10:50:42 +00:00
userType: 1,
2023-10-19 10:18:45 +00:00
userInfo: null,
2024-03-21 08:26:03 +00:00
token: '',
version: '',
2024-07-10 04:22:41 +00:00
XPACK_LICENSE_IS_VALID: false,
isXPack: false
2023-10-19 10:18:45 +00:00
}),
actions: {
2024-07-10 10:04:38 +00:00
isExpire() {
return this.isXPack && !this.XPACK_LICENSE_IS_VALID
},
isEnterprise() {
2024-07-10 04:22:41 +00:00
return this.isXPack && this.XPACK_LICENSE_IS_VALID
},
2023-10-19 10:18:45 +00:00
getToken(): String | null {
if (this.token) {
return this.token
}
return this.userType === 1 ? localStorage.getItem('token') : this.getAccessToken()
},
getAccessToken() {
const accessToken = sessionStorage.getItem('accessToken')
if (accessToken) {
return accessToken
}
return localStorage.getItem('accessToken')
2023-10-19 10:18:45 +00:00
},
getPermissions() {
if (this.userInfo) {
2024-07-10 04:22:41 +00:00
return this.isXPack && this.XPACK_LICENSE_IS_VALID
? [...this.userInfo?.permissions, 'x-pack']
: this.userInfo?.permissions
2023-10-19 10:18:45 +00:00
} else {
return []
}
},
getRole() {
if (this.userInfo) {
return this.userInfo?.role
} else {
return ''
}
},
2023-11-30 10:50:42 +00:00
changeUserType(num: number) {
this.userType = num
},
2024-03-21 08:26:03 +00:00
2024-07-11 10:28:01 +00:00
async asyncGetProfile() {
return new Promise((resolve, reject) => {
UserApi.getProfile()
.then((ok) => {
this.version = ok.data?.version || '-'
this.isXPack = ok.data?.IS_XPACK
this.XPACK_LICENSE_IS_VALID = ok.data?.XPACK_LICENSE_IS_VALID
resolve(ok)
})
.catch((error) => {
reject(error)
})
2024-03-21 08:26:03 +00:00
})
},
2023-10-19 10:18:45 +00:00
async profile() {
return UserApi.profile().then((ok) => {
this.userInfo = ok.data
2024-07-11 10:28:01 +00:00
this.asyncGetProfile()
2023-10-19 10:18:45 +00:00
})
},
async login(username: string, password: string) {
return UserApi.login({ username, password }).then((ok) => {
this.token = ok.data
localStorage.setItem('token', ok.data)
return this.profile()
})
},
async logout() {
return UserApi.logout().then(() => {
localStorage.removeItem('token')
return true
})
}
}
})
export default useUserStore