mirror of
https://gitee.com/ulthon/ulthon_admin.git
synced 2026-07-07 10:32:48 +08:00
feat(uniapp): 集成 Pinia 状态管理并实现用户认证流程
This commit is contained in:
@@ -1,18 +1,39 @@
|
||||
import { clearToken, getToken } from './auth'
|
||||
import { env } from '../config/env'
|
||||
import { pinia } from '../store'
|
||||
import { useUserStore } from '../store/user'
|
||||
|
||||
const BASE_URL = ''
|
||||
const AUTH_REQUIRED_CODE = 40101
|
||||
const AUTH_EXPIRED_CODE = 40102
|
||||
|
||||
function buildUrl(url) {
|
||||
if (!url) return ''
|
||||
if (/^https?:\/\//i.test(url)) return url
|
||||
if (url.startsWith('/')) return `${BASE_URL}${url}`
|
||||
return `${BASE_URL}/${url}`
|
||||
const baseUrl = env.apiBaseUrl || ''
|
||||
if (url.startsWith('/')) return `${baseUrl}${url}`
|
||||
return `${baseUrl}/${url}`
|
||||
}
|
||||
|
||||
function isLoginError(resData) {
|
||||
const msg = (resData && resData.msg) || ''
|
||||
const url = (resData && resData.url) || ''
|
||||
return msg.includes('请先登录') || msg.includes('登录已过期') || url.includes('/admin/login')
|
||||
function getCurrentRoutePath() {
|
||||
try {
|
||||
const pages = getCurrentPages()
|
||||
const current = pages && pages[pages.length - 1]
|
||||
const route = (current && (current.route || (current.$page && current.$page.fullPath))) || ''
|
||||
return String(route)
|
||||
} catch (e) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function redirectToLoginIfNeeded() {
|
||||
const route = getCurrentRoutePath()
|
||||
if (route.includes('pages/login/index')) return
|
||||
|
||||
uni.navigateTo({
|
||||
url: '/pages/login/index',
|
||||
fail: () => {
|
||||
uni.reLaunch({ url: '/pages/login/index' })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function request(options) {
|
||||
@@ -24,7 +45,9 @@ export function request(options) {
|
||||
...(options.header || {}),
|
||||
}
|
||||
|
||||
const token = getToken()
|
||||
const userStore = useUserStore(pinia)
|
||||
userStore.init()
|
||||
const token = userStore.token
|
||||
if (token && !header.Authorization) {
|
||||
header.Authorization = `Bearer ${token}`
|
||||
}
|
||||
@@ -39,7 +62,7 @@ export function request(options) {
|
||||
method,
|
||||
data: options.data || {},
|
||||
header,
|
||||
timeout: options.timeout || 60000,
|
||||
timeout: options.timeout || env.timeout || 60000,
|
||||
success: (res) => {
|
||||
const resData = res.data
|
||||
|
||||
@@ -61,9 +84,9 @@ export function request(options) {
|
||||
return
|
||||
}
|
||||
|
||||
if (isLoginError(resData)) {
|
||||
clearToken()
|
||||
uni.navigateTo({ url: '/pages/login/index' })
|
||||
if (resData.code === AUTH_REQUIRED_CODE || resData.code === AUTH_EXPIRED_CODE) {
|
||||
userStore.logout()
|
||||
redirectToLoginIfNeeded()
|
||||
}
|
||||
|
||||
uni.showToast({ title: resData.msg || '请求失败', icon: 'none' })
|
||||
@@ -80,4 +103,3 @@ export function request(options) {
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user