64 lines
1.4 KiB
TypeScript
64 lines
1.4 KiB
TypeScript
import { userProfile } from '~/api'
|
|
import type { IUser } from '~/types'
|
|
|
|
export const useLoginState = defineStore(
|
|
'loginState',
|
|
() => {
|
|
const isLoggedIn = ref(false)
|
|
|
|
const token = ref<string | null>(null)
|
|
const user = ref<IUser>({} as IUser)
|
|
|
|
const checkLogin = async (): Promise<IUser | false> => {
|
|
return new Promise((resolve, reject) => {
|
|
if (!token.value) {
|
|
user.value = {} as IUser
|
|
isLoggedIn.value = false
|
|
return reject(false)
|
|
}
|
|
userProfile()
|
|
.then((res) => {
|
|
if (res.code === 200) {
|
|
user.value = res.user
|
|
isLoggedIn.value = true
|
|
resolve(res.user)
|
|
}
|
|
else {
|
|
user.value = {} as IUser
|
|
isLoggedIn.value = false
|
|
token.value = null
|
|
reject(false)
|
|
}
|
|
})
|
|
.catch((_) => {
|
|
user.value = {} as IUser
|
|
isLoggedIn.value = false
|
|
token.value = null
|
|
reject(false)
|
|
})
|
|
})
|
|
}
|
|
|
|
const logout = () => {
|
|
isLoggedIn.value = false
|
|
token.value = null
|
|
user.value = {} as IUser
|
|
}
|
|
|
|
return {
|
|
isLoggedIn,
|
|
token,
|
|
user,
|
|
checkLogin,
|
|
logout,
|
|
}
|
|
},
|
|
{
|
|
persist: {
|
|
key: 'xshic_user_state',
|
|
storage: piniaPluginPersistedstate.localStorage(),
|
|
pick: ['isLoggedIn', 'token', 'user'],
|
|
},
|
|
},
|
|
)
|