token刷新修改

This commit is contained in:
weiwei committed 2025-03-05 21:53:37 +08:00
1 parent f940aed342
commit fa8ec6a1ce
2 files changed
+163 -171

No files matched your search

+24 -18
View File
@@ -28,23 +28,29 @@ export const useStaticCheckLogin = () => {
export const useCheckLogin = async (): Promise<boolean> => {
const tokenKey = storageConstant.TOKEN
const tokenStorage = uni.getStorageSync(tokenKey)
if (tokenStorage) return true
uni.showModal({
title: "提示",
content: "您还未登录,请先登录",
confirmColor: "#0094ff",
cancelText: "取消",
confirmText: "去登录",
success: async (res) => {
if (res.confirm) {
isDevEnv() ? jump("/pages/test/login", {}, 3) : jump("/pages/tabbar/my", {}, 3)
if (isDevEnv()) {
if (tokenStorage) return true
uni.showModal({
title: "提示",
content: "您还未登录,请先登录",
confirmColor: "#0094ff",
cancelText: "取消",
confirmText: "去登录",
success: async (res) => {
if (res.confirm) {
jump("/pages/test/login", {}, 3)
return
}
if (!res.confirm) {
return
}
return
}
if (!res.confirm) {
return
}
return
},
})
return false
},
})
return false
} else {
if (tokenStorage) return true
uni.showToast({ title: "你还未登录", icon: "none" })
return false
}
}
+139 -153
View File
@@ -55,8 +55,64 @@ const getAuthHeader = (tokenStorage: any) => {
return tokenStorage?.accessToken?.tokenValue ? `Bearer ${tokenStorage.accessToken.tokenValue}` : null
}
// token过期刷新检查
const checkAndRefreshToken = async (tokenStorage: any) => {
const { accessToken } = tokenStorage
if (!accessToken) return
const expiresDate = new Date(accessToken.expiresAt).getTime()
console.log("现在的时间大于过期时间吗:", new Date().getTime() >= expiresDate)
if (new Date().getTime() >= expiresDate) {
// try {
// const refreshData: any = await request({
// url: "/auth/oauth2/token",
// method: "POST",
// params: { grant_type: "refresh_token" },
// data: JSON.stringify({
// scope: "server",
// refresh_token: tokenStorage.refreshToken.tokenValue,
// }),
// header: {
// skipToken: true,
// Authorization: "Basic " + window.btoa(import.meta.env.VITE_OAUTH2_APP_CLIENT),
// "content-type": "application/x-www-form-urlencoded",
// },
// })
// if (refreshData.code === 0 && !isEmpty(refreshData.data)) {
// console.log("refreshData.data", refreshData.data)
// // 刷新成功,更新token并重试请求
// uni.setStorageSync(TOKEN_KEY, refreshData.data)
// }
// } catch (refreshError) {
// console.error("Token refresh failed:", refreshError)
// }
try {
uni.showLoading({ title: "加载中...", mask: true })
const params = new URL(window.location.href).searchParams
const token = params.get("uabaseToken")
if (token) {
const res = await userApi.auth(token)
if (res?.code === 0) {
uni.setStorageSync(TOKEN_KEY, res.data)
} else {
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(USER_INFO_KEY)
uni.showToast({ title: res.msg, icon: "none" })
}
}
} catch (error) {
uni.showToast({ title: "错误", icon: "none" })
} finally {
uni.hideLoading()
}
}
}
// 请求拦截器
http.interceptors.request.use((config) => {
http.interceptors.request.use(async (config) => {
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
const config_header: any = config?.header || {}
@@ -66,14 +122,6 @@ http.interceptors.request.use((config) => {
config_header["CLIENT-TOC"] = "Y"
}
// 设置认证头
if (config.url !== "/sys/auth/refresh-token" && config.url !== "/auth/oauth2/token") {
const authHeader = getAuthHeader(tokenStorage)
if (authHeader) {
config_header.Authorization = authHeader
}
}
// 处理 loading
if (config.custom?.showLoading) {
LoadingInstance.count++
@@ -86,115 +134,67 @@ http.interceptors.request.use((config) => {
}
}
// 设置认证头
if (
!config.url?.startsWith("/thirdparty/thirdPartyOAth2/zzdsso") &&
config.url !== "/sys/auth/refresh-token" &&
config.url !== "/auth/oauth2/token"
) {
if (!isEmpty(tokenStorage)) {
// token过期刷新检查
checkAndRefreshToken(tokenStorage)
const authHeader = getAuthHeader(tokenStorage)
if (authHeader) {
config_header.Authorization = authHeader
}
} else {
// token不存在,则发起登录
const params = new URL(window.location.href).searchParams
const token = params.get("uabaseToken")
if (token) {
try {
uni.showLoading({ title: "加载中...", mask: true })
const res = await userApi.auth(token)
if (res?.code === 0) {
uni.setStorageSync(TOKEN_KEY, res.data)
const { data: userData } = await userApi.userInfo()
uni.setStorageSync(USER_INFO_KEY, userData)
const authHeader = getAuthHeader(tokenStorage)
if (authHeader) {
config_header.Authorization = authHeader
}
} else {
uni.showToast({ title: "获取浙政钉用户信息失败", icon: "none" })
}
} catch (error) {
uni.showToast({ title: "错误", icon: "none" })
} finally {
uni.hideLoading()
}
}
}
}
return config
}, Promise.reject)
// 定义响应处理的辅助函数
const responseHelpers = {
// 处理错误响应
handleErrorResponse(response: any) {
if (!response.config?.custom?.showError) return
// 处理错误响应
const handleErrorResponse = (response: any) => {
if (!response.config?.custom?.showError) return
switch (response.data.code) {
case 401:
this.handleUnauthorized()
break
case 424:
try {
const params = new URL(window.location.href).searchParams
const token = params.get("uabaseToken")
if (token) {
userApi.auth(token).then((res) => {
if (res?.code === 0) {
uni.setStorageSync(TOKEN_KEY, res.data)
} else {
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(USER_INFO_KEY)
// uni.showToast({ title: "登录已过期", icon: "none" })
return Promise.resolve({
code: 1,
data: "登录已过期",
msg: "登录已过期",
})
}
})
}
} catch (error) {
uni.hideLoading()
uni.showToast({ title: "错误", icon: "none" })
}
break
default:
uni.showToast({
title: response.data.msg || "服务器开小差啦,请稍后再试~",
icon: "none",
mask: true,
})
}
},
// 处理未授权情况
handleUnauthorized() {
setTimeout(() => {
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(USER_INFO_KEY)
router.jump("/pages/tabbar/my", {}, 2)
}, 500)
},
// 处理成功提示
handleSuccessMessage(response: any) {
const { data, config } = response
if (data.code === 0 && data.message && config?.custom?.showSuccess) {
uni.showToast({
title: config.custom.successMsg || data.message,
icon: "none",
})
}
},
// 处理登录过期
handleLoginExpired() {
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(USER_INFO_KEY)
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
isDevEnv() ? router.jump("/pages/test/login") : router.jump("/pages/tabbar/my")
},
// 检查并刷新token
checkAndRefreshToken(tokenStorage: any) {
const { accessToken } = tokenStorage
if (!accessToken) return
const issuedDate = new Date(accessToken.issuedAt).getTime()
console.log(new Date().getTime() - issuedDate)
if (new Date().getTime() - issuedDate >= 1000 * 60 * 20) {
// try {
// const refreshData: any = await request({
// url: "/auth/oauth2/token",
// method: "POST",
// params: { grant_type: "refresh_token" },
// data: JSON.stringify({
// scope: "server",
// refresh_token: tokenStorage.refreshToken.tokenValue,
// }),
// header: {
// skipToken: true,
// Authorization: "Basic " + window.btoa(import.meta.env.VITE_OAUTH2_APP_CLIENT),
// "content-type": "application/x-www-form-urlencoded",
// },
// })
// if (refreshData.code === 0 && !isEmpty(refreshData.data)) {
// console.log("refreshData.data", refreshData.data)
// // 刷新成功,更新token并重试请求
// uni.setStorageSync(TOKEN_KEY, refreshData.data)
// }
// } catch (refreshError) {
// console.error("Token refresh failed:", refreshError)
// }
switch (response.data.code) {
case 401:
// 处理未授权情况
setTimeout(() => {
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(USER_INFO_KEY)
console.log("未授权")
}, 500)
break
case 424:
try {
const params = new URL(window.location.href).searchParams
const token = params.get("uabaseToken")
@@ -218,15 +218,30 @@ const responseHelpers = {
uni.hideLoading()
uni.showToast({ title: "错误", icon: "none" })
}
}
},
break
default:
uni.showToast({
title: response.data.msg || "服务器开小差啦,请稍后再试~",
icon: "none",
mask: true,
})
}
}
// 处理成功提示
const handleSuccessMessage = (response: any) => {
const { data, config } = response
if (data.code === 0 && data.message && config?.custom?.showSuccess) {
uni.showToast({
title: config.custom.successMsg || data.message,
icon: "none",
})
}
}
// 响应拦截器
http.interceptors.response.use(
async (response) => {
console.log("response", response)
// 关闭loading
if (response.config?.custom?.showLoading) {
closeLoading()
@@ -241,45 +256,14 @@ http.interceptors.response.use(
})
}
// 错误处理
// 错误处理和错误提示
if (response.data.code !== 0) {
responseHelpers.handleErrorResponse(response)
handleErrorResponse(response)
return Promise.resolve(response.data)
}
// 成功提示
responseHelpers.handleSuccessMessage(response)
if (isEmpty(uni.getStorageSync(TOKEN_KEY))) {
const params = new URL(window.location.href).searchParams
const token = params.get("uabaseToken")
if (token) {
try {
userApi.auth(token).then(async (res) => {
if (res?.code === 0) {
uni.setStorageSync(TOKEN_KEY, res.data)
const { data: userData } = await userApi.userInfo()
uni.setStorageSync(USER_INFO_KEY, userData)
} else {
uni.showToast({ title: "获取浙政钉用户信息失败", icon: "none" })
}
})
} catch (error) {
uni.showToast({ title: "错误", icon: "none" })
}
}
}
// 登录过期处理
if (response.data.code === 1) {
responseHelpers.handleLoginExpired()
}
// Token 刷新检查
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
if (!isEmpty(tokenStorage) && !response.config.url?.startsWith("/thirdparty/thirdPartyOAth2/zzdsso")) {
await responseHelpers.checkAndRefreshToken(tokenStorage)
}
handleSuccessMessage(response)
return Promise.resolve(response.data)
},
@@ -295,6 +279,7 @@ http.interceptors.response.use(
return false
} else {
try {
uni.showLoading({ title: "加载中...", mask: true })
const params = new URL(window.location.href).searchParams
const token = params.get("uabaseToken")
if (token) {
@@ -314,8 +299,9 @@ http.interceptors.response.use(
})
}
} catch (error) {
uni.hideLoading()
uni.showToast({ title: "错误", icon: "none" })
} finally {
uni.hideLoading()
}
}
}